blob: 4a0494295d2a8b8419d75014e04b707559e30680 [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
13#include "CodeGenFunction.h"
John McCall5d865c322010-08-31 07:33:07 +000014#include "CGCXXABI.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000015#include "CGObjCRuntime.h"
Daniel Dunbar072d0bb2010-03-30 22:26:10 +000016#include "CGRecordLayout.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"
Anders Carlssone1d5ca52009-07-24 15:20:52 +000022#include "clang/AST/RecordLayout.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000023#include "clang/AST/StmtVisitor.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Richard Smith5745feb2019-06-17 21:08:30 +000025#include "llvm/ADT/Sequence.h"
26#include "llvm/ADT/STLExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000027#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/GlobalVariable.h"
Anders Carlsson610ee712008-01-26 01:36:00 +000031using namespace clang;
32using namespace CodeGen;
33
Chris Lattnercfa3e7a2010-04-13 17:45:57 +000034//===----------------------------------------------------------------------===//
Richard Smith5745feb2019-06-17 21:08:30 +000035// ConstantAggregateBuilder
Chris Lattnercfa3e7a2010-04-13 17:45:57 +000036//===----------------------------------------------------------------------===//
37
38namespace {
Yunzhong Gaocb779302015-06-10 00:27:52 +000039class ConstExprEmitter;
Richard Smith5745feb2019-06-17 21:08:30 +000040
41struct ConstantAggregateBuilderUtils {
Anders Carlssone1d5ca52009-07-24 15:20:52 +000042 CodeGenModule &CGM;
Anders Carlssone1d5ca52009-07-24 15:20:52 +000043
Richard Smith5745feb2019-06-17 21:08:30 +000044 ConstantAggregateBuilderUtils(CodeGenModule &CGM) : CGM(CGM) {}
Mike Stump11289f42009-09-09 15:08:12 +000045
Ken Dycka1b35102011-03-18 01:26:17 +000046 CharUnits getAlignment(const llvm::Constant *C) const {
Ken Dycka1b35102011-03-18 01:26:17 +000047 return CharUnits::fromQuantity(
Micah Villmowdd31ca12012-10-08 16:25:52 +000048 CGM.getDataLayout().getABITypeAlignment(C->getType()));
Anders Carlssone1d5ca52009-07-24 15:20:52 +000049 }
Mike Stump11289f42009-09-09 15:08:12 +000050
Richard Smith5745feb2019-06-17 21:08:30 +000051 CharUnits getSize(llvm::Type *Ty) const {
52 return CharUnits::fromQuantity(CGM.getDataLayout().getTypeAllocSize(Ty));
53 }
54
55 CharUnits getSize(const llvm::Constant *C) const {
56 return getSize(C->getType());
57 }
58
59 llvm::Constant *getPadding(CharUnits PadSize) const {
60 llvm::Type *Ty = CGM.Int8Ty;
61 if (PadSize > CharUnits::One())
62 Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
63 return llvm::UndefValue::get(Ty);
64 }
65
66 llvm::Constant *getZeroes(CharUnits ZeroSize) const {
67 llvm::Type *Ty = llvm::ArrayType::get(CGM.Int8Ty, ZeroSize.getQuantity());
68 return llvm::ConstantAggregateZero::get(Ty);
Anders Carlssone1d5ca52009-07-24 15:20:52 +000069 }
Anders Carlssone1d5ca52009-07-24 15:20:52 +000070};
Mike Stump11289f42009-09-09 15:08:12 +000071
Richard Smith5745feb2019-06-17 21:08:30 +000072/// Incremental builder for an llvm::Constant* holding a struct or array
73/// constant.
74class ConstantAggregateBuilder : private ConstantAggregateBuilderUtils {
75 /// The elements of the constant. These two arrays must have the same size;
76 /// Offsets[i] describes the offset of Elems[i] within the constant. The
77 /// elements are kept in increasing offset order, and we ensure that there
78 /// is no overlap: Offsets[i+1] >= Offsets[i] + getSize(Elemes[i]).
79 ///
80 /// This may contain explicit padding elements (in order to create a
81 /// natural layout), but need not. Gaps between elements are implicitly
82 /// considered to be filled with undef.
83 llvm::SmallVector<llvm::Constant*, 32> Elems;
84 llvm::SmallVector<CharUnits, 32> Offsets;
85
86 /// The size of the constant (the maximum end offset of any added element).
87 /// May be larger than the end of Elems.back() if we split the last element
88 /// and removed some trailing undefs.
89 CharUnits Size = CharUnits::Zero();
90
91 /// This is true only if laying out Elems in order as the elements of a
92 /// non-packed LLVM struct will give the correct layout.
93 bool NaturalLayout = true;
94
95 bool split(size_t Index, CharUnits Hint);
96 Optional<size_t> splitAt(CharUnits Pos);
97
98 static llvm::Constant *buildFrom(CodeGenModule &CGM,
99 ArrayRef<llvm::Constant *> Elems,
100 ArrayRef<CharUnits> Offsets,
101 CharUnits StartOffset, CharUnits Size,
102 bool NaturalLayout, llvm::Type *DesiredTy,
103 bool AllowOversized);
104
105public:
106 ConstantAggregateBuilder(CodeGenModule &CGM)
107 : ConstantAggregateBuilderUtils(CGM) {}
108
109 /// Update or overwrite the value starting at \p Offset with \c C.
110 ///
111 /// \param AllowOverwrite If \c true, this constant might overwrite (part of)
112 /// a constant that has already been added. This flag is only used to
113 /// detect bugs.
114 bool add(llvm::Constant *C, CharUnits Offset, bool AllowOverwrite);
115
116 /// Update or overwrite the bits starting at \p OffsetInBits with \p Bits.
117 bool addBits(llvm::APInt Bits, uint64_t OffsetInBits, bool AllowOverwrite);
118
119 /// Attempt to condense the value starting at \p Offset to a constant of type
120 /// \p DesiredTy.
121 void condense(CharUnits Offset, llvm::Type *DesiredTy);
122
123 /// Produce a constant representing the entire accumulated value, ideally of
124 /// the specified type. If \p AllowOversized, the constant might be larger
125 /// than implied by \p DesiredTy (eg, if there is a flexible array member).
126 /// Otherwise, the constant will be of exactly the same size as \p DesiredTy
127 /// even if we can't represent it as that type.
128 llvm::Constant *build(llvm::Type *DesiredTy, bool AllowOversized) const {
129 return buildFrom(CGM, Elems, Offsets, CharUnits::Zero(), Size,
130 NaturalLayout, DesiredTy, AllowOversized);
131 }
132};
133
134template<typename Container, typename Range = std::initializer_list<
135 typename Container::value_type>>
136static void replace(Container &C, size_t BeginOff, size_t EndOff, Range Vals) {
137 assert(BeginOff <= EndOff && "invalid replacement range");
138 llvm::replace(C, C.begin() + BeginOff, C.begin() + EndOff, Vals);
139}
140
141bool ConstantAggregateBuilder::add(llvm::Constant *C, CharUnits Offset,
142 bool AllowOverwrite) {
143 // Common case: appending to a layout.
144 if (Offset >= Size) {
145 CharUnits Align = getAlignment(C);
146 CharUnits AlignedSize = Size.alignTo(Align);
147 if (AlignedSize > Offset || Offset.alignTo(Align) != Offset)
148 NaturalLayout = false;
149 else if (AlignedSize < Offset) {
150 Elems.push_back(getPadding(Offset - Size));
151 Offsets.push_back(Size);
152 }
153 Elems.push_back(C);
154 Offsets.push_back(Offset);
155 Size = Offset + getSize(C);
156 return true;
157 }
158
159 // Uncommon case: constant overlaps what we've already created.
160 llvm::Optional<size_t> FirstElemToReplace = splitAt(Offset);
161 if (!FirstElemToReplace)
162 return false;
163
164 CharUnits CSize = getSize(C);
165 llvm::Optional<size_t> LastElemToReplace = splitAt(Offset + CSize);
166 if (!LastElemToReplace)
167 return false;
168
169 assert((FirstElemToReplace == LastElemToReplace || AllowOverwrite) &&
170 "unexpectedly overwriting field");
171
172 replace(Elems, *FirstElemToReplace, *LastElemToReplace, {C});
173 replace(Offsets, *FirstElemToReplace, *LastElemToReplace, {Offset});
174 Size = std::max(Size, Offset + CSize);
175 NaturalLayout = false;
176 return true;
177}
178
179bool ConstantAggregateBuilder::addBits(llvm::APInt Bits, uint64_t OffsetInBits,
180 bool AllowOverwrite) {
181 const ASTContext &Context = CGM.getContext();
182 const uint64_t CharWidth = CGM.getContext().getCharWidth();
183
184 // Offset of where we want the first bit to go within the bits of the
185 // current char.
186 unsigned OffsetWithinChar = OffsetInBits % CharWidth;
187
188 // We split bit-fields up into individual bytes. Walk over the bytes and
189 // update them.
Richard Smith780c3742019-06-22 20:41:57 +0000190 for (CharUnits OffsetInChars =
191 Context.toCharUnitsFromBits(OffsetInBits - OffsetWithinChar);
Richard Smith5745feb2019-06-17 21:08:30 +0000192 /**/; ++OffsetInChars) {
193 // Number of bits we want to fill in this char.
194 unsigned WantedBits =
195 std::min((uint64_t)Bits.getBitWidth(), CharWidth - OffsetWithinChar);
196
197 // Get a char containing the bits we want in the right places. The other
198 // bits have unspecified values.
199 llvm::APInt BitsThisChar = Bits;
200 if (BitsThisChar.getBitWidth() < CharWidth)
201 BitsThisChar = BitsThisChar.zext(CharWidth);
202 if (CGM.getDataLayout().isBigEndian()) {
203 // Figure out how much to shift by. We may need to left-shift if we have
204 // less than one byte of Bits left.
205 int Shift = Bits.getBitWidth() - CharWidth + OffsetWithinChar;
206 if (Shift > 0)
207 BitsThisChar.lshrInPlace(Shift);
208 else if (Shift < 0)
209 BitsThisChar = BitsThisChar.shl(-Shift);
210 } else {
211 BitsThisChar = BitsThisChar.shl(OffsetWithinChar);
212 }
213 if (BitsThisChar.getBitWidth() > CharWidth)
214 BitsThisChar = BitsThisChar.trunc(CharWidth);
215
216 if (WantedBits == CharWidth) {
217 // Got a full byte: just add it directly.
218 add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar),
219 OffsetInChars, AllowOverwrite);
220 } else {
221 // Partial byte: update the existing integer if there is one. If we
222 // can't split out a 1-CharUnit range to update, then we can't add
223 // these bits and fail the entire constant emission.
224 llvm::Optional<size_t> FirstElemToUpdate = splitAt(OffsetInChars);
225 if (!FirstElemToUpdate)
226 return false;
227 llvm::Optional<size_t> LastElemToUpdate =
228 splitAt(OffsetInChars + CharUnits::One());
229 if (!LastElemToUpdate)
230 return false;
231 assert(*LastElemToUpdate - *FirstElemToUpdate < 2 &&
232 "should have at most one element covering one byte");
233
234 // Figure out which bits we want and discard the rest.
235 llvm::APInt UpdateMask(CharWidth, 0);
236 if (CGM.getDataLayout().isBigEndian())
237 UpdateMask.setBits(CharWidth - OffsetWithinChar - WantedBits,
238 CharWidth - OffsetWithinChar);
239 else
240 UpdateMask.setBits(OffsetWithinChar, OffsetWithinChar + WantedBits);
241 BitsThisChar &= UpdateMask;
242
243 if (*FirstElemToUpdate == *LastElemToUpdate ||
244 Elems[*FirstElemToUpdate]->isNullValue() ||
245 isa<llvm::UndefValue>(Elems[*FirstElemToUpdate])) {
246 // All existing bits are either zero or undef.
247 add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar),
248 OffsetInChars, /*AllowOverwrite*/ true);
249 } else {
250 llvm::Constant *&ToUpdate = Elems[*FirstElemToUpdate];
251 // In order to perform a partial update, we need the existing bitwise
252 // value, which we can only extract for a constant int.
253 auto *CI = dyn_cast<llvm::ConstantInt>(ToUpdate);
254 if (!CI)
255 return false;
256 // Because this is a 1-CharUnit range, the constant occupying it must
257 // be exactly one CharUnit wide.
258 assert(CI->getBitWidth() == CharWidth && "splitAt failed");
259 assert((!(CI->getValue() & UpdateMask) || AllowOverwrite) &&
260 "unexpectedly overwriting bitfield");
261 BitsThisChar |= (CI->getValue() & ~UpdateMask);
262 ToUpdate = llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar);
263 }
264 }
265
266 // Stop if we've added all the bits.
267 if (WantedBits == Bits.getBitWidth())
268 break;
269
270 // Remove the consumed bits from Bits.
271 if (!CGM.getDataLayout().isBigEndian())
272 Bits.lshrInPlace(WantedBits);
273 Bits = Bits.trunc(Bits.getBitWidth() - WantedBits);
274
275 // The remanining bits go at the start of the following bytes.
276 OffsetWithinChar = 0;
277 }
278
279 return true;
280}
281
282/// Returns a position within Elems and Offsets such that all elements
283/// before the returned index end before Pos and all elements at or after
284/// the returned index begin at or after Pos. Splits elements as necessary
285/// to ensure this. Returns None if we find something we can't split.
286Optional<size_t> ConstantAggregateBuilder::splitAt(CharUnits Pos) {
287 if (Pos >= Size)
288 return Offsets.size();
289
290 while (true) {
291 auto FirstAfterPos = std::upper_bound(Offsets.begin(), Offsets.end(), Pos);
292 if (FirstAfterPos == Offsets.begin())
293 return 0;
294
295 // If we already have an element starting at Pos, we're done.
296 size_t LastAtOrBeforePosIndex = FirstAfterPos - Offsets.begin() - 1;
297 if (Offsets[LastAtOrBeforePosIndex] == Pos)
298 return LastAtOrBeforePosIndex;
299
300 // We found an element starting before Pos. Check for overlap.
301 if (Offsets[LastAtOrBeforePosIndex] +
302 getSize(Elems[LastAtOrBeforePosIndex]) <= Pos)
303 return LastAtOrBeforePosIndex + 1;
304
305 // Try to decompose it into smaller constants.
306 if (!split(LastAtOrBeforePosIndex, Pos))
307 return None;
308 }
309}
310
311/// Split the constant at index Index, if possible. Return true if we did.
312/// Hint indicates the location at which we'd like to split, but may be
313/// ignored.
314bool ConstantAggregateBuilder::split(size_t Index, CharUnits Hint) {
315 NaturalLayout = false;
316 llvm::Constant *C = Elems[Index];
317 CharUnits Offset = Offsets[Index];
318
319 if (auto *CA = dyn_cast<llvm::ConstantAggregate>(C)) {
320 replace(Elems, Index, Index + 1,
321 llvm::map_range(llvm::seq(0u, CA->getNumOperands()),
322 [&](unsigned Op) { return CA->getOperand(Op); }));
323 if (auto *Seq = dyn_cast<llvm::SequentialType>(CA->getType())) {
324 // Array or vector.
325 CharUnits ElemSize = getSize(Seq->getElementType());
326 replace(
327 Offsets, Index, Index + 1,
328 llvm::map_range(llvm::seq(0u, CA->getNumOperands()),
329 [&](unsigned Op) { return Offset + Op * ElemSize; }));
330 } else {
331 // Must be a struct.
332 auto *ST = cast<llvm::StructType>(CA->getType());
333 const llvm::StructLayout *Layout =
334 CGM.getDataLayout().getStructLayout(ST);
335 replace(Offsets, Index, Index + 1,
336 llvm::map_range(
337 llvm::seq(0u, CA->getNumOperands()), [&](unsigned Op) {
338 return Offset + CharUnits::fromQuantity(
339 Layout->getElementOffset(Op));
340 }));
341 }
342 return true;
343 }
344
345 if (auto *CDS = dyn_cast<llvm::ConstantDataSequential>(C)) {
346 // FIXME: If possible, split into two ConstantDataSequentials at Hint.
347 CharUnits ElemSize = getSize(CDS->getElementType());
348 replace(Elems, Index, Index + 1,
349 llvm::map_range(llvm::seq(0u, CDS->getNumElements()),
350 [&](unsigned Elem) {
351 return CDS->getElementAsConstant(Elem);
352 }));
353 replace(Offsets, Index, Index + 1,
354 llvm::map_range(
355 llvm::seq(0u, CDS->getNumElements()),
356 [&](unsigned Elem) { return Offset + Elem * ElemSize; }));
357 return true;
358 }
359
Mikael Holmen5136ea42019-06-18 06:41:56 +0000360 if (isa<llvm::ConstantAggregateZero>(C)) {
Richard Smith5745feb2019-06-17 21:08:30 +0000361 CharUnits ElemSize = getSize(C);
362 assert(Hint > Offset && Hint < Offset + ElemSize && "nothing to split");
363 replace(Elems, Index, Index + 1,
364 {getZeroes(Hint - Offset), getZeroes(Offset + ElemSize - Hint)});
365 replace(Offsets, Index, Index + 1, {Offset, Hint});
366 return true;
367 }
368
369 if (isa<llvm::UndefValue>(C)) {
370 replace(Elems, Index, Index + 1, {});
371 replace(Offsets, Index, Index + 1, {});
372 return true;
373 }
374
375 // FIXME: We could split a ConstantInt if the need ever arose.
376 // We don't need to do this to handle bit-fields because we always eagerly
377 // split them into 1-byte chunks.
378
379 return false;
380}
381
382static llvm::Constant *
383EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,
384 llvm::Type *CommonElementType, unsigned ArrayBound,
385 SmallVectorImpl<llvm::Constant *> &Elements,
386 llvm::Constant *Filler);
387
388llvm::Constant *ConstantAggregateBuilder::buildFrom(
389 CodeGenModule &CGM, ArrayRef<llvm::Constant *> Elems,
390 ArrayRef<CharUnits> Offsets, CharUnits StartOffset, CharUnits Size,
391 bool NaturalLayout, llvm::Type *DesiredTy, bool AllowOversized) {
392 ConstantAggregateBuilderUtils Utils(CGM);
393
394 if (Elems.empty())
395 return llvm::UndefValue::get(DesiredTy);
396
397 auto Offset = [&](size_t I) { return Offsets[I] - StartOffset; };
398
399 // If we want an array type, see if all the elements are the same type and
400 // appropriately spaced.
401 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(DesiredTy)) {
402 assert(!AllowOversized && "oversized array emission not supported");
403
404 bool CanEmitArray = true;
405 llvm::Type *CommonType = Elems[0]->getType();
406 llvm::Constant *Filler = llvm::Constant::getNullValue(CommonType);
407 CharUnits ElemSize = Utils.getSize(ATy->getElementType());
408 SmallVector<llvm::Constant*, 32> ArrayElements;
409 for (size_t I = 0; I != Elems.size(); ++I) {
410 // Skip zeroes; we'll use a zero value as our array filler.
411 if (Elems[I]->isNullValue())
412 continue;
413
414 // All remaining elements must be the same type.
415 if (Elems[I]->getType() != CommonType ||
416 Offset(I) % ElemSize != 0) {
417 CanEmitArray = false;
418 break;
419 }
420 ArrayElements.resize(Offset(I) / ElemSize + 1, Filler);
421 ArrayElements.back() = Elems[I];
422 }
423
424 if (CanEmitArray) {
425 return EmitArrayConstant(CGM, ATy, CommonType, ATy->getNumElements(),
426 ArrayElements, Filler);
427 }
428
429 // Can't emit as an array, carry on to emit as a struct.
430 }
431
432 CharUnits DesiredSize = Utils.getSize(DesiredTy);
433 CharUnits Align = CharUnits::One();
434 for (llvm::Constant *C : Elems)
435 Align = std::max(Align, Utils.getAlignment(C));
436 CharUnits AlignedSize = Size.alignTo(Align);
437
438 bool Packed = false;
439 ArrayRef<llvm::Constant*> UnpackedElems = Elems;
440 llvm::SmallVector<llvm::Constant*, 32> UnpackedElemStorage;
441 if ((DesiredSize < AlignedSize && !AllowOversized) ||
442 DesiredSize.alignTo(Align) != DesiredSize) {
443 // The natural layout would be the wrong size; force use of a packed layout.
444 NaturalLayout = false;
445 Packed = true;
446 } else if (DesiredSize > AlignedSize) {
447 // The constant would be too small. Add padding to fix it.
448 UnpackedElemStorage.assign(Elems.begin(), Elems.end());
449 UnpackedElemStorage.push_back(Utils.getPadding(DesiredSize - Size));
450 UnpackedElems = UnpackedElemStorage;
451 }
452
453 // If we don't have a natural layout, insert padding as necessary.
454 // As we go, double-check to see if we can actually just emit Elems
455 // as a non-packed struct and do so opportunistically if possible.
456 llvm::SmallVector<llvm::Constant*, 32> PackedElems;
457 if (!NaturalLayout) {
458 CharUnits SizeSoFar = CharUnits::Zero();
459 for (size_t I = 0; I != Elems.size(); ++I) {
460 CharUnits Align = Utils.getAlignment(Elems[I]);
461 CharUnits NaturalOffset = SizeSoFar.alignTo(Align);
462 CharUnits DesiredOffset = Offset(I);
463 assert(DesiredOffset >= SizeSoFar && "elements out of order");
464
465 if (DesiredOffset != NaturalOffset)
466 Packed = true;
467 if (DesiredOffset != SizeSoFar)
468 PackedElems.push_back(Utils.getPadding(DesiredOffset - SizeSoFar));
469 PackedElems.push_back(Elems[I]);
470 SizeSoFar = DesiredOffset + Utils.getSize(Elems[I]);
471 }
472 // If we're using the packed layout, pad it out to the desired size if
473 // necessary.
474 if (Packed) {
475 assert((SizeSoFar <= DesiredSize || AllowOversized) &&
476 "requested size is too small for contents");
477 if (SizeSoFar < DesiredSize)
478 PackedElems.push_back(Utils.getPadding(DesiredSize - SizeSoFar));
479 }
480 }
481
482 llvm::StructType *STy = llvm::ConstantStruct::getTypeForElements(
483 CGM.getLLVMContext(), Packed ? PackedElems : UnpackedElems, Packed);
484
485 // Pick the type to use. If the type is layout identical to the desired
486 // type then use it, otherwise use whatever the builder produced for us.
487 if (llvm::StructType *DesiredSTy = dyn_cast<llvm::StructType>(DesiredTy)) {
488 if (DesiredSTy->isLayoutIdentical(STy))
489 STy = DesiredSTy;
490 }
491
492 return llvm::ConstantStruct::get(STy, Packed ? PackedElems : UnpackedElems);
493}
494
495void ConstantAggregateBuilder::condense(CharUnits Offset,
496 llvm::Type *DesiredTy) {
497 CharUnits Size = getSize(DesiredTy);
498
499 llvm::Optional<size_t> FirstElemToReplace = splitAt(Offset);
500 if (!FirstElemToReplace)
501 return;
502 size_t First = *FirstElemToReplace;
503
504 llvm::Optional<size_t> LastElemToReplace = splitAt(Offset + Size);
505 if (!LastElemToReplace)
506 return;
507 size_t Last = *LastElemToReplace;
508
509 size_t Length = Last - First;
510 if (Length == 0)
511 return;
512
513 if (Length == 1 && Offsets[First] == Offset &&
514 getSize(Elems[First]) == Size) {
515 // Re-wrap single element structs if necessary. Otherwise, leave any single
516 // element constant of the right size alone even if it has the wrong type.
517 auto *STy = dyn_cast<llvm::StructType>(DesiredTy);
518 if (STy && STy->getNumElements() == 1 &&
519 STy->getElementType(0) == Elems[First]->getType())
520 Elems[First] = llvm::ConstantStruct::get(STy, Elems[First]);
521 return;
522 }
523
524 llvm::Constant *Replacement = buildFrom(
525 CGM, makeArrayRef(Elems).slice(First, Length),
526 makeArrayRef(Offsets).slice(First, Length), Offset, getSize(DesiredTy),
527 /*known to have natural layout=*/false, DesiredTy, false);
528 replace(Elems, First, Last, {Replacement});
529 replace(Offsets, First, Last, {Offset});
530}
531
532//===----------------------------------------------------------------------===//
533// ConstStructBuilder
534//===----------------------------------------------------------------------===//
535
536class ConstStructBuilder {
537 CodeGenModule &CGM;
538 ConstantEmitter &Emitter;
539 ConstantAggregateBuilder &Builder;
540 CharUnits StartOffset;
541
542public:
543 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
544 InitListExpr *ILE, QualType StructTy);
545 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
546 const APValue &Value, QualType ValTy);
547 static bool UpdateStruct(ConstantEmitter &Emitter,
548 ConstantAggregateBuilder &Const, CharUnits Offset,
549 InitListExpr *Updater);
550
551private:
552 ConstStructBuilder(ConstantEmitter &Emitter,
553 ConstantAggregateBuilder &Builder, CharUnits StartOffset)
554 : CGM(Emitter.CGM), Emitter(Emitter), Builder(Builder),
555 StartOffset(StartOffset) {}
556
557 bool AppendField(const FieldDecl *Field, uint64_t FieldOffset,
558 llvm::Constant *InitExpr, bool AllowOverwrite = false);
559
560 bool AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst,
561 bool AllowOverwrite = false);
562
563 bool AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
564 llvm::ConstantInt *InitExpr, bool AllowOverwrite = false);
565
566 bool Build(InitListExpr *ILE, bool AllowOverwrite);
567 bool Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
568 const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
569 llvm::Constant *Finalize(QualType Ty);
570};
571
572bool ConstStructBuilder::AppendField(
573 const FieldDecl *Field, uint64_t FieldOffset, llvm::Constant *InitCst,
574 bool AllowOverwrite) {
Ken Dyck1c80fd12011-03-15 01:09:02 +0000575 const ASTContext &Context = CGM.getContext();
576
577 CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000578
Richard Smith5745feb2019-06-17 21:08:30 +0000579 return AppendBytes(FieldOffsetInChars, InitCst, AllowOverwrite);
Richard Smithc8998922012-02-23 08:33:23 +0000580}
581
Richard Smith5745feb2019-06-17 21:08:30 +0000582bool ConstStructBuilder::AppendBytes(CharUnits FieldOffsetInChars,
583 llvm::Constant *InitCst,
584 bool AllowOverwrite) {
585 return Builder.add(InitCst, StartOffset + FieldOffsetInChars, AllowOverwrite);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000586}
587
Richard Smith5745feb2019-06-17 21:08:30 +0000588bool ConstStructBuilder::AppendBitField(
589 const FieldDecl *Field, uint64_t FieldOffset, llvm::ConstantInt *CI,
590 bool AllowOverwrite) {
591 uint64_t FieldSize = Field->getBitWidthValue(CGM.getContext());
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000592 llvm::APInt FieldValue = CI->getValue();
593
594 // Promote the size of FieldValue if necessary
595 // FIXME: This should never occur, but currently it can because initializer
596 // constants are cast to bool, and because clang is not enforcing bitfield
597 // width limits.
598 if (FieldSize > FieldValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +0000599 FieldValue = FieldValue.zext(FieldSize);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000600
601 // Truncate the size of FieldValue to the bit field size.
602 if (FieldSize < FieldValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +0000603 FieldValue = FieldValue.trunc(FieldSize);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000604
Richard Smith5745feb2019-06-17 21:08:30 +0000605 return Builder.addBits(FieldValue,
606 CGM.getContext().toBits(StartOffset) + FieldOffset,
607 AllowOverwrite);
608}
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000609
Richard Smith5745feb2019-06-17 21:08:30 +0000610static bool EmitDesignatedInitUpdater(ConstantEmitter &Emitter,
611 ConstantAggregateBuilder &Const,
612 CharUnits Offset, QualType Type,
613 InitListExpr *Updater) {
614 if (Type->isRecordType())
615 return ConstStructBuilder::UpdateStruct(Emitter, Const, Offset, Updater);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000616
Richard Smith5745feb2019-06-17 21:08:30 +0000617 auto CAT = Emitter.CGM.getContext().getAsConstantArrayType(Type);
618 if (!CAT)
619 return false;
620 QualType ElemType = CAT->getElementType();
621 CharUnits ElemSize = Emitter.CGM.getContext().getTypeSizeInChars(ElemType);
622 llvm::Type *ElemTy = Emitter.CGM.getTypes().ConvertTypeForMem(ElemType);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000623
Richard Smith5745feb2019-06-17 21:08:30 +0000624 llvm::Constant *FillC = nullptr;
625 if (Expr *Filler = Updater->getArrayFiller()) {
626 if (!isa<NoInitExpr>(Filler)) {
627 FillC = Emitter.tryEmitAbstractForMemory(Filler, ElemType);
628 if (!FillC)
629 return false;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000630 }
Richard Smith5745feb2019-06-17 21:08:30 +0000631 }
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000632
Richard Smith5745feb2019-06-17 21:08:30 +0000633 unsigned NumElementsToUpdate =
634 FillC ? CAT->getSize().getZExtValue() : Updater->getNumInits();
635 for (unsigned I = 0; I != NumElementsToUpdate; ++I, Offset += ElemSize) {
636 Expr *Init = nullptr;
637 if (I < Updater->getNumInits())
638 Init = Updater->getInit(I);
639
640 if (!Init && FillC) {
641 if (!Const.add(FillC, Offset, true))
642 return false;
643 } else if (!Init || isa<NoInitExpr>(Init)) {
644 continue;
645 } else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init)) {
646 if (!EmitDesignatedInitUpdater(Emitter, Const, Offset, ElemType,
647 ChildILE))
648 return false;
649 // Attempt to reduce the array element to a single constant if necessary.
650 Const.condense(Offset, ElemTy);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000651 } else {
Richard Smith5745feb2019-06-17 21:08:30 +0000652 llvm::Constant *Val = Emitter.tryEmitPrivateForMemory(Init, ElemType);
653 if (!Const.add(Val, Offset, true))
654 return false;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000655 }
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000656 }
657
Richard Smith5745feb2019-06-17 21:08:30 +0000658 return true;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000659}
660
Richard Smith5745feb2019-06-17 21:08:30 +0000661bool ConstStructBuilder::Build(InitListExpr *ILE, bool AllowOverwrite) {
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000662 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
663 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
664
Richard Smith5745feb2019-06-17 21:08:30 +0000665 unsigned FieldNo = -1;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000666 unsigned ElementNo = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000667
668 // Bail out if we have base classes. We could support these, but they only
669 // arise in C++1z where we will have already constant folded most interesting
670 // cases. FIXME: There are still a few more cases we can handle this way.
671 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
672 if (CXXRD->getNumBases())
673 return false;
674
Richard Smith5745feb2019-06-17 21:08:30 +0000675 for (FieldDecl *Field : RD->fields()) {
676 ++FieldNo;
677
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000678 // If this is a union, skip all the fields that aren't being initialized.
Richard Smith78b239e2019-06-20 20:44:45 +0000679 if (RD->isUnion() &&
680 !declaresSameEntity(ILE->getInitializedFieldInUnion(), Field))
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000681 continue;
682
Richard Smith78b239e2019-06-20 20:44:45 +0000683 // Don't emit anonymous bitfields or zero-sized fields.
684 if (Field->isUnnamedBitfield() || Field->isZeroSize(CGM.getContext()))
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000685 continue;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000686
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000687 // Get the initializer. A struct can include fields without initializers,
688 // we just use explicit null values for them.
Richard Smith5745feb2019-06-17 21:08:30 +0000689 Expr *Init = nullptr;
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000690 if (ElementNo < ILE->getNumInits())
Richard Smith5745feb2019-06-17 21:08:30 +0000691 Init = ILE->getInit(ElementNo++);
692 if (Init && isa<NoInitExpr>(Init))
693 continue;
Eli Friedman3ee10222010-07-17 23:55:01 +0000694
Richard Smith5745feb2019-06-17 21:08:30 +0000695 // When emitting a DesignatedInitUpdateExpr, a nested InitListExpr
696 // represents additional overwriting of our current constant value, and not
697 // a new constant to emit independently.
698 if (AllowOverwrite &&
699 (Field->getType()->isArrayType() || Field->getType()->isRecordType())) {
700 if (auto *SubILE = dyn_cast<InitListExpr>(Init)) {
701 CharUnits Offset = CGM.getContext().toCharUnitsFromBits(
702 Layout.getFieldOffset(FieldNo));
703 if (!EmitDesignatedInitUpdater(Emitter, Builder, StartOffset + Offset,
704 Field->getType(), SubILE))
705 return false;
706 // If we split apart the field's value, try to collapse it down to a
707 // single value now.
708 Builder.condense(StartOffset + Offset,
709 CGM.getTypes().ConvertTypeForMem(Field->getType()));
710 continue;
711 }
712 }
713
714 llvm::Constant *EltInit =
715 Init ? Emitter.tryEmitPrivateForMemory(Init, Field->getType())
716 : Emitter.emitNullForMemory(Field->getType());
Eli Friedman3ee10222010-07-17 23:55:01 +0000717 if (!EltInit)
718 return false;
David Majnemer8062eb62015-03-14 22:24:38 +0000719
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000720 if (!Field->isBitField()) {
721 // Handle non-bitfield members.
Richard Smith5745feb2019-06-17 21:08:30 +0000722 if (!AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit,
723 AllowOverwrite))
724 return false;
Richard Smith78b239e2019-06-20 20:44:45 +0000725 // After emitting a non-empty field with [[no_unique_address]], we may
726 // need to overwrite its tail padding.
727 if (Field->hasAttr<NoUniqueAddressAttr>())
728 AllowOverwrite = true;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000729 } else {
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000730 // Otherwise we have a bitfield.
David Majnemer8062eb62015-03-14 22:24:38 +0000731 if (auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) {
Richard Smith5745feb2019-06-17 21:08:30 +0000732 if (!AppendBitField(Field, Layout.getFieldOffset(FieldNo), CI,
733 AllowOverwrite))
734 return false;
David Majnemer8062eb62015-03-14 22:24:38 +0000735 } else {
736 // We are trying to initialize a bitfield with a non-trivial constant,
737 // this must require run-time code.
738 return false;
739 }
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000740 }
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000741 }
742
Richard Smithdafff942012-01-14 04:30:29 +0000743 return true;
744}
745
Richard Smithc8998922012-02-23 08:33:23 +0000746namespace {
747struct BaseInfo {
748 BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
749 : Decl(Decl), Offset(Offset), Index(Index) {
750 }
751
752 const CXXRecordDecl *Decl;
753 CharUnits Offset;
754 unsigned Index;
755
756 bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
757};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000758}
Richard Smithc8998922012-02-23 08:33:23 +0000759
John McCallde0fe072017-08-15 21:42:52 +0000760bool ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000761 bool IsPrimaryBase,
Richard Smithc8998922012-02-23 08:33:23 +0000762 const CXXRecordDecl *VTableClass,
763 CharUnits Offset) {
Richard Smithdafff942012-01-14 04:30:29 +0000764 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
765
Richard Smithc8998922012-02-23 08:33:23 +0000766 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
767 // Add a vtable pointer, if we need one and it hasn't already been added.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000768 if (CD->isDynamicClass() && !IsPrimaryBase) {
769 llvm::Constant *VTableAddressPoint =
770 CGM.getCXXABI().getVTableAddressPointForConstExpr(
771 BaseSubobject(CD, Offset), VTableClass);
Richard Smith5745feb2019-06-17 21:08:30 +0000772 if (!AppendBytes(Offset, VTableAddressPoint))
773 return false;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000774 }
Richard Smithc8998922012-02-23 08:33:23 +0000775
776 // Accumulate and sort bases, in order to visit them in address order, which
777 // may not be the same as declaration order.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000778 SmallVector<BaseInfo, 8> Bases;
Richard Smithc8998922012-02-23 08:33:23 +0000779 Bases.reserve(CD->getNumBases());
Richard Smithdafff942012-01-14 04:30:29 +0000780 unsigned BaseNo = 0;
Richard Smithc8998922012-02-23 08:33:23 +0000781 for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
Richard Smithdafff942012-01-14 04:30:29 +0000782 BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
Richard Smithc8998922012-02-23 08:33:23 +0000783 assert(!Base->isVirtual() && "should not have virtual bases here");
Richard Smithdafff942012-01-14 04:30:29 +0000784 const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
785 CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
Richard Smithc8998922012-02-23 08:33:23 +0000786 Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
787 }
Fangrui Song899d1392019-04-24 14:43:05 +0000788 llvm::stable_sort(Bases);
Richard Smithdafff942012-01-14 04:30:29 +0000789
Richard Smithc8998922012-02-23 08:33:23 +0000790 for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
791 BaseInfo &Base = Bases[I];
Richard Smithdafff942012-01-14 04:30:29 +0000792
Richard Smithc8998922012-02-23 08:33:23 +0000793 bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
794 Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000795 VTableClass, Offset + Base.Offset);
Richard Smithdafff942012-01-14 04:30:29 +0000796 }
797 }
798
799 unsigned FieldNo = 0;
Eli Friedmana154dd52012-03-30 03:55:31 +0000800 uint64_t OffsetBits = CGM.getContext().toBits(Offset);
Richard Smithdafff942012-01-14 04:30:29 +0000801
Richard Smith78b239e2019-06-20 20:44:45 +0000802 bool AllowOverwrite = false;
Richard Smithdafff942012-01-14 04:30:29 +0000803 for (RecordDecl::field_iterator Field = RD->field_begin(),
804 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
Richard Smithdafff942012-01-14 04:30:29 +0000805 // If this is a union, skip all the fields that aren't being initialized.
David Blaikie275a55c2019-05-22 20:36:06 +0000806 if (RD->isUnion() && !declaresSameEntity(Val.getUnionField(), *Field))
Richard Smithdafff942012-01-14 04:30:29 +0000807 continue;
808
Richard Smith78b239e2019-06-20 20:44:45 +0000809 // Don't emit anonymous bitfields or zero-sized fields.
810 if (Field->isUnnamedBitfield() || Field->isZeroSize(CGM.getContext()))
Richard Smithdafff942012-01-14 04:30:29 +0000811 continue;
Richard Smithdafff942012-01-14 04:30:29 +0000812
813 // Emit the value of the initializer.
814 const APValue &FieldValue =
815 RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
816 llvm::Constant *EltInit =
John McCallde0fe072017-08-15 21:42:52 +0000817 Emitter.tryEmitPrivateForMemory(FieldValue, Field->getType());
818 if (!EltInit)
819 return false;
Richard Smithdafff942012-01-14 04:30:29 +0000820
821 if (!Field->isBitField()) {
822 // Handle non-bitfield members.
Richard Smith5745feb2019-06-17 21:08:30 +0000823 if (!AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
Richard Smith78b239e2019-06-20 20:44:45 +0000824 EltInit, AllowOverwrite))
Richard Smith5745feb2019-06-17 21:08:30 +0000825 return false;
Richard Smith78b239e2019-06-20 20:44:45 +0000826 // After emitting a non-empty field with [[no_unique_address]], we may
827 // need to overwrite its tail padding.
828 if (Field->hasAttr<NoUniqueAddressAttr>())
829 AllowOverwrite = true;
Richard Smithdafff942012-01-14 04:30:29 +0000830 } else {
831 // Otherwise we have a bitfield.
Richard Smith5745feb2019-06-17 21:08:30 +0000832 if (!AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
Richard Smith78b239e2019-06-20 20:44:45 +0000833 cast<llvm::ConstantInt>(EltInit), AllowOverwrite))
Richard Smith5745feb2019-06-17 21:08:30 +0000834 return false;
Richard Smithdafff942012-01-14 04:30:29 +0000835 }
836 }
John McCallde0fe072017-08-15 21:42:52 +0000837
838 return true;
Richard Smithdafff942012-01-14 04:30:29 +0000839}
840
Richard Smith5745feb2019-06-17 21:08:30 +0000841llvm::Constant *ConstStructBuilder::Finalize(QualType Type) {
842 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
843 llvm::Type *ValTy = CGM.getTypes().ConvertType(Type);
844 return Builder.build(ValTy, RD->hasFlexibleArrayMember());
Yunzhong Gaocb779302015-06-10 00:27:52 +0000845}
846
John McCallde0fe072017-08-15 21:42:52 +0000847llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
848 InitListExpr *ILE,
849 QualType ValTy) {
Richard Smith5745feb2019-06-17 21:08:30 +0000850 ConstantAggregateBuilder Const(Emitter.CGM);
851 ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
Richard Smithdafff942012-01-14 04:30:29 +0000852
Richard Smith5745feb2019-06-17 21:08:30 +0000853 if (!Builder.Build(ILE, /*AllowOverwrite*/false))
Craig Topper8a13c412014-05-21 05:09:00 +0000854 return nullptr;
Richard Smithdafff942012-01-14 04:30:29 +0000855
John McCallde0fe072017-08-15 21:42:52 +0000856 return Builder.Finalize(ValTy);
Richard Smithdafff942012-01-14 04:30:29 +0000857}
858
John McCallde0fe072017-08-15 21:42:52 +0000859llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
Richard Smithdafff942012-01-14 04:30:29 +0000860 const APValue &Val,
861 QualType ValTy) {
Richard Smith5745feb2019-06-17 21:08:30 +0000862 ConstantAggregateBuilder Const(Emitter.CGM);
863 ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
Richard Smithc8998922012-02-23 08:33:23 +0000864
865 const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
866 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
John McCallde0fe072017-08-15 21:42:52 +0000867 if (!Builder.Build(Val, RD, false, CD, CharUnits::Zero()))
868 return nullptr;
Richard Smithc8998922012-02-23 08:33:23 +0000869
Richard Smithdafff942012-01-14 04:30:29 +0000870 return Builder.Finalize(ValTy);
871}
872
Richard Smith5745feb2019-06-17 21:08:30 +0000873bool ConstStructBuilder::UpdateStruct(ConstantEmitter &Emitter,
874 ConstantAggregateBuilder &Const,
875 CharUnits Offset, InitListExpr *Updater) {
876 return ConstStructBuilder(Emitter, Const, Offset)
877 .Build(Updater, /*AllowOverwrite*/ true);
878}
Richard Smithdafff942012-01-14 04:30:29 +0000879
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000880//===----------------------------------------------------------------------===//
881// ConstExprEmitter
882//===----------------------------------------------------------------------===//
Richard Smithdd5bdd82012-01-17 21:42:19 +0000883
John McCallde0fe072017-08-15 21:42:52 +0000884static ConstantAddress tryEmitGlobalCompoundLiteral(CodeGenModule &CGM,
885 CodeGenFunction *CGF,
886 const CompoundLiteralExpr *E) {
887 CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType());
888 if (llvm::GlobalVariable *Addr =
889 CGM.getAddrOfConstantCompoundLiteralIfEmitted(E))
890 return ConstantAddress(Addr, Align);
891
Alexander Richardson6d989432017-10-15 18:48:14 +0000892 LangAS addressSpace = E->getType().getAddressSpace();
John McCallde0fe072017-08-15 21:42:52 +0000893
894 ConstantEmitter emitter(CGM, CGF);
895 llvm::Constant *C = emitter.tryEmitForInitializer(E->getInitializer(),
896 addressSpace, E->getType());
897 if (!C) {
898 assert(!E->isFileScope() &&
899 "file-scope compound literal did not have constant initializer!");
900 return ConstantAddress::invalid();
901 }
902
903 auto GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
904 CGM.isTypeConstant(E->getType(), true),
905 llvm::GlobalValue::InternalLinkage,
906 C, ".compoundliteral", nullptr,
907 llvm::GlobalVariable::NotThreadLocal,
908 CGM.getContext().getTargetAddressSpace(addressSpace));
909 emitter.finalize(GV);
910 GV->setAlignment(Align.getQuantity());
911 CGM.setAddrOfConstantCompoundLiteral(E, GV);
912 return ConstantAddress(GV, Align);
913}
914
Richard Smith3e268632018-05-23 23:41:38 +0000915static llvm::Constant *
Richard Smith5745feb2019-06-17 21:08:30 +0000916EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,
Richard Smith3e268632018-05-23 23:41:38 +0000917 llvm::Type *CommonElementType, unsigned ArrayBound,
918 SmallVectorImpl<llvm::Constant *> &Elements,
919 llvm::Constant *Filler) {
920 // Figure out how long the initial prefix of non-zero elements is.
921 unsigned NonzeroLength = ArrayBound;
922 if (Elements.size() < NonzeroLength && Filler->isNullValue())
923 NonzeroLength = Elements.size();
924 if (NonzeroLength == Elements.size()) {
925 while (NonzeroLength > 0 && Elements[NonzeroLength - 1]->isNullValue())
926 --NonzeroLength;
927 }
928
Richard Smith5745feb2019-06-17 21:08:30 +0000929 if (NonzeroLength == 0)
930 return llvm::ConstantAggregateZero::get(DesiredType);
Richard Smith3e268632018-05-23 23:41:38 +0000931
932 // Add a zeroinitializer array filler if we have lots of trailing zeroes.
933 unsigned TrailingZeroes = ArrayBound - NonzeroLength;
934 if (TrailingZeroes >= 8) {
935 assert(Elements.size() >= NonzeroLength &&
936 "missing initializer for non-zero element");
Richard Smith83497d92018-07-19 21:38:56 +0000937
938 // If all the elements had the same type up to the trailing zeroes, emit a
939 // struct of two arrays (the nonzero data and the zeroinitializer).
940 if (CommonElementType && NonzeroLength >= 8) {
941 llvm::Constant *Initial = llvm::ConstantArray::get(
Richard Smith4c656882018-07-19 23:24:41 +0000942 llvm::ArrayType::get(CommonElementType, NonzeroLength),
Richard Smith83497d92018-07-19 21:38:56 +0000943 makeArrayRef(Elements).take_front(NonzeroLength));
944 Elements.resize(2);
945 Elements[0] = Initial;
946 } else {
947 Elements.resize(NonzeroLength + 1);
948 }
949
Richard Smith3e268632018-05-23 23:41:38 +0000950 auto *FillerType =
Richard Smith5745feb2019-06-17 21:08:30 +0000951 CommonElementType ? CommonElementType : DesiredType->getElementType();
Richard Smith3e268632018-05-23 23:41:38 +0000952 FillerType = llvm::ArrayType::get(FillerType, TrailingZeroes);
953 Elements.back() = llvm::ConstantAggregateZero::get(FillerType);
954 CommonElementType = nullptr;
955 } else if (Elements.size() != ArrayBound) {
956 // Otherwise pad to the right size with the filler if necessary.
957 Elements.resize(ArrayBound, Filler);
958 if (Filler->getType() != CommonElementType)
959 CommonElementType = nullptr;
960 }
961
962 // If all elements have the same type, just emit an array constant.
963 if (CommonElementType)
964 return llvm::ConstantArray::get(
965 llvm::ArrayType::get(CommonElementType, ArrayBound), Elements);
966
967 // We have mixed types. Use a packed struct.
968 llvm::SmallVector<llvm::Type *, 16> Types;
969 Types.reserve(Elements.size());
970 for (llvm::Constant *Elt : Elements)
971 Types.push_back(Elt->getType());
972 llvm::StructType *SType =
973 llvm::StructType::get(CGM.getLLVMContext(), Types, true);
974 return llvm::ConstantStruct::get(SType, Elements);
975}
976
Eli Friedman7f98e3c2019-02-08 21:36:04 +0000977// This class only needs to handle arrays, structs and unions. Outside C++11
978// mode, we don't currently constant fold those types. All other types are
979// handled by constant folding.
980//
981// Constant folding is currently missing support for a few features supported
982// here: CK_ToUnion, CK_ReinterpretMemberPointer, and DesignatedInitUpdateExpr.
Benjamin Kramer337e3a52009-11-28 19:45:26 +0000983class ConstExprEmitter :
John McCallde0fe072017-08-15 21:42:52 +0000984 public StmtVisitor<ConstExprEmitter, llvm::Constant*, QualType> {
Anders Carlsson610ee712008-01-26 01:36:00 +0000985 CodeGenModule &CGM;
John McCallde0fe072017-08-15 21:42:52 +0000986 ConstantEmitter &Emitter;
Owen Anderson170229f2009-07-14 23:10:40 +0000987 llvm::LLVMContext &VMContext;
Anders Carlsson610ee712008-01-26 01:36:00 +0000988public:
John McCallde0fe072017-08-15 21:42:52 +0000989 ConstExprEmitter(ConstantEmitter &emitter)
990 : CGM(emitter.CGM), Emitter(emitter), VMContext(CGM.getLLVMContext()) {
Anders Carlsson610ee712008-01-26 01:36:00 +0000991 }
Mike Stump11289f42009-09-09 15:08:12 +0000992
Anders Carlsson610ee712008-01-26 01:36:00 +0000993 //===--------------------------------------------------------------------===//
994 // Visitor Methods
995 //===--------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000996
John McCallde0fe072017-08-15 21:42:52 +0000997 llvm::Constant *VisitStmt(Stmt *S, QualType T) {
Craig Topper8a13c412014-05-21 05:09:00 +0000998 return nullptr;
Anders Carlsson610ee712008-01-26 01:36:00 +0000999 }
Mike Stump11289f42009-09-09 15:08:12 +00001000
Bill Wendling8003edc2018-11-09 00:41:36 +00001001 llvm::Constant *VisitConstantExpr(ConstantExpr *CE, QualType T) {
1002 return Visit(CE->getSubExpr(), T);
1003 }
1004
John McCallde0fe072017-08-15 21:42:52 +00001005 llvm::Constant *VisitParenExpr(ParenExpr *PE, QualType T) {
1006 return Visit(PE->getSubExpr(), T);
Anders Carlsson610ee712008-01-26 01:36:00 +00001007 }
Mike Stump11289f42009-09-09 15:08:12 +00001008
John McCall7c454bb2011-07-15 05:09:51 +00001009 llvm::Constant *
John McCallde0fe072017-08-15 21:42:52 +00001010 VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE,
1011 QualType T) {
1012 return Visit(PE->getReplacement(), T);
John McCall7c454bb2011-07-15 05:09:51 +00001013 }
1014
John McCallde0fe072017-08-15 21:42:52 +00001015 llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE,
1016 QualType T) {
1017 return Visit(GE->getResultExpr(), T);
Peter Collingbourne91147592011-04-15 00:35:48 +00001018 }
1019
John McCallde0fe072017-08-15 21:42:52 +00001020 llvm::Constant *VisitChooseExpr(ChooseExpr *CE, QualType T) {
1021 return Visit(CE->getChosenSubExpr(), T);
Eli Friedman4c27ac22013-07-16 22:40:53 +00001022 }
1023
John McCallde0fe072017-08-15 21:42:52 +00001024 llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E, QualType T) {
1025 return Visit(E->getInitializer(), T);
Anders Carlsson610ee712008-01-26 01:36:00 +00001026 }
John McCallf3a88602011-02-03 08:15:49 +00001027
John McCallde0fe072017-08-15 21:42:52 +00001028 llvm::Constant *VisitCastExpr(CastExpr *E, QualType destType) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00001029 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
John McCallde0fe072017-08-15 21:42:52 +00001030 CGM.EmitExplicitCastExprType(ECE, Emitter.CGF);
John McCall2de87f62011-03-15 21:17:48 +00001031 Expr *subExpr = E->getSubExpr();
John McCall2de87f62011-03-15 21:17:48 +00001032
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +00001033 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00001034 case CK_ToUnion: {
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +00001035 // GCC cast to union extension
1036 assert(E->getType()->isUnionType() &&
1037 "Destination type is not union type!");
Mike Stump11289f42009-09-09 15:08:12 +00001038
John McCallde0fe072017-08-15 21:42:52 +00001039 auto field = E->getTargetUnionField();
1040
1041 auto C = Emitter.tryEmitPrivateForMemory(subExpr, field->getType());
1042 if (!C) return nullptr;
1043
1044 auto destTy = ConvertType(destType);
1045 if (C->getType() == destTy) return C;
1046
Anders Carlssond65ab042009-07-31 21:38:39 +00001047 // Build a struct with the union sub-element as the first member,
John McCallde0fe072017-08-15 21:42:52 +00001048 // and padded to the appropriate size.
Bill Wendling99729582012-02-07 00:13:27 +00001049 SmallVector<llvm::Constant*, 2> Elts;
1050 SmallVector<llvm::Type*, 2> Types;
Anders Carlssond65ab042009-07-31 21:38:39 +00001051 Elts.push_back(C);
1052 Types.push_back(C->getType());
Micah Villmowdd31ca12012-10-08 16:25:52 +00001053 unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
John McCallde0fe072017-08-15 21:42:52 +00001054 unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destTy);
Mike Stump11289f42009-09-09 15:08:12 +00001055
Anders Carlssond65ab042009-07-31 21:38:39 +00001056 assert(CurSize <= TotalSize && "Union size mismatch!");
1057 if (unsigned NumPadBytes = TotalSize - CurSize) {
Chris Lattnerece04092012-02-07 00:39:47 +00001058 llvm::Type *Ty = CGM.Int8Ty;
Anders Carlssond65ab042009-07-31 21:38:39 +00001059 if (NumPadBytes > 1)
1060 Ty = llvm::ArrayType::get(Ty, NumPadBytes);
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +00001061
Nuno Lopes5863c992010-04-16 20:56:35 +00001062 Elts.push_back(llvm::UndefValue::get(Ty));
Anders Carlssond65ab042009-07-31 21:38:39 +00001063 Types.push_back(Ty);
1064 }
Mike Stump11289f42009-09-09 15:08:12 +00001065
John McCallde0fe072017-08-15 21:42:52 +00001066 llvm::StructType *STy = llvm::StructType::get(VMContext, Types, false);
Anders Carlssond65ab042009-07-31 21:38:39 +00001067 return llvm::ConstantStruct::get(STy, Elts);
Nuno Lopes4d78cf02009-01-17 00:48:48 +00001068 }
Anders Carlsson9500ad12009-10-18 20:31:03 +00001069
John McCallde0fe072017-08-15 21:42:52 +00001070 case CK_AddressSpaceConversion: {
1071 auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
1072 if (!C) return nullptr;
Alexander Richardson6d989432017-10-15 18:48:14 +00001073 LangAS destAS = E->getType()->getPointeeType().getAddressSpace();
1074 LangAS srcAS = subExpr->getType()->getPointeeType().getAddressSpace();
John McCallde0fe072017-08-15 21:42:52 +00001075 llvm::Type *destTy = ConvertType(E->getType());
1076 return CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGM, C, srcAS,
1077 destAS, destTy);
1078 }
David Tweede1468322013-12-11 13:39:46 +00001079
John McCall2de87f62011-03-15 21:17:48 +00001080 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00001081 case CK_AtomicToNonAtomic:
1082 case CK_NonAtomicToAtomic:
John McCall2de87f62011-03-15 21:17:48 +00001083 case CK_NoOp:
Eli Friedman4c27ac22013-07-16 22:40:53 +00001084 case CK_ConstructorConversion:
John McCallde0fe072017-08-15 21:42:52 +00001085 return Visit(subExpr, destType);
Anders Carlsson9500ad12009-10-18 20:31:03 +00001086
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001087 case CK_IntToOCLSampler:
1088 llvm_unreachable("global sampler variables are not generated");
1089
John McCall2de87f62011-03-15 21:17:48 +00001090 case CK_Dependent: llvm_unreachable("saw dependent cast!");
1091
Eli Friedman34866c72012-08-31 00:14:07 +00001092 case CK_BuiltinFnToFnPtr:
1093 llvm_unreachable("builtin functions are handled elsewhere");
1094
John McCallc62bb392012-02-15 01:22:51 +00001095 case CK_ReinterpretMemberPointer:
1096 case CK_DerivedToBaseMemberPointer:
John McCallde0fe072017-08-15 21:42:52 +00001097 case CK_BaseToDerivedMemberPointer: {
1098 auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
1099 if (!C) return nullptr;
John McCallc62bb392012-02-15 01:22:51 +00001100 return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
John McCallde0fe072017-08-15 21:42:52 +00001101 }
John McCallc62bb392012-02-15 01:22:51 +00001102
John McCall2de87f62011-03-15 21:17:48 +00001103 // These will never be supported.
1104 case CK_ObjCObjectLValueCast:
John McCall2d637d22011-09-10 06:18:15 +00001105 case CK_ARCProduceObject:
1106 case CK_ARCConsumeObject:
1107 case CK_ARCReclaimReturnedObject:
1108 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00001109 case CK_CopyAndAutoreleaseBlockObject:
Craig Topper8a13c412014-05-21 05:09:00 +00001110 return nullptr;
John McCall2de87f62011-03-15 21:17:48 +00001111
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001112 // These don't need to be handled here because Evaluate knows how to
Richard Smithdd5bdd82012-01-17 21:42:19 +00001113 // evaluate them in the cases where they can be folded.
John McCallc62bb392012-02-15 01:22:51 +00001114 case CK_BitCast:
Richard Smithdd5bdd82012-01-17 21:42:19 +00001115 case CK_ToVoid:
1116 case CK_Dynamic:
1117 case CK_LValueBitCast:
1118 case CK_NullToMemberPointer:
Richard Smithdd5bdd82012-01-17 21:42:19 +00001119 case CK_UserDefinedConversion:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001120 case CK_CPointerToObjCPointerCast:
1121 case CK_BlockPointerToObjCPointerCast:
1122 case CK_AnyPointerToBlockPointerCast:
John McCall2de87f62011-03-15 21:17:48 +00001123 case CK_ArrayToPointerDecay:
1124 case CK_FunctionToPointerDecay:
1125 case CK_BaseToDerived:
1126 case CK_DerivedToBase:
1127 case CK_UncheckedDerivedToBase:
1128 case CK_MemberPointerToBoolean:
1129 case CK_VectorSplat:
1130 case CK_FloatingRealToComplex:
1131 case CK_FloatingComplexToReal:
1132 case CK_FloatingComplexToBoolean:
1133 case CK_FloatingComplexCast:
1134 case CK_FloatingComplexToIntegralComplex:
1135 case CK_IntegralRealToComplex:
1136 case CK_IntegralComplexToReal:
1137 case CK_IntegralComplexToBoolean:
1138 case CK_IntegralComplexCast:
1139 case CK_IntegralComplexToFloatingComplex:
John McCall2de87f62011-03-15 21:17:48 +00001140 case CK_PointerToIntegral:
John McCall2de87f62011-03-15 21:17:48 +00001141 case CK_PointerToBoolean:
John McCall2de87f62011-03-15 21:17:48 +00001142 case CK_NullToPointer:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001143 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00001144 case CK_BooleanToSignedIntegral:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001145 case CK_IntegralToPointer:
John McCall2de87f62011-03-15 21:17:48 +00001146 case CK_IntegralToBoolean:
John McCall2de87f62011-03-15 21:17:48 +00001147 case CK_IntegralToFloating:
John McCall2de87f62011-03-15 21:17:48 +00001148 case CK_FloatingToIntegral:
John McCall2de87f62011-03-15 21:17:48 +00001149 case CK_FloatingToBoolean:
John McCall2de87f62011-03-15 21:17:48 +00001150 case CK_FloatingCast:
Leonard Chan99bda372018-10-15 16:07:02 +00001151 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +00001152 case CK_FixedPointToBoolean:
Leonard Chan8f7caae2019-03-06 00:28:43 +00001153 case CK_FixedPointToIntegral:
1154 case CK_IntegralToFixedPoint:
Andrew Savonichevb555b762018-10-23 15:19:20 +00001155 case CK_ZeroToOCLOpaqueType:
Craig Topper8a13c412014-05-21 05:09:00 +00001156 return nullptr;
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +00001157 }
Matt Beaumont-Gay145e2eb2011-03-17 00:46:34 +00001158 llvm_unreachable("Invalid CastKind");
Anders Carlsson610ee712008-01-26 01:36:00 +00001159 }
Devang Patela703a672008-02-05 02:39:50 +00001160
John McCallde0fe072017-08-15 21:42:52 +00001161 llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE, QualType T) {
Richard Smith852c9db2013-04-20 22:23:05 +00001162 // No need for a DefaultInitExprScope: we don't handle 'this' in a
1163 // constant expression.
John McCallde0fe072017-08-15 21:42:52 +00001164 return Visit(DIE->getExpr(), T);
Richard Smith852c9db2013-04-20 22:23:05 +00001165 }
1166
John McCallde0fe072017-08-15 21:42:52 +00001167 llvm::Constant *VisitExprWithCleanups(ExprWithCleanups *E, QualType T) {
Tim Shen4a05bb82016-06-21 20:29:17 +00001168 if (!E->cleanupsHaveSideEffects())
John McCallde0fe072017-08-15 21:42:52 +00001169 return Visit(E->getSubExpr(), T);
Tim Shen4a05bb82016-06-21 20:29:17 +00001170 return nullptr;
1171 }
1172
John McCallde0fe072017-08-15 21:42:52 +00001173 llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E,
1174 QualType T) {
1175 return Visit(E->GetTemporaryExpr(), T);
Douglas Gregorfe314812011-06-21 17:03:29 +00001176 }
1177
John McCallde0fe072017-08-15 21:42:52 +00001178 llvm::Constant *EmitArrayInitialization(InitListExpr *ILE, QualType T) {
Richard Smith3e268632018-05-23 23:41:38 +00001179 auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType());
1180 assert(CAT && "can't emit array init for non-constant-bound array");
Richard Smith9ec1e482012-04-15 02:50:59 +00001181 unsigned NumInitElements = ILE->getNumInits();
Richard Smith3e268632018-05-23 23:41:38 +00001182 unsigned NumElements = CAT->getSize().getZExtValue();
Devang Patela703a672008-02-05 02:39:50 +00001183
Mike Stump11289f42009-09-09 15:08:12 +00001184 // Initialising an array requires us to automatically
Devang Patela703a672008-02-05 02:39:50 +00001185 // initialise any elements that have not been initialised explicitly
1186 unsigned NumInitableElts = std::min(NumInitElements, NumElements);
1187
Richard Smith3e268632018-05-23 23:41:38 +00001188 QualType EltType = CAT->getElementType();
John McCallde0fe072017-08-15 21:42:52 +00001189
David Majnemer90d85442014-12-28 23:46:59 +00001190 // Initialize remaining array elements.
Richard Smith3e268632018-05-23 23:41:38 +00001191 llvm::Constant *fillC = nullptr;
1192 if (Expr *filler = ILE->getArrayFiller()) {
John McCallde0fe072017-08-15 21:42:52 +00001193 fillC = Emitter.tryEmitAbstractForMemory(filler, EltType);
Richard Smith3e268632018-05-23 23:41:38 +00001194 if (!fillC)
1195 return nullptr;
1196 }
David Majnemer90d85442014-12-28 23:46:59 +00001197
Devang Patela703a672008-02-05 02:39:50 +00001198 // Copy initializer elements.
John McCallde0fe072017-08-15 21:42:52 +00001199 SmallVector<llvm::Constant*, 16> Elts;
Richard Smith3e268632018-05-23 23:41:38 +00001200 if (fillC && fillC->isNullValue())
1201 Elts.reserve(NumInitableElts + 1);
1202 else
1203 Elts.reserve(NumElements);
Benjamin Kramer8001f742012-02-14 12:06:21 +00001204
Richard Smith3e268632018-05-23 23:41:38 +00001205 llvm::Type *CommonElementType = nullptr;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001206 for (unsigned i = 0; i < NumInitableElts; ++i) {
Anders Carlsson80f97ab2009-04-08 04:48:15 +00001207 Expr *Init = ILE->getInit(i);
John McCallde0fe072017-08-15 21:42:52 +00001208 llvm::Constant *C = Emitter.tryEmitPrivateForMemory(Init, EltType);
Daniel Dunbar38ad1e62009-02-17 18:43:32 +00001209 if (!C)
Craig Topper8a13c412014-05-21 05:09:00 +00001210 return nullptr;
Richard Smith3e268632018-05-23 23:41:38 +00001211 if (i == 0)
1212 CommonElementType = C->getType();
1213 else if (C->getType() != CommonElementType)
1214 CommonElementType = nullptr;
Devang Patela703a672008-02-05 02:39:50 +00001215 Elts.push_back(C);
1216 }
Eli Friedman34994cb2008-05-30 19:58:50 +00001217
Richard Smith5745feb2019-06-17 21:08:30 +00001218 llvm::ArrayType *Desired =
1219 cast<llvm::ArrayType>(CGM.getTypes().ConvertType(ILE->getType()));
1220 return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,
Richard Smith3e268632018-05-23 23:41:38 +00001221 fillC);
Devang Patela703a672008-02-05 02:39:50 +00001222 }
1223
John McCallde0fe072017-08-15 21:42:52 +00001224 llvm::Constant *EmitRecordInitialization(InitListExpr *ILE, QualType T) {
1225 return ConstStructBuilder::BuildStruct(Emitter, ILE, T);
Eli Friedmana2eaffc2008-05-30 10:24:46 +00001226 }
1227
John McCallde0fe072017-08-15 21:42:52 +00001228 llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E,
1229 QualType T) {
1230 return CGM.EmitNullConstant(T);
Anders Carlsson02714ed2009-01-30 06:13:25 +00001231 }
Mike Stump11289f42009-09-09 15:08:12 +00001232
John McCallde0fe072017-08-15 21:42:52 +00001233 llvm::Constant *VisitInitListExpr(InitListExpr *ILE, QualType T) {
Richard Smith122f88d2016-12-06 23:52:28 +00001234 if (ILE->isTransparent())
John McCallde0fe072017-08-15 21:42:52 +00001235 return Visit(ILE->getInit(0), T);
Richard Smith122f88d2016-12-06 23:52:28 +00001236
Eli Friedmana2eaffc2008-05-30 10:24:46 +00001237 if (ILE->getType()->isArrayType())
John McCallde0fe072017-08-15 21:42:52 +00001238 return EmitArrayInitialization(ILE, T);
Devang Patel45a65d22008-01-29 23:23:18 +00001239
Jin-Gu Kang1a5e4232012-09-05 08:37:43 +00001240 if (ILE->getType()->isRecordType())
John McCallde0fe072017-08-15 21:42:52 +00001241 return EmitRecordInitialization(ILE, T);
Jin-Gu Kang1a5e4232012-09-05 08:37:43 +00001242
Craig Topper8a13c412014-05-21 05:09:00 +00001243 return nullptr;
Anders Carlsson610ee712008-01-26 01:36:00 +00001244 }
Eli Friedmana2433112008-02-21 17:57:49 +00001245
John McCallde0fe072017-08-15 21:42:52 +00001246 llvm::Constant *VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E,
1247 QualType destType) {
1248 auto C = Visit(E->getBase(), destType);
Richard Smith5745feb2019-06-17 21:08:30 +00001249 if (!C)
1250 return nullptr;
1251
1252 ConstantAggregateBuilder Const(CGM);
1253 Const.add(C, CharUnits::Zero(), false);
1254
1255 if (!EmitDesignatedInitUpdater(Emitter, Const, CharUnits::Zero(), destType,
1256 E->getUpdater()))
1257 return nullptr;
1258
1259 llvm::Type *ValTy = CGM.getTypes().ConvertType(destType);
1260 bool HasFlexibleArray = false;
1261 if (auto *RT = destType->getAs<RecordType>())
1262 HasFlexibleArray = RT->getDecl()->hasFlexibleArrayMember();
1263 return Const.build(ValTy, HasFlexibleArray);
Fangrui Song6907ce22018-07-30 19:24:48 +00001264 }
Yunzhong Gaocb779302015-06-10 00:27:52 +00001265
John McCallde0fe072017-08-15 21:42:52 +00001266 llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E, QualType Ty) {
John McCall49786a62010-02-02 08:02:49 +00001267 if (!E->getConstructor()->isTrivial())
Craig Topper8a13c412014-05-21 05:09:00 +00001268 return nullptr;
John McCall49786a62010-02-02 08:02:49 +00001269
Anders Carlssoncb86e102010-02-05 18:38:45 +00001270 // FIXME: We should not have to call getBaseElementType here.
Fangrui Song6907ce22018-07-30 19:24:48 +00001271 const RecordType *RT =
Anders Carlssoncb86e102010-02-05 18:38:45 +00001272 CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>();
1273 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00001274
Anders Carlssoncb86e102010-02-05 18:38:45 +00001275 // If the class doesn't have a trivial destructor, we can't emit it as a
1276 // constant expr.
1277 if (!RD->hasTrivialDestructor())
Craig Topper8a13c412014-05-21 05:09:00 +00001278 return nullptr;
1279
John McCall49786a62010-02-02 08:02:49 +00001280 // Only copy and default constructors can be trivial.
1281
John McCall49786a62010-02-02 08:02:49 +00001282
1283 if (E->getNumArgs()) {
1284 assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Sebastian Redl22653ba2011-08-30 19:58:05 +00001285 assert(E->getConstructor()->isCopyOrMoveConstructor() &&
1286 "trivial ctor has argument but isn't a copy/move ctor");
John McCall49786a62010-02-02 08:02:49 +00001287
1288 Expr *Arg = E->getArg(0);
1289 assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
1290 "argument to copy ctor is of wrong type");
1291
John McCallde0fe072017-08-15 21:42:52 +00001292 return Visit(Arg, Ty);
John McCall49786a62010-02-02 08:02:49 +00001293 }
1294
1295 return CGM.EmitNullConstant(Ty);
1296 }
1297
John McCallde0fe072017-08-15 21:42:52 +00001298 llvm::Constant *VisitStringLiteral(StringLiteral *E, QualType T) {
Eli Friedman7f98e3c2019-02-08 21:36:04 +00001299 // This is a string literal initializing an array in an initializer.
Eli Friedmanfcec6302011-11-01 02:23:42 +00001300 return CGM.GetConstantArrayFromStringLiteral(E);
Anders Carlsson610ee712008-01-26 01:36:00 +00001301 }
1302
John McCallde0fe072017-08-15 21:42:52 +00001303 llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E, QualType T) {
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001304 // This must be an @encode initializing an array in a static initializer.
1305 // Don't emit it as the address of the string, emit the string data itself
1306 // as an inline array.
1307 std::string Str;
1308 CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
John McCallde0fe072017-08-15 21:42:52 +00001309 const ConstantArrayType *CAT = CGM.getContext().getAsConstantArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00001310
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001311 // Resize the string to the right size, adding zeros at the end, or
1312 // truncating as needed.
1313 Str.resize(CAT->getSize().getZExtValue(), '\0');
Chris Lattner9c818332012-02-05 02:30:40 +00001314 return llvm::ConstantDataArray::getString(VMContext, Str, false);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001315 }
Mike Stump11289f42009-09-09 15:08:12 +00001316
John McCallde0fe072017-08-15 21:42:52 +00001317 llvm::Constant *VisitUnaryExtension(const UnaryOperator *E, QualType T) {
1318 return Visit(E->getSubExpr(), T);
Eli Friedman045bf4f2008-05-29 11:22:45 +00001319 }
Mike Stumpa6703322009-02-19 22:01:56 +00001320
Anders Carlsson610ee712008-01-26 01:36:00 +00001321 // Utility methods
Chris Lattner2192fe52011-07-18 04:24:23 +00001322 llvm::Type *ConvertType(QualType T) {
Anders Carlsson610ee712008-01-26 01:36:00 +00001323 return CGM.getTypes().ConvertType(T);
1324 }
Anders Carlssona4139112008-01-26 02:08:50 +00001325};
Mike Stump11289f42009-09-09 15:08:12 +00001326
Anders Carlsson610ee712008-01-26 01:36:00 +00001327} // end anonymous namespace.
1328
John McCallde0fe072017-08-15 21:42:52 +00001329llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C,
1330 AbstractState saved) {
1331 Abstract = saved.OldValue;
1332
1333 assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&
1334 "created a placeholder while doing an abstract emission?");
1335
1336 // No validation necessary for now.
1337 // No cleanup to do for now.
1338 return C;
1339}
1340
1341llvm::Constant *
1342ConstantEmitter::tryEmitAbstractForInitializer(const VarDecl &D) {
1343 auto state = pushAbstract();
1344 auto C = tryEmitPrivateForVarInit(D);
1345 return validateAndPopAbstract(C, state);
1346}
1347
1348llvm::Constant *
1349ConstantEmitter::tryEmitAbstract(const Expr *E, QualType destType) {
1350 auto state = pushAbstract();
1351 auto C = tryEmitPrivate(E, destType);
1352 return validateAndPopAbstract(C, state);
1353}
1354
1355llvm::Constant *
1356ConstantEmitter::tryEmitAbstract(const APValue &value, QualType destType) {
1357 auto state = pushAbstract();
1358 auto C = tryEmitPrivate(value, destType);
1359 return validateAndPopAbstract(C, state);
1360}
1361
1362llvm::Constant *
1363ConstantEmitter::emitAbstract(const Expr *E, QualType destType) {
1364 auto state = pushAbstract();
1365 auto C = tryEmitPrivate(E, destType);
1366 C = validateAndPopAbstract(C, state);
1367 if (!C) {
1368 CGM.Error(E->getExprLoc(),
1369 "internal error: could not emit constant value \"abstractly\"");
1370 C = CGM.EmitNullConstant(destType);
1371 }
1372 return C;
1373}
1374
1375llvm::Constant *
1376ConstantEmitter::emitAbstract(SourceLocation loc, const APValue &value,
1377 QualType destType) {
1378 auto state = pushAbstract();
1379 auto C = tryEmitPrivate(value, destType);
1380 C = validateAndPopAbstract(C, state);
1381 if (!C) {
1382 CGM.Error(loc,
1383 "internal error: could not emit constant value \"abstractly\"");
1384 C = CGM.EmitNullConstant(destType);
1385 }
1386 return C;
1387}
1388
1389llvm::Constant *ConstantEmitter::tryEmitForInitializer(const VarDecl &D) {
1390 initializeNonAbstract(D.getType().getAddressSpace());
1391 return markIfFailed(tryEmitPrivateForVarInit(D));
1392}
1393
1394llvm::Constant *ConstantEmitter::tryEmitForInitializer(const Expr *E,
Alexander Richardson6d989432017-10-15 18:48:14 +00001395 LangAS destAddrSpace,
John McCallde0fe072017-08-15 21:42:52 +00001396 QualType destType) {
1397 initializeNonAbstract(destAddrSpace);
1398 return markIfFailed(tryEmitPrivateForMemory(E, destType));
1399}
1400
1401llvm::Constant *ConstantEmitter::emitForInitializer(const APValue &value,
Alexander Richardson6d989432017-10-15 18:48:14 +00001402 LangAS destAddrSpace,
John McCallde0fe072017-08-15 21:42:52 +00001403 QualType destType) {
1404 initializeNonAbstract(destAddrSpace);
1405 auto C = tryEmitPrivateForMemory(value, destType);
1406 assert(C && "couldn't emit constant value non-abstractly?");
1407 return C;
1408}
1409
1410llvm::GlobalValue *ConstantEmitter::getCurrentAddrPrivate() {
1411 assert(!Abstract && "cannot get current address for abstract constant");
1412
1413
1414
1415 // Make an obviously ill-formed global that should blow up compilation
1416 // if it survives.
1417 auto global = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, true,
1418 llvm::GlobalValue::PrivateLinkage,
1419 /*init*/ nullptr,
1420 /*name*/ "",
1421 /*before*/ nullptr,
1422 llvm::GlobalVariable::NotThreadLocal,
1423 CGM.getContext().getTargetAddressSpace(DestAddressSpace));
1424
1425 PlaceholderAddresses.push_back(std::make_pair(nullptr, global));
1426
1427 return global;
1428}
1429
1430void ConstantEmitter::registerCurrentAddrPrivate(llvm::Constant *signal,
1431 llvm::GlobalValue *placeholder) {
1432 assert(!PlaceholderAddresses.empty());
1433 assert(PlaceholderAddresses.back().first == nullptr);
1434 assert(PlaceholderAddresses.back().second == placeholder);
1435 PlaceholderAddresses.back().first = signal;
1436}
1437
1438namespace {
1439 struct ReplacePlaceholders {
1440 CodeGenModule &CGM;
1441
1442 /// The base address of the global.
1443 llvm::Constant *Base;
1444 llvm::Type *BaseValueTy = nullptr;
1445
1446 /// The placeholder addresses that were registered during emission.
1447 llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses;
1448
1449 /// The locations of the placeholder signals.
1450 llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations;
1451
1452 /// The current index stack. We use a simple unsigned stack because
1453 /// we assume that placeholders will be relatively sparse in the
1454 /// initializer, but we cache the index values we find just in case.
1455 llvm::SmallVector<unsigned, 8> Indices;
1456 llvm::SmallVector<llvm::Constant*, 8> IndexValues;
1457
1458 ReplacePlaceholders(CodeGenModule &CGM, llvm::Constant *base,
1459 ArrayRef<std::pair<llvm::Constant*,
1460 llvm::GlobalVariable*>> addresses)
1461 : CGM(CGM), Base(base),
1462 PlaceholderAddresses(addresses.begin(), addresses.end()) {
1463 }
1464
1465 void replaceInInitializer(llvm::Constant *init) {
1466 // Remember the type of the top-most initializer.
1467 BaseValueTy = init->getType();
1468
1469 // Initialize the stack.
1470 Indices.push_back(0);
1471 IndexValues.push_back(nullptr);
1472
1473 // Recurse into the initializer.
1474 findLocations(init);
1475
1476 // Check invariants.
1477 assert(IndexValues.size() == Indices.size() && "mismatch");
1478 assert(Indices.size() == 1 && "didn't pop all indices");
1479
1480 // Do the replacement; this basically invalidates 'init'.
1481 assert(Locations.size() == PlaceholderAddresses.size() &&
1482 "missed a placeholder?");
1483
1484 // We're iterating over a hashtable, so this would be a source of
1485 // non-determinism in compiler output *except* that we're just
1486 // messing around with llvm::Constant structures, which never itself
1487 // does anything that should be visible in compiler output.
1488 for (auto &entry : Locations) {
1489 assert(entry.first->getParent() == nullptr && "not a placeholder!");
1490 entry.first->replaceAllUsesWith(entry.second);
1491 entry.first->eraseFromParent();
1492 }
1493 }
1494
1495 private:
1496 void findLocations(llvm::Constant *init) {
1497 // Recurse into aggregates.
1498 if (auto agg = dyn_cast<llvm::ConstantAggregate>(init)) {
1499 for (unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) {
1500 Indices.push_back(i);
1501 IndexValues.push_back(nullptr);
1502
1503 findLocations(agg->getOperand(i));
1504
1505 IndexValues.pop_back();
1506 Indices.pop_back();
1507 }
1508 return;
1509 }
1510
1511 // Otherwise, check for registered constants.
1512 while (true) {
1513 auto it = PlaceholderAddresses.find(init);
1514 if (it != PlaceholderAddresses.end()) {
1515 setLocation(it->second);
1516 break;
1517 }
1518
1519 // Look through bitcasts or other expressions.
1520 if (auto expr = dyn_cast<llvm::ConstantExpr>(init)) {
1521 init = expr->getOperand(0);
1522 } else {
1523 break;
1524 }
1525 }
1526 }
1527
1528 void setLocation(llvm::GlobalVariable *placeholder) {
1529 assert(Locations.find(placeholder) == Locations.end() &&
1530 "already found location for placeholder!");
1531
1532 // Lazily fill in IndexValues with the values from Indices.
1533 // We do this in reverse because we should always have a strict
1534 // prefix of indices from the start.
1535 assert(Indices.size() == IndexValues.size());
1536 for (size_t i = Indices.size() - 1; i != size_t(-1); --i) {
1537 if (IndexValues[i]) {
1538#ifndef NDEBUG
1539 for (size_t j = 0; j != i + 1; ++j) {
1540 assert(IndexValues[j] &&
1541 isa<llvm::ConstantInt>(IndexValues[j]) &&
1542 cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue()
1543 == Indices[j]);
1544 }
1545#endif
1546 break;
1547 }
1548
1549 IndexValues[i] = llvm::ConstantInt::get(CGM.Int32Ty, Indices[i]);
1550 }
1551
1552 // Form a GEP and then bitcast to the placeholder type so that the
1553 // replacement will succeed.
1554 llvm::Constant *location =
1555 llvm::ConstantExpr::getInBoundsGetElementPtr(BaseValueTy,
1556 Base, IndexValues);
1557 location = llvm::ConstantExpr::getBitCast(location,
1558 placeholder->getType());
1559
1560 Locations.insert({placeholder, location});
1561 }
1562 };
1563}
1564
1565void ConstantEmitter::finalize(llvm::GlobalVariable *global) {
1566 assert(InitializedNonAbstract &&
1567 "finalizing emitter that was used for abstract emission?");
1568 assert(!Finalized && "finalizing emitter multiple times");
1569 assert(global->getInitializer());
1570
1571 // Note that we might also be Failed.
1572 Finalized = true;
1573
1574 if (!PlaceholderAddresses.empty()) {
1575 ReplacePlaceholders(CGM, global, PlaceholderAddresses)
1576 .replaceInInitializer(global->getInitializer());
1577 PlaceholderAddresses.clear(); // satisfy
1578 }
1579}
1580
1581ConstantEmitter::~ConstantEmitter() {
1582 assert((!InitializedNonAbstract || Finalized || Failed) &&
1583 "not finalized after being initialized for non-abstract emission");
1584 assert(PlaceholderAddresses.empty() && "unhandled placeholders");
1585}
1586
1587static QualType getNonMemoryType(CodeGenModule &CGM, QualType type) {
1588 if (auto AT = type->getAs<AtomicType>()) {
1589 return CGM.getContext().getQualifiedType(AT->getValueType(),
1590 type.getQualifiers());
1591 }
1592 return type;
1593}
1594
1595llvm::Constant *ConstantEmitter::tryEmitPrivateForVarInit(const VarDecl &D) {
Fariborz Jahaniancc7f0082013-01-10 23:28:43 +00001596 // Make a quick check if variable can be default NULL initialized
1597 // and avoid going through rest of code which may do, for c++11,
1598 // initialization of memory to all NULLs.
Richard Smith3f1d6de2018-05-21 20:36:58 +00001599 if (!D.hasLocalStorage()) {
1600 QualType Ty = CGM.getContext().getBaseElementType(D.getType());
1601 if (Ty->isRecordType())
1602 if (const CXXConstructExpr *E =
1603 dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
1604 const CXXConstructorDecl *CD = E->getConstructor();
1605 if (CD->isTrivial() && CD->isDefaultConstructor())
1606 return CGM.EmitNullConstant(D.getType());
1607 }
Bill Wendling958b94d2018-12-01 09:06:26 +00001608 InConstantContext = true;
Richard Smith3f1d6de2018-05-21 20:36:58 +00001609 }
John McCallde0fe072017-08-15 21:42:52 +00001610
1611 QualType destType = D.getType();
1612
1613 // Try to emit the initializer. Note that this can allow some things that
1614 // are not allowed by tryEmitPrivateForMemory alone.
1615 if (auto value = D.evaluateValue()) {
1616 return tryEmitPrivateForMemory(*value, destType);
1617 }
Richard Smithdafff942012-01-14 04:30:29 +00001618
Richard Smith6331c402012-02-13 22:16:19 +00001619 // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
1620 // reference is a constant expression, and the reference binds to a temporary,
1621 // then constant initialization is performed. ConstExprEmitter will
1622 // incorrectly emit a prvalue constant in this case, and the calling code
1623 // interprets that as the (pointer) value of the reference, rather than the
1624 // desired value of the referee.
John McCallde0fe072017-08-15 21:42:52 +00001625 if (destType->isReferenceType())
Craig Topper8a13c412014-05-21 05:09:00 +00001626 return nullptr;
Richard Smith6331c402012-02-13 22:16:19 +00001627
Richard Smithdafff942012-01-14 04:30:29 +00001628 const Expr *E = D.getInit();
1629 assert(E && "No initializer to emit");
1630
John McCallde0fe072017-08-15 21:42:52 +00001631 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1632 auto C =
1633 ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), nonMemoryDestType);
1634 return (C ? emitForMemory(C, destType) : nullptr);
1635}
1636
1637llvm::Constant *
1638ConstantEmitter::tryEmitAbstractForMemory(const Expr *E, QualType destType) {
1639 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1640 auto C = tryEmitAbstract(E, nonMemoryDestType);
Fangrui Song6907ce22018-07-30 19:24:48 +00001641 return (C ? emitForMemory(C, destType) : nullptr);
John McCallde0fe072017-08-15 21:42:52 +00001642}
1643
1644llvm::Constant *
1645ConstantEmitter::tryEmitAbstractForMemory(const APValue &value,
1646 QualType destType) {
1647 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1648 auto C = tryEmitAbstract(value, nonMemoryDestType);
Fangrui Song6907ce22018-07-30 19:24:48 +00001649 return (C ? emitForMemory(C, destType) : nullptr);
John McCallde0fe072017-08-15 21:42:52 +00001650}
1651
1652llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const Expr *E,
1653 QualType destType) {
1654 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1655 llvm::Constant *C = tryEmitPrivate(E, nonMemoryDestType);
1656 return (C ? emitForMemory(C, destType) : nullptr);
1657}
1658
1659llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const APValue &value,
1660 QualType destType) {
1661 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1662 auto C = tryEmitPrivate(value, nonMemoryDestType);
1663 return (C ? emitForMemory(C, destType) : nullptr);
1664}
1665
1666llvm::Constant *ConstantEmitter::emitForMemory(CodeGenModule &CGM,
1667 llvm::Constant *C,
1668 QualType destType) {
1669 // For an _Atomic-qualified constant, we may need to add tail padding.
1670 if (auto AT = destType->getAs<AtomicType>()) {
1671 QualType destValueType = AT->getValueType();
1672 C = emitForMemory(CGM, C, destValueType);
1673
1674 uint64_t innerSize = CGM.getContext().getTypeSize(destValueType);
1675 uint64_t outerSize = CGM.getContext().getTypeSize(destType);
1676 if (innerSize == outerSize)
1677 return C;
1678
1679 assert(innerSize < outerSize && "emitted over-large constant for atomic");
1680 llvm::Constant *elts[] = {
1681 C,
1682 llvm::ConstantAggregateZero::get(
1683 llvm::ArrayType::get(CGM.Int8Ty, (outerSize - innerSize) / 8))
1684 };
1685 return llvm::ConstantStruct::getAnon(elts);
Richard Smithdafff942012-01-14 04:30:29 +00001686 }
John McCallde0fe072017-08-15 21:42:52 +00001687
1688 // Zero-extend bool.
1689 if (C->getType()->isIntegerTy(1)) {
1690 llvm::Type *boolTy = CGM.getTypes().ConvertTypeForMem(destType);
1691 return llvm::ConstantExpr::getZExt(C, boolTy);
1692 }
1693
Richard Smithdafff942012-01-14 04:30:29 +00001694 return C;
1695}
1696
John McCallde0fe072017-08-15 21:42:52 +00001697llvm::Constant *ConstantEmitter::tryEmitPrivate(const Expr *E,
1698 QualType destType) {
Anders Carlsson38eef1d2008-12-01 02:42:14 +00001699 Expr::EvalResult Result;
Mike Stump11289f42009-09-09 15:08:12 +00001700
Anders Carlssond8e39bb2009-04-11 01:08:03 +00001701 bool Success = false;
Mike Stump11289f42009-09-09 15:08:12 +00001702
John McCallde0fe072017-08-15 21:42:52 +00001703 if (destType->isReferenceType())
1704 Success = E->EvaluateAsLValue(Result, CGM.getContext());
Mike Stump11289f42009-09-09 15:08:12 +00001705 else
Bill Wendling2a81f662018-12-01 08:29:36 +00001706 Success = E->EvaluateAsRValue(Result, CGM.getContext(), InConstantContext);
Mike Stump11289f42009-09-09 15:08:12 +00001707
John McCallde0fe072017-08-15 21:42:52 +00001708 llvm::Constant *C;
Richard Smithdafff942012-01-14 04:30:29 +00001709 if (Success && !Result.HasSideEffects)
John McCallde0fe072017-08-15 21:42:52 +00001710 C = tryEmitPrivate(Result.Val, destType);
Richard Smithbc6387672012-03-02 23:27:11 +00001711 else
John McCallde0fe072017-08-15 21:42:52 +00001712 C = ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), destType);
Eli Friedman10c24172008-06-01 15:31:44 +00001713
Eli Friedman10c24172008-06-01 15:31:44 +00001714 return C;
Anders Carlsson610ee712008-01-26 01:36:00 +00001715}
Eli Friedman20bb5e02009-04-13 21:47:26 +00001716
Yaxun Liu402804b2016-12-15 08:09:08 +00001717llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) {
1718 return getTargetCodeGenInfo().getNullPointer(*this, T, QT);
1719}
1720
John McCall99e5e982017-08-17 05:03:55 +00001721namespace {
1722/// A struct which can be used to peephole certain kinds of finalization
1723/// that normally happen during l-value emission.
1724struct ConstantLValue {
1725 llvm::Constant *Value;
1726 bool HasOffsetApplied;
1727
1728 /*implicit*/ ConstantLValue(llvm::Constant *value,
1729 bool hasOffsetApplied = false)
1730 : Value(value), HasOffsetApplied(false) {}
1731
1732 /*implicit*/ ConstantLValue(ConstantAddress address)
1733 : ConstantLValue(address.getPointer()) {}
1734};
1735
1736/// A helper class for emitting constant l-values.
1737class ConstantLValueEmitter : public ConstStmtVisitor<ConstantLValueEmitter,
1738 ConstantLValue> {
1739 CodeGenModule &CGM;
1740 ConstantEmitter &Emitter;
1741 const APValue &Value;
1742 QualType DestType;
1743
1744 // Befriend StmtVisitorBase so that we don't have to expose Visit*.
1745 friend StmtVisitorBase;
1746
1747public:
1748 ConstantLValueEmitter(ConstantEmitter &emitter, const APValue &value,
1749 QualType destType)
1750 : CGM(emitter.CGM), Emitter(emitter), Value(value), DestType(destType) {}
1751
1752 llvm::Constant *tryEmit();
1753
1754private:
1755 llvm::Constant *tryEmitAbsolute(llvm::Type *destTy);
1756 ConstantLValue tryEmitBase(const APValue::LValueBase &base);
1757
1758 ConstantLValue VisitStmt(const Stmt *S) { return nullptr; }
Bill Wendling8003edc2018-11-09 00:41:36 +00001759 ConstantLValue VisitConstantExpr(const ConstantExpr *E);
John McCall99e5e982017-08-17 05:03:55 +00001760 ConstantLValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1761 ConstantLValue VisitStringLiteral(const StringLiteral *E);
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001762 ConstantLValue VisitObjCBoxedExpr(const ObjCBoxedExpr *E);
John McCall99e5e982017-08-17 05:03:55 +00001763 ConstantLValue VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1764 ConstantLValue VisitObjCStringLiteral(const ObjCStringLiteral *E);
1765 ConstantLValue VisitPredefinedExpr(const PredefinedExpr *E);
1766 ConstantLValue VisitAddrLabelExpr(const AddrLabelExpr *E);
1767 ConstantLValue VisitCallExpr(const CallExpr *E);
1768 ConstantLValue VisitBlockExpr(const BlockExpr *E);
1769 ConstantLValue VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1770 ConstantLValue VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1771 ConstantLValue VisitMaterializeTemporaryExpr(
1772 const MaterializeTemporaryExpr *E);
1773
1774 bool hasNonZeroOffset() const {
1775 return !Value.getLValueOffset().isZero();
1776 }
1777
1778 /// Return the value offset.
1779 llvm::Constant *getOffset() {
1780 return llvm::ConstantInt::get(CGM.Int64Ty,
1781 Value.getLValueOffset().getQuantity());
1782 }
1783
1784 /// Apply the value offset to the given constant.
1785 llvm::Constant *applyOffset(llvm::Constant *C) {
1786 if (!hasNonZeroOffset())
1787 return C;
1788
1789 llvm::Type *origPtrTy = C->getType();
1790 unsigned AS = origPtrTy->getPointerAddressSpace();
1791 llvm::Type *charPtrTy = CGM.Int8Ty->getPointerTo(AS);
1792 C = llvm::ConstantExpr::getBitCast(C, charPtrTy);
1793 C = llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, C, getOffset());
1794 C = llvm::ConstantExpr::getPointerCast(C, origPtrTy);
1795 return C;
1796 }
1797};
1798
1799}
1800
1801llvm::Constant *ConstantLValueEmitter::tryEmit() {
1802 const APValue::LValueBase &base = Value.getLValueBase();
1803
Eli Friedman7f98e3c2019-02-08 21:36:04 +00001804 // The destination type should be a pointer or reference
John McCall99e5e982017-08-17 05:03:55 +00001805 // type, but it might also be a cast thereof.
1806 //
1807 // FIXME: the chain of casts required should be reflected in the APValue.
1808 // We need this in order to correctly handle things like a ptrtoint of a
1809 // non-zero null pointer and addrspace casts that aren't trivially
1810 // represented in LLVM IR.
1811 auto destTy = CGM.getTypes().ConvertTypeForMem(DestType);
1812 assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy));
1813
1814 // If there's no base at all, this is a null or absolute pointer,
1815 // possibly cast back to an integer type.
1816 if (!base) {
1817 return tryEmitAbsolute(destTy);
1818 }
1819
1820 // Otherwise, try to emit the base.
1821 ConstantLValue result = tryEmitBase(base);
1822
1823 // If that failed, we're done.
1824 llvm::Constant *value = result.Value;
1825 if (!value) return nullptr;
1826
1827 // Apply the offset if necessary and not already done.
1828 if (!result.HasOffsetApplied) {
1829 value = applyOffset(value);
1830 }
1831
1832 // Convert to the appropriate type; this could be an lvalue for
1833 // an integer. FIXME: performAddrSpaceCast
1834 if (isa<llvm::PointerType>(destTy))
1835 return llvm::ConstantExpr::getPointerCast(value, destTy);
1836
1837 return llvm::ConstantExpr::getPtrToInt(value, destTy);
1838}
1839
1840/// Try to emit an absolute l-value, such as a null pointer or an integer
1841/// bitcast to pointer type.
1842llvm::Constant *
1843ConstantLValueEmitter::tryEmitAbsolute(llvm::Type *destTy) {
John McCall99e5e982017-08-17 05:03:55 +00001844 // If we're producing a pointer, this is easy.
Don Hintonf170dff2019-03-19 06:14:14 +00001845 auto destPtrTy = cast<llvm::PointerType>(destTy);
1846 if (Value.isNullPointer()) {
1847 // FIXME: integer offsets from non-zero null pointers.
1848 return CGM.getNullPointer(destPtrTy, DestType);
John McCall99e5e982017-08-17 05:03:55 +00001849 }
1850
Don Hintonf170dff2019-03-19 06:14:14 +00001851 // Convert the integer to a pointer-sized integer before converting it
1852 // to a pointer.
1853 // FIXME: signedness depends on the original integer type.
1854 auto intptrTy = CGM.getDataLayout().getIntPtrType(destPtrTy);
Simon Pilgrim3ff9c512019-05-11 11:01:46 +00001855 llvm::Constant *C;
Don Hintonf170dff2019-03-19 06:14:14 +00001856 C = llvm::ConstantExpr::getIntegerCast(getOffset(), intptrTy,
1857 /*isSigned*/ false);
1858 C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy);
John McCall99e5e982017-08-17 05:03:55 +00001859 return C;
1860}
1861
1862ConstantLValue
1863ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
1864 // Handle values.
1865 if (const ValueDecl *D = base.dyn_cast<const ValueDecl*>()) {
1866 if (D->hasAttr<WeakRefAttr>())
1867 return CGM.GetWeakRefReference(D).getPointer();
1868
1869 if (auto FD = dyn_cast<FunctionDecl>(D))
1870 return CGM.GetAddrOfFunction(FD);
1871
1872 if (auto VD = dyn_cast<VarDecl>(D)) {
1873 // We can never refer to a variable with local storage.
1874 if (!VD->hasLocalStorage()) {
1875 if (VD->isFileVarDecl() || VD->hasExternalStorage())
1876 return CGM.GetAddrOfGlobalVar(VD);
1877
1878 if (VD->isLocalVarDecl()) {
1879 return CGM.getOrCreateStaticVarDecl(
1880 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false));
1881 }
1882 }
1883 }
1884
1885 return nullptr;
1886 }
1887
Richard Smithee0ce3022019-05-17 07:06:46 +00001888 // Handle typeid(T).
1889 if (TypeInfoLValue TI = base.dyn_cast<TypeInfoLValue>()) {
1890 llvm::Type *StdTypeInfoPtrTy =
1891 CGM.getTypes().ConvertType(base.getTypeInfoType())->getPointerTo();
1892 llvm::Constant *TypeInfo =
1893 CGM.GetAddrOfRTTIDescriptor(QualType(TI.getType(), 0));
1894 if (TypeInfo->getType() != StdTypeInfoPtrTy)
1895 TypeInfo = llvm::ConstantExpr::getBitCast(TypeInfo, StdTypeInfoPtrTy);
1896 return TypeInfo;
1897 }
1898
John McCall99e5e982017-08-17 05:03:55 +00001899 // Otherwise, it must be an expression.
1900 return Visit(base.get<const Expr*>());
1901}
1902
1903ConstantLValue
Bill Wendling8003edc2018-11-09 00:41:36 +00001904ConstantLValueEmitter::VisitConstantExpr(const ConstantExpr *E) {
1905 return Visit(E->getSubExpr());
1906}
1907
1908ConstantLValue
John McCall99e5e982017-08-17 05:03:55 +00001909ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1910 return tryEmitGlobalCompoundLiteral(CGM, Emitter.CGF, E);
1911}
1912
1913ConstantLValue
1914ConstantLValueEmitter::VisitStringLiteral(const StringLiteral *E) {
1915 return CGM.GetAddrOfConstantStringFromLiteral(E);
1916}
1917
1918ConstantLValue
1919ConstantLValueEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
1920 return CGM.GetAddrOfConstantStringFromObjCEncode(E);
1921}
1922
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001923static ConstantLValue emitConstantObjCStringLiteral(const StringLiteral *S,
1924 QualType T,
1925 CodeGenModule &CGM) {
1926 auto C = CGM.getObjCRuntime().GenerateConstantString(S);
1927 return C.getElementBitCast(CGM.getTypes().ConvertTypeForMem(T));
1928}
1929
John McCall99e5e982017-08-17 05:03:55 +00001930ConstantLValue
1931ConstantLValueEmitter::VisitObjCStringLiteral(const ObjCStringLiteral *E) {
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001932 return emitConstantObjCStringLiteral(E->getString(), E->getType(), CGM);
1933}
1934
1935ConstantLValue
1936ConstantLValueEmitter::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
1937 assert(E->isExpressibleAsConstantInitializer() &&
1938 "this boxed expression can't be emitted as a compile-time constant");
1939 auto *SL = cast<StringLiteral>(E->getSubExpr()->IgnoreParenCasts());
1940 return emitConstantObjCStringLiteral(SL, E->getType(), CGM);
John McCall99e5e982017-08-17 05:03:55 +00001941}
1942
1943ConstantLValue
1944ConstantLValueEmitter::VisitPredefinedExpr(const PredefinedExpr *E) {
Eli Friedman3f82f9e2019-01-22 00:11:17 +00001945 return CGM.GetAddrOfConstantStringFromLiteral(E->getFunctionName());
John McCall99e5e982017-08-17 05:03:55 +00001946}
1947
1948ConstantLValue
1949ConstantLValueEmitter::VisitAddrLabelExpr(const AddrLabelExpr *E) {
1950 assert(Emitter.CGF && "Invalid address of label expression outside function");
1951 llvm::Constant *Ptr = Emitter.CGF->GetAddrOfLabel(E->getLabel());
1952 Ptr = llvm::ConstantExpr::getBitCast(Ptr,
1953 CGM.getTypes().ConvertType(E->getType()));
1954 return Ptr;
1955}
1956
1957ConstantLValue
1958ConstantLValueEmitter::VisitCallExpr(const CallExpr *E) {
1959 unsigned builtin = E->getBuiltinCallee();
1960 if (builtin != Builtin::BI__builtin___CFStringMakeConstantString &&
1961 builtin != Builtin::BI__builtin___NSStringMakeConstantString)
1962 return nullptr;
1963
1964 auto literal = cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts());
1965 if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) {
1966 return CGM.getObjCRuntime().GenerateConstantString(literal);
1967 } else {
1968 // FIXME: need to deal with UCN conversion issues.
1969 return CGM.GetAddrOfConstantCFString(literal);
1970 }
1971}
1972
1973ConstantLValue
1974ConstantLValueEmitter::VisitBlockExpr(const BlockExpr *E) {
1975 StringRef functionName;
1976 if (auto CGF = Emitter.CGF)
1977 functionName = CGF->CurFn->getName();
1978 else
1979 functionName = "global";
1980
1981 return CGM.GetAddrOfGlobalBlock(E, functionName);
1982}
1983
1984ConstantLValue
1985ConstantLValueEmitter::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
1986 QualType T;
1987 if (E->isTypeOperand())
1988 T = E->getTypeOperand(CGM.getContext());
1989 else
1990 T = E->getExprOperand()->getType();
1991 return CGM.GetAddrOfRTTIDescriptor(T);
1992}
1993
1994ConstantLValue
1995ConstantLValueEmitter::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
1996 return CGM.GetAddrOfUuidDescriptor(E);
1997}
1998
1999ConstantLValue
2000ConstantLValueEmitter::VisitMaterializeTemporaryExpr(
2001 const MaterializeTemporaryExpr *E) {
2002 assert(E->getStorageDuration() == SD_Static);
2003 SmallVector<const Expr *, 2> CommaLHSs;
2004 SmallVector<SubobjectAdjustment, 2> Adjustments;
2005 const Expr *Inner = E->GetTemporaryExpr()
2006 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
2007 return CGM.GetAddrOfGlobalTemporary(E, Inner);
2008}
2009
John McCallde0fe072017-08-15 21:42:52 +00002010llvm::Constant *ConstantEmitter::tryEmitPrivate(const APValue &Value,
2011 QualType DestType) {
Richard Smithdafff942012-01-14 04:30:29 +00002012 switch (Value.getKind()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002013 case APValue::None:
2014 case APValue::Indeterminate:
2015 // Out-of-lifetime and indeterminate values can be modeled as 'undef'.
2016 return llvm::UndefValue::get(CGM.getTypes().ConvertType(DestType));
John McCall99e5e982017-08-17 05:03:55 +00002017 case APValue::LValue:
2018 return ConstantLValueEmitter(*this, Value, DestType).tryEmit();
Richard Smithbc6387672012-03-02 23:27:11 +00002019 case APValue::Int:
John McCallde0fe072017-08-15 21:42:52 +00002020 return llvm::ConstantInt::get(CGM.getLLVMContext(), Value.getInt());
Leonard Chan86285d22019-01-16 18:53:05 +00002021 case APValue::FixedPoint:
2022 return llvm::ConstantInt::get(CGM.getLLVMContext(),
2023 Value.getFixedPoint().getValue());
Richard Smithdafff942012-01-14 04:30:29 +00002024 case APValue::ComplexInt: {
2025 llvm::Constant *Complex[2];
2026
John McCallde0fe072017-08-15 21:42:52 +00002027 Complex[0] = llvm::ConstantInt::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00002028 Value.getComplexIntReal());
John McCallde0fe072017-08-15 21:42:52 +00002029 Complex[1] = llvm::ConstantInt::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00002030 Value.getComplexIntImag());
2031
2032 // FIXME: the target may want to specify that this is packed.
Serge Guelton1d993272017-05-09 19:31:30 +00002033 llvm::StructType *STy =
2034 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
Richard Smithdafff942012-01-14 04:30:29 +00002035 return llvm::ConstantStruct::get(STy, Complex);
2036 }
2037 case APValue::Float: {
2038 const llvm::APFloat &Init = Value.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002039 if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() &&
John McCallde0fe072017-08-15 21:42:52 +00002040 !CGM.getContext().getLangOpts().NativeHalfType &&
Akira Hatanaka502775a2017-12-09 00:02:37 +00002041 CGM.getContext().getTargetInfo().useFP16ConversionIntrinsics())
John McCallde0fe072017-08-15 21:42:52 +00002042 return llvm::ConstantInt::get(CGM.getLLVMContext(),
2043 Init.bitcastToAPInt());
Richard Smithdafff942012-01-14 04:30:29 +00002044 else
John McCallde0fe072017-08-15 21:42:52 +00002045 return llvm::ConstantFP::get(CGM.getLLVMContext(), Init);
Richard Smithdafff942012-01-14 04:30:29 +00002046 }
2047 case APValue::ComplexFloat: {
2048 llvm::Constant *Complex[2];
2049
John McCallde0fe072017-08-15 21:42:52 +00002050 Complex[0] = llvm::ConstantFP::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00002051 Value.getComplexFloatReal());
John McCallde0fe072017-08-15 21:42:52 +00002052 Complex[1] = llvm::ConstantFP::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00002053 Value.getComplexFloatImag());
2054
2055 // FIXME: the target may want to specify that this is packed.
Serge Guelton1d993272017-05-09 19:31:30 +00002056 llvm::StructType *STy =
2057 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
Richard Smithdafff942012-01-14 04:30:29 +00002058 return llvm::ConstantStruct::get(STy, Complex);
2059 }
2060 case APValue::Vector: {
Richard Smithdafff942012-01-14 04:30:29 +00002061 unsigned NumElts = Value.getVectorLength();
George Burgess IV533ff002015-12-11 00:23:35 +00002062 SmallVector<llvm::Constant *, 4> Inits(NumElts);
Richard Smithdafff942012-01-14 04:30:29 +00002063
George Burgess IV533ff002015-12-11 00:23:35 +00002064 for (unsigned I = 0; I != NumElts; ++I) {
2065 const APValue &Elt = Value.getVectorElt(I);
Richard Smithdafff942012-01-14 04:30:29 +00002066 if (Elt.isInt())
John McCallde0fe072017-08-15 21:42:52 +00002067 Inits[I] = llvm::ConstantInt::get(CGM.getLLVMContext(), Elt.getInt());
George Burgess IV533ff002015-12-11 00:23:35 +00002068 else if (Elt.isFloat())
John McCallde0fe072017-08-15 21:42:52 +00002069 Inits[I] = llvm::ConstantFP::get(CGM.getLLVMContext(), Elt.getFloat());
Richard Smithdafff942012-01-14 04:30:29 +00002070 else
George Burgess IV533ff002015-12-11 00:23:35 +00002071 llvm_unreachable("unsupported vector element type");
Richard Smithdafff942012-01-14 04:30:29 +00002072 }
2073 return llvm::ConstantVector::get(Inits);
2074 }
2075 case APValue::AddrLabelDiff: {
2076 const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
2077 const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
John McCallde0fe072017-08-15 21:42:52 +00002078 llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->getType());
2079 llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->getType());
2080 if (!LHS || !RHS) return nullptr;
Richard Smithdafff942012-01-14 04:30:29 +00002081
2082 // Compute difference
John McCallde0fe072017-08-15 21:42:52 +00002083 llvm::Type *ResultType = CGM.getTypes().ConvertType(DestType);
2084 LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.IntPtrTy);
2085 RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.IntPtrTy);
Richard Smithdafff942012-01-14 04:30:29 +00002086 llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
2087
2088 // LLVM is a bit sensitive about the exact format of the
2089 // address-of-label difference; make sure to truncate after
2090 // the subtraction.
2091 return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
2092 }
2093 case APValue::Struct:
2094 case APValue::Union:
John McCallde0fe072017-08-15 21:42:52 +00002095 return ConstStructBuilder::BuildStruct(*this, Value, DestType);
Richard Smithdafff942012-01-14 04:30:29 +00002096 case APValue::Array: {
Richard Smith3e268632018-05-23 23:41:38 +00002097 const ConstantArrayType *CAT =
2098 CGM.getContext().getAsConstantArrayType(DestType);
Richard Smithdafff942012-01-14 04:30:29 +00002099 unsigned NumElements = Value.getArraySize();
2100 unsigned NumInitElts = Value.getArrayInitializedElts();
2101
Richard Smithdafff942012-01-14 04:30:29 +00002102 // Emit array filler, if there is one.
Craig Topper8a13c412014-05-21 05:09:00 +00002103 llvm::Constant *Filler = nullptr;
Richard Smith3e268632018-05-23 23:41:38 +00002104 if (Value.hasArrayFiller()) {
John McCallde0fe072017-08-15 21:42:52 +00002105 Filler = tryEmitAbstractForMemory(Value.getArrayFiller(),
2106 CAT->getElementType());
Richard Smith3e268632018-05-23 23:41:38 +00002107 if (!Filler)
2108 return nullptr;
Hans Wennborg156349f2018-05-23 08:24:01 +00002109 }
David Majnemer90d85442014-12-28 23:46:59 +00002110
Richard Smith3e268632018-05-23 23:41:38 +00002111 // Emit initializer elements.
John McCallde0fe072017-08-15 21:42:52 +00002112 SmallVector<llvm::Constant*, 16> Elts;
Richard Smith3e268632018-05-23 23:41:38 +00002113 if (Filler && Filler->isNullValue())
2114 Elts.reserve(NumInitElts + 1);
2115 else
2116 Elts.reserve(NumElements);
2117
2118 llvm::Type *CommonElementType = nullptr;
2119 for (unsigned I = 0; I < NumInitElts; ++I) {
2120 llvm::Constant *C = tryEmitPrivateForMemory(
2121 Value.getArrayInitializedElt(I), CAT->getElementType());
John McCallde0fe072017-08-15 21:42:52 +00002122 if (!C) return nullptr;
2123
Richard Smithdafff942012-01-14 04:30:29 +00002124 if (I == 0)
2125 CommonElementType = C->getType();
2126 else if (C->getType() != CommonElementType)
Craig Topper8a13c412014-05-21 05:09:00 +00002127 CommonElementType = nullptr;
Richard Smithdafff942012-01-14 04:30:29 +00002128 Elts.push_back(C);
2129 }
2130
Balaji V. Iyer749e8282018-08-08 00:01:21 +00002131 // This means that the array type is probably "IncompleteType" or some
2132 // type that is not ConstantArray.
2133 if (CAT == nullptr && CommonElementType == nullptr && !NumInitElts) {
2134 const ArrayType *AT = CGM.getContext().getAsArrayType(DestType);
2135 CommonElementType = CGM.getTypes().ConvertType(AT->getElementType());
2136 llvm::ArrayType *AType = llvm::ArrayType::get(CommonElementType,
2137 NumElements);
2138 return llvm::ConstantAggregateZero::get(AType);
2139 }
2140
Richard Smith5745feb2019-06-17 21:08:30 +00002141 llvm::ArrayType *Desired =
2142 cast<llvm::ArrayType>(CGM.getTypes().ConvertType(DestType));
2143 return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,
Richard Smith3e268632018-05-23 23:41:38 +00002144 Filler);
Richard Smithdafff942012-01-14 04:30:29 +00002145 }
2146 case APValue::MemberPointer:
John McCallde0fe072017-08-15 21:42:52 +00002147 return CGM.getCXXABI().EmitMemberPointer(Value, DestType);
Richard Smithdafff942012-01-14 04:30:29 +00002148 }
2149 llvm_unreachable("Unknown APValue kind");
2150}
2151
George Burgess IV1a39b862016-12-28 07:27:40 +00002152llvm::GlobalVariable *CodeGenModule::getAddrOfConstantCompoundLiteralIfEmitted(
2153 const CompoundLiteralExpr *E) {
2154 return EmittedCompoundLiterals.lookup(E);
2155}
2156
2157void CodeGenModule::setAddrOfConstantCompoundLiteral(
2158 const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV) {
2159 bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second;
2160 (void)Ok;
2161 assert(Ok && "CLE has already been emitted!");
2162}
2163
John McCall7f416cc2015-09-08 08:05:57 +00002164ConstantAddress
Richard Smith2d988f02011-11-22 22:48:32 +00002165CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
2166 assert(E->isFileScope() && "not a file-scope compound literal expr");
John McCallde0fe072017-08-15 21:42:52 +00002167 return tryEmitGlobalCompoundLiteral(*this, nullptr, E);
Richard Smith2d988f02011-11-22 22:48:32 +00002168}
2169
John McCallf3a88602011-02-03 08:15:49 +00002170llvm::Constant *
2171CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
2172 // Member pointer constants always have a very particular form.
2173 const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
2174 const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
2175
2176 // A member function pointer.
2177 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
David Majnemere2be95b2015-06-23 07:31:01 +00002178 return getCXXABI().EmitMemberFunctionPointer(method);
John McCallf3a88602011-02-03 08:15:49 +00002179
2180 // Otherwise, a member data pointer.
Richard Smithdafff942012-01-14 04:30:29 +00002181 uint64_t fieldOffset = getContext().getFieldOffset(decl);
John McCallf3a88602011-02-03 08:15:49 +00002182 CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
2183 return getCXXABI().EmitMemberDataPointer(type, chars);
2184}
2185
John McCall0217dfc22011-02-15 06:40:56 +00002186static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00002187 llvm::Type *baseType,
John McCall0217dfc22011-02-15 06:40:56 +00002188 const CXXRecordDecl *base);
2189
Anders Carlsson849ea412010-11-22 18:42:14 +00002190static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
Yaxun Liu402804b2016-12-15 08:09:08 +00002191 const RecordDecl *record,
John McCall0217dfc22011-02-15 06:40:56 +00002192 bool asCompleteObject) {
2193 const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
Chris Lattner2192fe52011-07-18 04:24:23 +00002194 llvm::StructType *structure =
John McCall0217dfc22011-02-15 06:40:56 +00002195 (asCompleteObject ? layout.getLLVMType()
2196 : layout.getBaseSubobjectLLVMType());
Anders Carlsson849ea412010-11-22 18:42:14 +00002197
John McCall0217dfc22011-02-15 06:40:56 +00002198 unsigned numElements = structure->getNumElements();
2199 std::vector<llvm::Constant *> elements(numElements);
Anders Carlsson849ea412010-11-22 18:42:14 +00002200
Yaxun Liu402804b2016-12-15 08:09:08 +00002201 auto CXXR = dyn_cast<CXXRecordDecl>(record);
John McCall0217dfc22011-02-15 06:40:56 +00002202 // Fill in all the bases.
Yaxun Liu402804b2016-12-15 08:09:08 +00002203 if (CXXR) {
2204 for (const auto &I : CXXR->bases()) {
2205 if (I.isVirtual()) {
2206 // Ignore virtual bases; if we're laying out for a complete
2207 // object, we'll lay these out later.
2208 continue;
2209 }
2210
2211 const CXXRecordDecl *base =
2212 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2213
2214 // Ignore empty bases.
2215 if (base->isEmpty() ||
2216 CGM.getContext().getASTRecordLayout(base).getNonVirtualSize()
2217 .isZero())
2218 continue;
2219
2220 unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
2221 llvm::Type *baseType = structure->getElementType(fieldIndex);
2222 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
Anders Carlsson849ea412010-11-22 18:42:14 +00002223 }
Anders Carlsson849ea412010-11-22 18:42:14 +00002224 }
2225
John McCall0217dfc22011-02-15 06:40:56 +00002226 // Fill in all the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002227 for (const auto *Field : record->fields()) {
Eli Friedmandae858a2011-12-07 01:30:11 +00002228 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
2229 // will fill in later.)
Richard Smith78b239e2019-06-20 20:44:45 +00002230 if (!Field->isBitField() && !Field->isZeroSize(CGM.getContext())) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002231 unsigned fieldIndex = layout.getLLVMFieldNo(Field);
2232 elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
Eli Friedmandae858a2011-12-07 01:30:11 +00002233 }
2234
2235 // For unions, stop after the first named field.
David Majnemer4e51dfc2015-05-30 09:12:07 +00002236 if (record->isUnion()) {
2237 if (Field->getIdentifier())
2238 break;
George Karpenkov39e51372018-07-28 02:16:13 +00002239 if (const auto *FieldRD = Field->getType()->getAsRecordDecl())
David Majnemer4e51dfc2015-05-30 09:12:07 +00002240 if (FieldRD->findFirstNamedDataMember())
2241 break;
2242 }
John McCall0217dfc22011-02-15 06:40:56 +00002243 }
2244
2245 // Fill in the virtual bases, if we're working with the complete object.
Yaxun Liu402804b2016-12-15 08:09:08 +00002246 if (CXXR && asCompleteObject) {
2247 for (const auto &I : CXXR->vbases()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002248 const CXXRecordDecl *base =
Aaron Ballman445a9392014-03-13 16:15:17 +00002249 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
John McCall0217dfc22011-02-15 06:40:56 +00002250
2251 // Ignore empty bases.
2252 if (base->isEmpty())
2253 continue;
2254
2255 unsigned fieldIndex = layout.getVirtualBaseIndex(base);
2256
2257 // We might have already laid this field out.
2258 if (elements[fieldIndex]) continue;
2259
Chris Lattner2192fe52011-07-18 04:24:23 +00002260 llvm::Type *baseType = structure->getElementType(fieldIndex);
John McCall0217dfc22011-02-15 06:40:56 +00002261 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2262 }
Anders Carlsson849ea412010-11-22 18:42:14 +00002263 }
2264
2265 // Now go through all other fields and zero them out.
John McCall0217dfc22011-02-15 06:40:56 +00002266 for (unsigned i = 0; i != numElements; ++i) {
2267 if (!elements[i])
2268 elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
Anders Carlsson849ea412010-11-22 18:42:14 +00002269 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002270
John McCall0217dfc22011-02-15 06:40:56 +00002271 return llvm::ConstantStruct::get(structure, elements);
2272}
2273
2274/// Emit the null constant for a base subobject.
2275static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00002276 llvm::Type *baseType,
John McCall0217dfc22011-02-15 06:40:56 +00002277 const CXXRecordDecl *base) {
2278 const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
2279
2280 // Just zero out bases that don't have any pointer to data members.
2281 if (baseLayout.isZeroInitializableAsBase())
2282 return llvm::Constant::getNullValue(baseType);
2283
David Majnemer2213bfe2014-10-17 01:00:43 +00002284 // Otherwise, we can just use its null constant.
2285 return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);
Anders Carlsson849ea412010-11-22 18:42:14 +00002286}
2287
John McCallde0fe072017-08-15 21:42:52 +00002288llvm::Constant *ConstantEmitter::emitNullForMemory(CodeGenModule &CGM,
2289 QualType T) {
2290 return emitForMemory(CGM, CGM.EmitNullConstant(T), T);
2291}
2292
Eli Friedman20bb5e02009-04-13 21:47:26 +00002293llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
Yaxun Liu402804b2016-12-15 08:09:08 +00002294 if (T->getAs<PointerType>())
2295 return getNullPointer(
2296 cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T);
2297
John McCall614dbdc2010-08-22 21:01:12 +00002298 if (getTypes().isZeroInitializable(T))
Anders Carlsson867b48f2009-08-24 17:16:23 +00002299 return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
Fangrui Song6907ce22018-07-30 19:24:48 +00002300
Anders Carlssonf48123b2009-08-09 18:26:27 +00002301 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
Chris Lattner72977a12012-02-06 22:00:56 +00002302 llvm::ArrayType *ATy =
2303 cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
Mike Stump11289f42009-09-09 15:08:12 +00002304
Anders Carlssonf48123b2009-08-09 18:26:27 +00002305 QualType ElementTy = CAT->getElementType();
2306
John McCallde0fe072017-08-15 21:42:52 +00002307 llvm::Constant *Element =
2308 ConstantEmitter::emitNullForMemory(*this, ElementTy);
Anders Carlssone8bfe412010-02-02 05:17:25 +00002309 unsigned NumElements = CAT->getSize().getZExtValue();
Chris Lattner72977a12012-02-06 22:00:56 +00002310 SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
Anders Carlssone8bfe412010-02-02 05:17:25 +00002311 return llvm::ConstantArray::get(ATy, Array);
Anders Carlssonf48123b2009-08-09 18:26:27 +00002312 }
Anders Carlssond606de72009-08-23 01:25:01 +00002313
Yaxun Liu402804b2016-12-15 08:09:08 +00002314 if (const RecordType *RT = T->getAs<RecordType>())
2315 return ::EmitNullConstant(*this, RT->getDecl(), /*complete object*/ true);
Mike Stump11289f42009-09-09 15:08:12 +00002316
David Majnemer5fd33e02015-04-24 01:25:08 +00002317 assert(T->isMemberDataPointerType() &&
Anders Carlssone8bfe412010-02-02 05:17:25 +00002318 "Should only see pointers to data members here!");
David Majnemer2213bfe2014-10-17 01:00:43 +00002319
John McCallf3a88602011-02-03 08:15:49 +00002320 return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
Eli Friedman20bb5e02009-04-13 21:47:26 +00002321}
Eli Friedmanfde961d2011-10-14 02:27:24 +00002322
2323llvm::Constant *
2324CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
2325 return ::EmitNullConstant(*this, Record, false);
2326}