forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCGExprConstant.cpp
2731 lines (2320 loc) · 101 KB
/
CGExprConstant.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This contains code to emit Constant Expr nodes as LLVM code.
//
//===----------------------------------------------------------------------===//
#include "ABIInfoImpl.h"
#include "CGCXXABI.h"
#include "CGObjCRuntime.h"
#include "CGRecordLayout.h"
#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "ConstantEmitter.h"
#include "TargetInfo.h"
#include "clang/AST/APValue.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/Basic/Builtins.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Sequence.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include <optional>
using namespace clang;
using namespace CodeGen;
//===----------------------------------------------------------------------===//
// ConstantAggregateBuilder
//===----------------------------------------------------------------------===//
namespace {
class ConstExprEmitter;
llvm::Constant *getPadding(const CodeGenModule &CGM, CharUnits PadSize) {
llvm::Type *Ty = CGM.CharTy;
if (PadSize > CharUnits::One())
Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
if (CGM.shouldZeroInitPadding()) {
return llvm::Constant::getNullValue(Ty);
}
return llvm::UndefValue::get(Ty);
}
struct ConstantAggregateBuilderUtils {
CodeGenModule &CGM;
ConstantAggregateBuilderUtils(CodeGenModule &CGM) : CGM(CGM) {}
CharUnits getAlignment(const llvm::Constant *C) const {
return CharUnits::fromQuantity(
CGM.getDataLayout().getABITypeAlign(C->getType()));
}
CharUnits getSize(llvm::Type *Ty) const {
return CharUnits::fromQuantity(CGM.getDataLayout().getTypeAllocSize(Ty));
}
CharUnits getSize(const llvm::Constant *C) const {
return getSize(C->getType());
}
llvm::Constant *getPadding(CharUnits PadSize) const {
return ::getPadding(CGM, PadSize);
}
llvm::Constant *getZeroes(CharUnits ZeroSize) const {
llvm::Type *Ty = llvm::ArrayType::get(CGM.CharTy, ZeroSize.getQuantity());
return llvm::ConstantAggregateZero::get(Ty);
}
};
/// Incremental builder for an llvm::Constant* holding a struct or array
/// constant.
class ConstantAggregateBuilder : private ConstantAggregateBuilderUtils {
/// The elements of the constant. These two arrays must have the same size;
/// Offsets[i] describes the offset of Elems[i] within the constant. The
/// elements are kept in increasing offset order, and we ensure that there
/// is no overlap: Offsets[i+1] >= Offsets[i] + getSize(Elemes[i]).
///
/// This may contain explicit padding elements (in order to create a
/// natural layout), but need not. Gaps between elements are implicitly
/// considered to be filled with undef.
llvm::SmallVector<llvm::Constant*, 32> Elems;
llvm::SmallVector<CharUnits, 32> Offsets;
/// The size of the constant (the maximum end offset of any added element).
/// May be larger than the end of Elems.back() if we split the last element
/// and removed some trailing undefs.
CharUnits Size = CharUnits::Zero();
/// This is true only if laying out Elems in order as the elements of a
/// non-packed LLVM struct will give the correct layout.
bool NaturalLayout = true;
bool split(size_t Index, CharUnits Hint);
std::optional<size_t> splitAt(CharUnits Pos);
static llvm::Constant *buildFrom(CodeGenModule &CGM,
ArrayRef<llvm::Constant *> Elems,
ArrayRef<CharUnits> Offsets,
CharUnits StartOffset, CharUnits Size,
bool NaturalLayout, llvm::Type *DesiredTy,
bool AllowOversized);
public:
ConstantAggregateBuilder(CodeGenModule &CGM)
: ConstantAggregateBuilderUtils(CGM) {}
/// Update or overwrite the value starting at \p Offset with \c C.
///
/// \param AllowOverwrite If \c true, this constant might overwrite (part of)
/// a constant that has already been added. This flag is only used to
/// detect bugs.
bool add(llvm::Constant *C, CharUnits Offset, bool AllowOverwrite);
/// Update or overwrite the bits starting at \p OffsetInBits with \p Bits.
bool addBits(llvm::APInt Bits, uint64_t OffsetInBits, bool AllowOverwrite);
/// Attempt to condense the value starting at \p Offset to a constant of type
/// \p DesiredTy.
void condense(CharUnits Offset, llvm::Type *DesiredTy);
/// Produce a constant representing the entire accumulated value, ideally of
/// the specified type. If \p AllowOversized, the constant might be larger
/// than implied by \p DesiredTy (eg, if there is a flexible array member).
/// Otherwise, the constant will be of exactly the same size as \p DesiredTy
/// even if we can't represent it as that type.
llvm::Constant *build(llvm::Type *DesiredTy, bool AllowOversized) const {
return buildFrom(CGM, Elems, Offsets, CharUnits::Zero(), Size,
NaturalLayout, DesiredTy, AllowOversized);
}
};
template<typename Container, typename Range = std::initializer_list<
typename Container::value_type>>
static void replace(Container &C, size_t BeginOff, size_t EndOff, Range Vals) {
assert(BeginOff <= EndOff && "invalid replacement range");
llvm::replace(C, C.begin() + BeginOff, C.begin() + EndOff, Vals);
}
bool ConstantAggregateBuilder::add(llvm::Constant *C, CharUnits Offset,
bool AllowOverwrite) {
// Common case: appending to a layout.
if (Offset >= Size) {
CharUnits Align = getAlignment(C);
CharUnits AlignedSize = Size.alignTo(Align);
if (AlignedSize > Offset || Offset.alignTo(Align) != Offset)
NaturalLayout = false;
else if (AlignedSize < Offset) {
Elems.push_back(getPadding(Offset - Size));
Offsets.push_back(Size);
}
Elems.push_back(C);
Offsets.push_back(Offset);
Size = Offset + getSize(C);
return true;
}
// Uncommon case: constant overlaps what we've already created.
std::optional<size_t> FirstElemToReplace = splitAt(Offset);
if (!FirstElemToReplace)
return false;
CharUnits CSize = getSize(C);
std::optional<size_t> LastElemToReplace = splitAt(Offset + CSize);
if (!LastElemToReplace)
return false;
assert((FirstElemToReplace == LastElemToReplace || AllowOverwrite) &&
"unexpectedly overwriting field");
replace(Elems, *FirstElemToReplace, *LastElemToReplace, {C});
replace(Offsets, *FirstElemToReplace, *LastElemToReplace, {Offset});
Size = std::max(Size, Offset + CSize);
NaturalLayout = false;
return true;
}
bool ConstantAggregateBuilder::addBits(llvm::APInt Bits, uint64_t OffsetInBits,
bool AllowOverwrite) {
const ASTContext &Context = CGM.getContext();
const uint64_t CharWidth = CGM.getContext().getCharWidth();
// Offset of where we want the first bit to go within the bits of the
// current char.
unsigned OffsetWithinChar = OffsetInBits % CharWidth;
// We split bit-fields up into individual bytes. Walk over the bytes and
// update them.
for (CharUnits OffsetInChars =
Context.toCharUnitsFromBits(OffsetInBits - OffsetWithinChar);
/**/; ++OffsetInChars) {
// Number of bits we want to fill in this char.
unsigned WantedBits =
std::min((uint64_t)Bits.getBitWidth(), CharWidth - OffsetWithinChar);
// Get a char containing the bits we want in the right places. The other
// bits have unspecified values.
llvm::APInt BitsThisChar = Bits;
if (BitsThisChar.getBitWidth() < CharWidth)
BitsThisChar = BitsThisChar.zext(CharWidth);
if (CGM.getDataLayout().isBigEndian()) {
// Figure out how much to shift by. We may need to left-shift if we have
// less than one byte of Bits left.
int Shift = Bits.getBitWidth() - CharWidth + OffsetWithinChar;
if (Shift > 0)
BitsThisChar.lshrInPlace(Shift);
else if (Shift < 0)
BitsThisChar = BitsThisChar.shl(-Shift);
} else {
BitsThisChar = BitsThisChar.shl(OffsetWithinChar);
}
if (BitsThisChar.getBitWidth() > CharWidth)
BitsThisChar = BitsThisChar.trunc(CharWidth);
if (WantedBits == CharWidth) {
// Got a full byte: just add it directly.
add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar),
OffsetInChars, AllowOverwrite);
} else {
// Partial byte: update the existing integer if there is one. If we
// can't split out a 1-CharUnit range to update, then we can't add
// these bits and fail the entire constant emission.
std::optional<size_t> FirstElemToUpdate = splitAt(OffsetInChars);
if (!FirstElemToUpdate)
return false;
std::optional<size_t> LastElemToUpdate =
splitAt(OffsetInChars + CharUnits::One());
if (!LastElemToUpdate)
return false;
assert(*LastElemToUpdate - *FirstElemToUpdate < 2 &&
"should have at most one element covering one byte");
// Figure out which bits we want and discard the rest.
llvm::APInt UpdateMask(CharWidth, 0);
if (CGM.getDataLayout().isBigEndian())
UpdateMask.setBits(CharWidth - OffsetWithinChar - WantedBits,
CharWidth - OffsetWithinChar);
else
UpdateMask.setBits(OffsetWithinChar, OffsetWithinChar + WantedBits);
BitsThisChar &= UpdateMask;
if (*FirstElemToUpdate == *LastElemToUpdate ||
Elems[*FirstElemToUpdate]->isNullValue() ||
isa<llvm::UndefValue>(Elems[*FirstElemToUpdate])) {
// All existing bits are either zero or undef.
add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar),
OffsetInChars, /*AllowOverwrite*/ true);
} else {
llvm::Constant *&ToUpdate = Elems[*FirstElemToUpdate];
// In order to perform a partial update, we need the existing bitwise
// value, which we can only extract for a constant int.
auto *CI = dyn_cast<llvm::ConstantInt>(ToUpdate);
if (!CI)
return false;
// Because this is a 1-CharUnit range, the constant occupying it must
// be exactly one CharUnit wide.
assert(CI->getBitWidth() == CharWidth && "splitAt failed");
assert((!(CI->getValue() & UpdateMask) || AllowOverwrite) &&
"unexpectedly overwriting bitfield");
BitsThisChar |= (CI->getValue() & ~UpdateMask);
ToUpdate = llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar);
}
}
// Stop if we've added all the bits.
if (WantedBits == Bits.getBitWidth())
break;
// Remove the consumed bits from Bits.
if (!CGM.getDataLayout().isBigEndian())
Bits.lshrInPlace(WantedBits);
Bits = Bits.trunc(Bits.getBitWidth() - WantedBits);
// The remanining bits go at the start of the following bytes.
OffsetWithinChar = 0;
}
return true;
}
/// Returns a position within Elems and Offsets such that all elements
/// before the returned index end before Pos and all elements at or after
/// the returned index begin at or after Pos. Splits elements as necessary
/// to ensure this. Returns std::nullopt if we find something we can't split.
std::optional<size_t> ConstantAggregateBuilder::splitAt(CharUnits Pos) {
if (Pos >= Size)
return Offsets.size();
while (true) {
auto FirstAfterPos = llvm::upper_bound(Offsets, Pos);
if (FirstAfterPos == Offsets.begin())
return 0;
// If we already have an element starting at Pos, we're done.
size_t LastAtOrBeforePosIndex = FirstAfterPos - Offsets.begin() - 1;
if (Offsets[LastAtOrBeforePosIndex] == Pos)
return LastAtOrBeforePosIndex;
// We found an element starting before Pos. Check for overlap.
if (Offsets[LastAtOrBeforePosIndex] +
getSize(Elems[LastAtOrBeforePosIndex]) <= Pos)
return LastAtOrBeforePosIndex + 1;
// Try to decompose it into smaller constants.
if (!split(LastAtOrBeforePosIndex, Pos))
return std::nullopt;
}
}
/// Split the constant at index Index, if possible. Return true if we did.
/// Hint indicates the location at which we'd like to split, but may be
/// ignored.
bool ConstantAggregateBuilder::split(size_t Index, CharUnits Hint) {
NaturalLayout = false;
llvm::Constant *C = Elems[Index];
CharUnits Offset = Offsets[Index];
if (auto *CA = dyn_cast<llvm::ConstantAggregate>(C)) {
// Expand the sequence into its contained elements.
// FIXME: This assumes vector elements are byte-sized.
replace(Elems, Index, Index + 1,
llvm::map_range(llvm::seq(0u, CA->getNumOperands()),
[&](unsigned Op) { return CA->getOperand(Op); }));
if (isa<llvm::ArrayType>(CA->getType()) ||
isa<llvm::VectorType>(CA->getType())) {
// Array or vector.
llvm::Type *ElemTy =
llvm::GetElementPtrInst::getTypeAtIndex(CA->getType(), (uint64_t)0);
CharUnits ElemSize = getSize(ElemTy);
replace(
Offsets, Index, Index + 1,
llvm::map_range(llvm::seq(0u, CA->getNumOperands()),
[&](unsigned Op) { return Offset + Op * ElemSize; }));
} else {
// Must be a struct.
auto *ST = cast<llvm::StructType>(CA->getType());
const llvm::StructLayout *Layout =
CGM.getDataLayout().getStructLayout(ST);
replace(Offsets, Index, Index + 1,
llvm::map_range(
llvm::seq(0u, CA->getNumOperands()), [&](unsigned Op) {
return Offset + CharUnits::fromQuantity(
Layout->getElementOffset(Op));
}));
}
return true;
}
if (auto *CDS = dyn_cast<llvm::ConstantDataSequential>(C)) {
// Expand the sequence into its contained elements.
// FIXME: This assumes vector elements are byte-sized.
// FIXME: If possible, split into two ConstantDataSequentials at Hint.
CharUnits ElemSize = getSize(CDS->getElementType());
replace(Elems, Index, Index + 1,
llvm::map_range(llvm::seq(0u, CDS->getNumElements()),
[&](unsigned Elem) {
return CDS->getElementAsConstant(Elem);
}));
replace(Offsets, Index, Index + 1,
llvm::map_range(
llvm::seq(0u, CDS->getNumElements()),
[&](unsigned Elem) { return Offset + Elem * ElemSize; }));
return true;
}
if (isa<llvm::ConstantAggregateZero>(C)) {
// Split into two zeros at the hinted offset.
CharUnits ElemSize = getSize(C);
assert(Hint > Offset && Hint < Offset + ElemSize && "nothing to split");
replace(Elems, Index, Index + 1,
{getZeroes(Hint - Offset), getZeroes(Offset + ElemSize - Hint)});
replace(Offsets, Index, Index + 1, {Offset, Hint});
return true;
}
if (isa<llvm::UndefValue>(C)) {
// Drop undef; it doesn't contribute to the final layout.
replace(Elems, Index, Index + 1, {});
replace(Offsets, Index, Index + 1, {});
return true;
}
// FIXME: We could split a ConstantInt if the need ever arose.
// We don't need to do this to handle bit-fields because we always eagerly
// split them into 1-byte chunks.
return false;
}
static llvm::Constant *
EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,
llvm::Type *CommonElementType, uint64_t ArrayBound,
SmallVectorImpl<llvm::Constant *> &Elements,
llvm::Constant *Filler);
llvm::Constant *ConstantAggregateBuilder::buildFrom(
CodeGenModule &CGM, ArrayRef<llvm::Constant *> Elems,
ArrayRef<CharUnits> Offsets, CharUnits StartOffset, CharUnits Size,
bool NaturalLayout, llvm::Type *DesiredTy, bool AllowOversized) {
ConstantAggregateBuilderUtils Utils(CGM);
if (Elems.empty())
return llvm::UndefValue::get(DesiredTy);
auto Offset = [&](size_t I) { return Offsets[I] - StartOffset; };
// If we want an array type, see if all the elements are the same type and
// appropriately spaced.
if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(DesiredTy)) {
assert(!AllowOversized && "oversized array emission not supported");
bool CanEmitArray = true;
llvm::Type *CommonType = Elems[0]->getType();
llvm::Constant *Filler = llvm::Constant::getNullValue(CommonType);
CharUnits ElemSize = Utils.getSize(ATy->getElementType());
SmallVector<llvm::Constant*, 32> ArrayElements;
for (size_t I = 0; I != Elems.size(); ++I) {
// Skip zeroes; we'll use a zero value as our array filler.
if (Elems[I]->isNullValue())
continue;
// All remaining elements must be the same type.
if (Elems[I]->getType() != CommonType ||
Offset(I) % ElemSize != 0) {
CanEmitArray = false;
break;
}
ArrayElements.resize(Offset(I) / ElemSize + 1, Filler);
ArrayElements.back() = Elems[I];
}
if (CanEmitArray) {
return EmitArrayConstant(CGM, ATy, CommonType, ATy->getNumElements(),
ArrayElements, Filler);
}
// Can't emit as an array, carry on to emit as a struct.
}
// The size of the constant we plan to generate. This is usually just
// the size of the initialized type, but in AllowOversized mode (i.e.
// flexible array init), it can be larger.
CharUnits DesiredSize = Utils.getSize(DesiredTy);
if (Size > DesiredSize) {
assert(AllowOversized && "Elems are oversized");
DesiredSize = Size;
}
// The natural alignment of an unpacked LLVM struct with the given elements.
CharUnits Align = CharUnits::One();
for (llvm::Constant *C : Elems)
Align = std::max(Align, Utils.getAlignment(C));
// The natural size of an unpacked LLVM struct with the given elements.
CharUnits AlignedSize = Size.alignTo(Align);
bool Packed = false;
ArrayRef<llvm::Constant*> UnpackedElems = Elems;
llvm::SmallVector<llvm::Constant*, 32> UnpackedElemStorage;
if (DesiredSize < AlignedSize || DesiredSize.alignTo(Align) != DesiredSize) {
// The natural layout would be too big; force use of a packed layout.
NaturalLayout = false;
Packed = true;
} else if (DesiredSize > AlignedSize) {
// The natural layout would be too small. Add padding to fix it. (This
// is ignored if we choose a packed layout.)
UnpackedElemStorage.assign(Elems.begin(), Elems.end());
UnpackedElemStorage.push_back(Utils.getPadding(DesiredSize - Size));
UnpackedElems = UnpackedElemStorage;
}
// If we don't have a natural layout, insert padding as necessary.
// As we go, double-check to see if we can actually just emit Elems
// as a non-packed struct and do so opportunistically if possible.
llvm::SmallVector<llvm::Constant*, 32> PackedElems;
if (!NaturalLayout) {
CharUnits SizeSoFar = CharUnits::Zero();
for (size_t I = 0; I != Elems.size(); ++I) {
CharUnits Align = Utils.getAlignment(Elems[I]);
CharUnits NaturalOffset = SizeSoFar.alignTo(Align);
CharUnits DesiredOffset = Offset(I);
assert(DesiredOffset >= SizeSoFar && "elements out of order");
if (DesiredOffset != NaturalOffset)
Packed = true;
if (DesiredOffset != SizeSoFar)
PackedElems.push_back(Utils.getPadding(DesiredOffset - SizeSoFar));
PackedElems.push_back(Elems[I]);
SizeSoFar = DesiredOffset + Utils.getSize(Elems[I]);
}
// If we're using the packed layout, pad it out to the desired size if
// necessary.
if (Packed) {
assert(SizeSoFar <= DesiredSize &&
"requested size is too small for contents");
if (SizeSoFar < DesiredSize)
PackedElems.push_back(Utils.getPadding(DesiredSize - SizeSoFar));
}
}
llvm::StructType *STy = llvm::ConstantStruct::getTypeForElements(
CGM.getLLVMContext(), Packed ? PackedElems : UnpackedElems, Packed);
// Pick the type to use. If the type is layout identical to the desired
// type then use it, otherwise use whatever the builder produced for us.
if (llvm::StructType *DesiredSTy = dyn_cast<llvm::StructType>(DesiredTy)) {
if (DesiredSTy->isLayoutIdentical(STy))
STy = DesiredSTy;
}
return llvm::ConstantStruct::get(STy, Packed ? PackedElems : UnpackedElems);
}
void ConstantAggregateBuilder::condense(CharUnits Offset,
llvm::Type *DesiredTy) {
CharUnits Size = getSize(DesiredTy);
std::optional<size_t> FirstElemToReplace = splitAt(Offset);
if (!FirstElemToReplace)
return;
size_t First = *FirstElemToReplace;
std::optional<size_t> LastElemToReplace = splitAt(Offset + Size);
if (!LastElemToReplace)
return;
size_t Last = *LastElemToReplace;
size_t Length = Last - First;
if (Length == 0)
return;
if (Length == 1 && Offsets[First] == Offset &&
getSize(Elems[First]) == Size) {
// Re-wrap single element structs if necessary. Otherwise, leave any single
// element constant of the right size alone even if it has the wrong type.
auto *STy = dyn_cast<llvm::StructType>(DesiredTy);
if (STy && STy->getNumElements() == 1 &&
STy->getElementType(0) == Elems[First]->getType())
Elems[First] = llvm::ConstantStruct::get(STy, Elems[First]);
return;
}
llvm::Constant *Replacement = buildFrom(
CGM, ArrayRef(Elems).slice(First, Length),
ArrayRef(Offsets).slice(First, Length), Offset, getSize(DesiredTy),
/*known to have natural layout=*/false, DesiredTy, false);
replace(Elems, First, Last, {Replacement});
replace(Offsets, First, Last, {Offset});
}
//===----------------------------------------------------------------------===//
// ConstStructBuilder
//===----------------------------------------------------------------------===//
class ConstStructBuilder {
CodeGenModule &CGM;
ConstantEmitter &Emitter;
ConstantAggregateBuilder &Builder;
CharUnits StartOffset;
public:
static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
const InitListExpr *ILE,
QualType StructTy);
static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
const APValue &Value, QualType ValTy);
static bool UpdateStruct(ConstantEmitter &Emitter,
ConstantAggregateBuilder &Const, CharUnits Offset,
const InitListExpr *Updater);
private:
ConstStructBuilder(ConstantEmitter &Emitter,
ConstantAggregateBuilder &Builder, CharUnits StartOffset)
: CGM(Emitter.CGM), Emitter(Emitter), Builder(Builder),
StartOffset(StartOffset) {}
bool AppendField(const FieldDecl *Field, uint64_t FieldOffset,
llvm::Constant *InitExpr, bool AllowOverwrite = false);
bool AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst,
bool AllowOverwrite = false);
bool AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
llvm::Constant *InitExpr, bool AllowOverwrite = false);
bool Build(const InitListExpr *ILE, bool AllowOverwrite);
bool Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
bool DoZeroInitPadding(const ASTRecordLayout &Layout, unsigned FieldNo,
const FieldDecl &Field, bool AllowOverwrite,
CharUnits &SizeSoFar, bool &ZeroFieldSize);
bool DoZeroInitPadding(const ASTRecordLayout &Layout, bool AllowOverwrite,
CharUnits SizeSoFar);
llvm::Constant *Finalize(QualType Ty);
};
bool ConstStructBuilder::AppendField(
const FieldDecl *Field, uint64_t FieldOffset, llvm::Constant *InitCst,
bool AllowOverwrite) {
const ASTContext &Context = CGM.getContext();
CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
return AppendBytes(FieldOffsetInChars, InitCst, AllowOverwrite);
}
bool ConstStructBuilder::AppendBytes(CharUnits FieldOffsetInChars,
llvm::Constant *InitCst,
bool AllowOverwrite) {
return Builder.add(InitCst, StartOffset + FieldOffsetInChars, AllowOverwrite);
}
bool ConstStructBuilder::AppendBitField(const FieldDecl *Field,
uint64_t FieldOffset, llvm::Constant *C,
bool AllowOverwrite) {
llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C);
if (!CI) {
// Constants for long _BitInt types are sometimes split into individual
// bytes. Try to fold these back into an integer constant. If that doesn't
// work out, then we are trying to initialize a bitfield with a non-trivial
// constant, this must require run-time code.
llvm::Type *LoadType =
CGM.getTypes().convertTypeForLoadStore(Field->getType(), C->getType());
llvm::Constant *FoldedConstant = llvm::ConstantFoldLoadFromConst(
C, LoadType, llvm::APInt::getZero(32), CGM.getDataLayout());
CI = dyn_cast_if_present<llvm::ConstantInt>(FoldedConstant);
if (!CI)
return false;
}
const CGRecordLayout &RL =
CGM.getTypes().getCGRecordLayout(Field->getParent());
const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field);
llvm::APInt FieldValue = CI->getValue();
// Promote the size of FieldValue if necessary
// FIXME: This should never occur, but currently it can because initializer
// constants are cast to bool, and because clang is not enforcing bitfield
// width limits.
if (Info.Size > FieldValue.getBitWidth())
FieldValue = FieldValue.zext(Info.Size);
// Truncate the size of FieldValue to the bit field size.
if (Info.Size < FieldValue.getBitWidth())
FieldValue = FieldValue.trunc(Info.Size);
return Builder.addBits(FieldValue,
CGM.getContext().toBits(StartOffset) + FieldOffset,
AllowOverwrite);
}
static bool EmitDesignatedInitUpdater(ConstantEmitter &Emitter,
ConstantAggregateBuilder &Const,
CharUnits Offset, QualType Type,
const InitListExpr *Updater) {
if (Type->isRecordType())
return ConstStructBuilder::UpdateStruct(Emitter, Const, Offset, Updater);
auto CAT = Emitter.CGM.getContext().getAsConstantArrayType(Type);
if (!CAT)
return false;
QualType ElemType = CAT->getElementType();
CharUnits ElemSize = Emitter.CGM.getContext().getTypeSizeInChars(ElemType);
llvm::Type *ElemTy = Emitter.CGM.getTypes().ConvertTypeForMem(ElemType);
llvm::Constant *FillC = nullptr;
if (const Expr *Filler = Updater->getArrayFiller()) {
if (!isa<NoInitExpr>(Filler)) {
FillC = Emitter.tryEmitAbstractForMemory(Filler, ElemType);
if (!FillC)
return false;
}
}
unsigned NumElementsToUpdate =
FillC ? CAT->getZExtSize() : Updater->getNumInits();
for (unsigned I = 0; I != NumElementsToUpdate; ++I, Offset += ElemSize) {
const Expr *Init = nullptr;
if (I < Updater->getNumInits())
Init = Updater->getInit(I);
if (!Init && FillC) {
if (!Const.add(FillC, Offset, true))
return false;
} else if (!Init || isa<NoInitExpr>(Init)) {
continue;
} else if (const auto *ChildILE = dyn_cast<InitListExpr>(Init)) {
if (!EmitDesignatedInitUpdater(Emitter, Const, Offset, ElemType,
ChildILE))
return false;
// Attempt to reduce the array element to a single constant if necessary.
Const.condense(Offset, ElemTy);
} else {
llvm::Constant *Val = Emitter.tryEmitPrivateForMemory(Init, ElemType);
if (!Const.add(Val, Offset, true))
return false;
}
}
return true;
}
bool ConstStructBuilder::Build(const InitListExpr *ILE, bool AllowOverwrite) {
RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();
const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
unsigned FieldNo = -1;
unsigned ElementNo = 0;
// Bail out if we have base classes. We could support these, but they only
// arise in C++1z where we will have already constant folded most interesting
// cases. FIXME: There are still a few more cases we can handle this way.
if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
if (CXXRD->getNumBases())
return false;
const bool ZeroInitPadding = CGM.shouldZeroInitPadding();
bool ZeroFieldSize = false;
CharUnits SizeSoFar = CharUnits::Zero();
for (FieldDecl *Field : RD->fields()) {
++FieldNo;
// If this is a union, skip all the fields that aren't being initialized.
if (RD->isUnion() &&
!declaresSameEntity(ILE->getInitializedFieldInUnion(), Field))
continue;
// Don't emit anonymous bitfields.
if (Field->isUnnamedBitField())
continue;
// Get the initializer. A struct can include fields without initializers,
// we just use explicit null values for them.
const Expr *Init = nullptr;
if (ElementNo < ILE->getNumInits())
Init = ILE->getInit(ElementNo++);
if (isa_and_nonnull<NoInitExpr>(Init)) {
if (ZeroInitPadding &&
!DoZeroInitPadding(Layout, FieldNo, *Field, AllowOverwrite, SizeSoFar,
ZeroFieldSize))
return false;
continue;
}
// Zero-sized fields are not emitted, but their initializers may still
// prevent emission of this struct as a constant.
if (isEmptyFieldForLayout(CGM.getContext(), Field)) {
if (Init && Init->HasSideEffects(CGM.getContext()))
return false;
continue;
}
if (ZeroInitPadding &&
!DoZeroInitPadding(Layout, FieldNo, *Field, AllowOverwrite, SizeSoFar,
ZeroFieldSize))
return false;
// When emitting a DesignatedInitUpdateExpr, a nested InitListExpr
// represents additional overwriting of our current constant value, and not
// a new constant to emit independently.
if (AllowOverwrite &&
(Field->getType()->isArrayType() || Field->getType()->isRecordType())) {
if (auto *SubILE = dyn_cast<InitListExpr>(Init)) {
CharUnits Offset = CGM.getContext().toCharUnitsFromBits(
Layout.getFieldOffset(FieldNo));
if (!EmitDesignatedInitUpdater(Emitter, Builder, StartOffset + Offset,
Field->getType(), SubILE))
return false;
// If we split apart the field's value, try to collapse it down to a
// single value now.
Builder.condense(StartOffset + Offset,
CGM.getTypes().ConvertTypeForMem(Field->getType()));
continue;
}
}
llvm::Constant *EltInit =
Init ? Emitter.tryEmitPrivateForMemory(Init, Field->getType())
: Emitter.emitNullForMemory(Field->getType());
if (!EltInit)
return false;
if (ZeroInitPadding && ZeroFieldSize)
SizeSoFar += CharUnits::fromQuantity(
CGM.getDataLayout().getTypeAllocSize(EltInit->getType()));
if (!Field->isBitField()) {
// Handle non-bitfield members.
if (!AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit,
AllowOverwrite))
return false;
// After emitting a non-empty field with [[no_unique_address]], we may
// need to overwrite its tail padding.
if (Field->hasAttr<NoUniqueAddressAttr>())
AllowOverwrite = true;
} else {
// Otherwise we have a bitfield.
if (!AppendBitField(Field, Layout.getFieldOffset(FieldNo), EltInit,
AllowOverwrite))
return false;
}
}
if (ZeroInitPadding && !DoZeroInitPadding(Layout, AllowOverwrite, SizeSoFar))
return false;
return true;
}
namespace {
struct BaseInfo {
BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
: Decl(Decl), Offset(Offset), Index(Index) {
}
const CXXRecordDecl *Decl;
CharUnits Offset;
unsigned Index;
bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
};
}
bool ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
bool IsPrimaryBase,
const CXXRecordDecl *VTableClass,
CharUnits Offset) {
const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
// Add a vtable pointer, if we need one and it hasn't already been added.
if (Layout.hasOwnVFPtr()) {
llvm::Constant *VTableAddressPoint =
CGM.getCXXABI().getVTableAddressPoint(BaseSubobject(CD, Offset),
VTableClass);
if (auto Authentication = CGM.getVTablePointerAuthentication(CD)) {
VTableAddressPoint = Emitter.tryEmitConstantSignedPointer(
VTableAddressPoint, *Authentication);
if (!VTableAddressPoint)
return false;
}
if (!AppendBytes(Offset, VTableAddressPoint))
return false;
}
// Accumulate and sort bases, in order to visit them in address order, which
// may not be the same as declaration order.
SmallVector<BaseInfo, 8> Bases;
Bases.reserve(CD->getNumBases());
unsigned BaseNo = 0;
for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
assert(!Base->isVirtual() && "should not have virtual bases here");
const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
}
llvm::stable_sort(Bases);
for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
BaseInfo &Base = Bases[I];
bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
VTableClass, Offset + Base.Offset);
}
}
unsigned FieldNo = 0;
uint64_t OffsetBits = CGM.getContext().toBits(Offset);
const bool ZeroInitPadding = CGM.shouldZeroInitPadding();
bool ZeroFieldSize = false;
CharUnits SizeSoFar = CharUnits::Zero();
bool AllowOverwrite = false;
for (RecordDecl::field_iterator Field = RD->field_begin(),
FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
// If this is a union, skip all the fields that aren't being initialized.
if (RD->isUnion() && !declaresSameEntity(Val.getUnionField(), *Field))
continue;
// Don't emit anonymous bitfields or zero-sized fields.
if (Field->isUnnamedBitField() ||
isEmptyFieldForLayout(CGM.getContext(), *Field))
continue;
// Emit the value of the initializer.
const APValue &FieldValue =
RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
llvm::Constant *EltInit =
Emitter.tryEmitPrivateForMemory(FieldValue, Field->getType());
if (!EltInit)
return false;
if (ZeroInitPadding) {
if (!DoZeroInitPadding(Layout, FieldNo, **Field, AllowOverwrite,
SizeSoFar, ZeroFieldSize))
return false;
if (ZeroFieldSize)
SizeSoFar += CharUnits::fromQuantity(
CGM.getDataLayout().getTypeAllocSize(EltInit->getType()));
}
if (!Field->isBitField()) {
// Handle non-bitfield members.
if (!AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
EltInit, AllowOverwrite))
return false;
// After emitting a non-empty field with [[no_unique_address]], we may
// need to overwrite its tail padding.
if (Field->hasAttr<NoUniqueAddressAttr>())
AllowOverwrite = true;
} else {
// Otherwise we have a bitfield.
if (!AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
EltInit, AllowOverwrite))
return false;
}
}
if (ZeroInitPadding && !DoZeroInitPadding(Layout, AllowOverwrite, SizeSoFar))
return false;
return true;
}
bool ConstStructBuilder::DoZeroInitPadding(
const ASTRecordLayout &Layout, unsigned FieldNo, const FieldDecl &Field,
bool AllowOverwrite, CharUnits &SizeSoFar, bool &ZeroFieldSize) {
uint64_t StartBitOffset = Layout.getFieldOffset(FieldNo);
CharUnits StartOffset = CGM.getContext().toCharUnitsFromBits(StartBitOffset);
if (SizeSoFar < StartOffset)
if (!AppendBytes(SizeSoFar, getPadding(CGM, StartOffset - SizeSoFar),
AllowOverwrite))
return false;
if (!Field.isBitField()) {
CharUnits FieldSize = CGM.getContext().getTypeSizeInChars(Field.getType());
SizeSoFar = StartOffset + FieldSize;
ZeroFieldSize = FieldSize.isZero();
} else {
const CGRecordLayout &RL =
CGM.getTypes().getCGRecordLayout(Field.getParent());
const CGBitFieldInfo &Info = RL.getBitFieldInfo(&Field);
uint64_t EndBitOffset = StartBitOffset + Info.Size;
SizeSoFar = CGM.getContext().toCharUnitsFromBits(EndBitOffset);
if (EndBitOffset % CGM.getContext().getCharWidth() != 0) {
SizeSoFar++;
}
ZeroFieldSize = Info.Size == 0;
}
return true;
}
bool ConstStructBuilder::DoZeroInitPadding(const ASTRecordLayout &Layout,
bool AllowOverwrite,
CharUnits SizeSoFar) {
CharUnits TotalSize = Layout.getSize();
if (SizeSoFar < TotalSize)
if (!AppendBytes(SizeSoFar, getPadding(CGM, TotalSize - SizeSoFar),
AllowOverwrite))
return false;
SizeSoFar = TotalSize;
return true;
}
llvm::Constant *ConstStructBuilder::Finalize(QualType Type) {
Type = Type.getNonReferenceType();
RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
llvm::Type *ValTy = CGM.getTypes().ConvertType(Type);
return Builder.build(ValTy, RD->hasFlexibleArrayMember());
}
llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
const InitListExpr *ILE,
QualType ValTy) {
ConstantAggregateBuilder Const(Emitter.CGM);
ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
if (!Builder.Build(ILE, /*AllowOverwrite*/false))
return nullptr;
return Builder.Finalize(ValTy);
}
llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
const APValue &Val,