/
CIRGenExpr.cpp
2269 lines (1934 loc) · 83.8 KB
/
CIRGenExpr.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
//===--- CIRGenExpr.cpp - Emit LLVM Code from 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 Expr nodes as CIR code.
//
//===----------------------------------------------------------------------===//
#include "CIRGenCXXABI.h"
#include "CIRGenCall.h"
#include "CIRGenCstEmitter.h"
#include "CIRGenFunction.h"
#include "CIRGenModule.h"
#include "UnimplementedFeatureGuarding.h"
#include "clang/AST/GlobalDecl.h"
#include "clang/Basic/Builtins.h"
#include "clang/CIR/Dialect/IR/CIRDialect.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/IR/Value.h"
using namespace cir;
using namespace clang;
using namespace mlir::cir;
static mlir::cir::FuncOp buildFunctionDeclPointer(CIRGenModule &CGM,
GlobalDecl GD) {
const auto *FD = cast<FunctionDecl>(GD.getDecl());
assert(!FD->hasAttr<WeakRefAttr>() && "NYI");
auto V = CGM.GetAddrOfFunction(GD);
assert(FD->hasPrototype() &&
"Only prototyped functions are currently callable");
return V;
}
static Address buildPreserveStructAccess(CIRGenFunction &CGF, LValue base,
Address addr, const FieldDecl *field) {
llvm_unreachable("NYI");
}
/// Get the address of a zero-sized field within a record. The resulting address
/// doesn't necessarily have the right type.
static Address buildAddrOfFieldStorage(CIRGenFunction &CGF, Address Base,
const FieldDecl *field,
llvm::StringRef fieldName) {
if (field->isZeroSize(CGF.getContext()))
llvm_unreachable("NYI");
auto loc = CGF.getLoc(field->getLocation());
auto fieldType = CGF.convertType(field->getType());
auto fieldPtr =
mlir::cir::PointerType::get(CGF.getBuilder().getContext(), fieldType);
// For most cases fieldName is the same as field->getName() but for lambdas,
// which do not currently carry the name, so it can be passed down from the
// CaptureStmt.
auto sea = CGF.getBuilder().create<mlir::cir::StructElementAddr>(
loc, fieldPtr, Base.getPointer(), fieldName);
// TODO: We could get the alignment from the CIRGenRecordLayout, but given the
// member name based lookup of the member here we probably shouldn't be. We'll
// have to consider this later.
auto addr = Address(sea->getResult(0), CharUnits::One());
return addr;
}
static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
if (!RD)
return false;
if (RD->isDynamicClass())
return true;
for (const auto &Base : RD->bases())
if (hasAnyVptr(Base.getType(), Context))
return true;
for (const FieldDecl *Field : RD->fields())
if (hasAnyVptr(Field->getType(), Context))
return true;
return false;
}
LValue CIRGenFunction::buildLValueForField(LValue base,
const FieldDecl *field) {
LValueBaseInfo BaseInfo = base.getBaseInfo();
if (field->isBitField()) {
llvm_unreachable("NYI");
}
// Fields of may-alias structures are may-alais themselves.
// FIXME: this hould get propagated down through anonymous structs and unions.
QualType FieldType = field->getType();
const RecordDecl *rec = field->getParent();
AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
if (UnimplementedFeature::tbaa() || rec->hasAttr<MayAliasAttr>() ||
FieldType->isVectorType()) {
assert(!UnimplementedFeature::tbaa() && "NYI");
} else if (rec->isUnion()) {
assert(!UnimplementedFeature::tbaa() && "NYI");
} else {
// If no base type been assigned for the base access, then try to generate
// one for this base lvalue.
assert(!UnimplementedFeature::tbaa() && "NYI");
}
Address addr = base.getAddress();
if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) {
if (CGM.getCodeGenOpts().StrictVTablePointers &&
ClassDef->isDynamicClass()) {
llvm_unreachable("NYI");
}
}
unsigned RecordCVR = base.getVRQualifiers();
if (rec->isUnion()) {
// For unions, there is no pointer adjustment.
if (CGM.getCodeGenOpts().StrictVTablePointers &&
hasAnyVptr(FieldType, getContext()))
// Because unions can easily skip invariant.barriers, we need to add
// a barrier every time CXXRecord field with vptr is referenced.
assert(!UnimplementedFeature::createLaunderInvariantGroup());
if (IsInPreservedAIRegion ||
(getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
assert(!UnimplementedFeature::generateDebugInfo());
}
if (FieldType->isReferenceType())
llvm_unreachable("NYI");
} else {
if (!IsInPreservedAIRegion &&
(!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
llvm::StringRef fieldName = field->getName();
if (CGM.LambdaFieldToName.count(field))
fieldName = CGM.LambdaFieldToName[field];
addr = buildAddrOfFieldStorage(*this, addr, field, fieldName);
} else
// Remember the original struct field index
addr = buildPreserveStructAccess(*this, base, addr, field);
}
// If this is a reference field, load the reference right now.
if (FieldType->isReferenceType()) {
assert(!UnimplementedFeature::tbaa());
LValue RefLVal = makeAddrLValue(addr, FieldType, FieldBaseInfo);
if (RecordCVR & Qualifiers::Volatile)
RefLVal.getQuals().addVolatile();
addr = buildLoadOfReference(RefLVal, getLoc(field->getSourceRange()),
&FieldBaseInfo);
// Qualifiers on the struct don't apply to the referencee.
RecordCVR = 0;
FieldType = FieldType->getPointeeType();
}
// Make sure that the address is pointing to the right type. This is critical
// for both unions and structs. A union needs a bitcast, a struct element will
// need a bitcast if the CIR type laid out doesn't match the desired type.
// TODO(CIR): CodeGen requires a bitcast here for unions or for structs where
// the LLVM type doesn't match the desired type. No idea when the latter might
// occur, though.
if (field->hasAttr<AnnotateAttr>())
llvm_unreachable("NYI");
if (UnimplementedFeature::tbaa())
// Next line should take a TBAA object
llvm_unreachable("NYI");
LValue LV = makeAddrLValue(addr, FieldType, FieldBaseInfo);
LV.getQuals().addCVRQualifiers(RecordCVR);
// __weak attribute on a field is ignored.
if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
llvm_unreachable("NYI");
return LV;
}
LValue CIRGenFunction::buildLValueForFieldInitialization(
LValue Base, const clang::FieldDecl *Field, llvm::StringRef FieldName) {
QualType FieldType = Field->getType();
if (!FieldType->isReferenceType())
return buildLValueForField(Base, Field);
Address V =
buildAddrOfFieldStorage(*this, Base.getAddress(), Field, FieldName);
// Make sure that the address is pointing to the right type.
auto memTy = getTypes().convertTypeForMem(FieldType);
V = builder.createElementBitCast(getLoc(Field->getSourceRange()), V, memTy);
// TODO: Generate TBAA information that describes this access as a structure
// member access and not just an access to an object of the field's type. This
// should be similar to what we do in EmitLValueForField().
LValueBaseInfo BaseInfo = Base.getBaseInfo();
AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
assert(!UnimplementedFeature::tbaa() && "NYI");
return makeAddrLValue(V, FieldType, FieldBaseInfo);
}
// Detect the unusual situation where an inline version is shadowed by a
// non-inline version. In that case we should pick the external one
// everywhere. That's GCC behavior too.
static bool onlyHasInlineBuiltinDeclaration(const FunctionDecl *FD) {
for (const FunctionDecl *PD = FD; PD; PD = PD->getPreviousDecl())
if (!PD->isInlineBuiltinDeclaration())
return false;
return true;
}
static CIRGenCallee buildDirectCallee(CIRGenModule &CGM, GlobalDecl GD) {
const auto *FD = cast<FunctionDecl>(GD.getDecl());
if (auto builtinID = FD->getBuiltinID()) {
std::string NoBuiltinFD = ("no-builtin-" + FD->getName()).str();
std::string NoBuiltins = "no-builtins";
auto *A = FD->getAttr<AsmLabelAttr>();
StringRef Ident = A ? A->getLabel() : FD->getName();
std::string FDInlineName = (Ident + ".inline").str();
auto &CGF = *CGM.getCurrCIRGenFun();
bool IsPredefinedLibFunction =
CGM.getASTContext().BuiltinInfo.isPredefinedLibFunction(builtinID);
bool HasAttributeNoBuiltin = false;
assert(!UnimplementedFeature::attributeNoBuiltin() && "NYI");
// bool HasAttributeNoBuiltin =
// CGF.CurFn->getAttributes().hasFnAttr(NoBuiltinFD) ||
// CGF.CurFn->getAttributes().hasFnAttr(NoBuiltins);
// When directing calling an inline builtin, call it through it's mangled
// name to make it clear it's not the actual builtin.
if (CGF.CurFn.getName() != FDInlineName &&
onlyHasInlineBuiltinDeclaration(FD)) {
assert(0 && "NYI");
}
// Replaceable builtins provide their own implementation of a builtin. If we
// are in an inline builtin implementation, avoid trivial infinite
// recursion. Honor __attribute__((no_builtin("foo"))) or
// __attribute__((no_builtin)) on the current function unless foo is
// not a predefined library function which means we must generate the
// builtin no matter what.
else if (!IsPredefinedLibFunction || !HasAttributeNoBuiltin)
return CIRGenCallee::forBuiltin(builtinID, FD);
}
auto CalleePtr = buildFunctionDeclPointer(CGM, GD);
assert(!CGM.getLangOpts().CUDA && "NYI");
return CIRGenCallee::forDirect(CalleePtr, GD);
}
// TODO: this can also be abstrated into common AST helpers
bool CIRGenFunction::hasBooleanRepresentation(QualType Ty) {
if (Ty->isBooleanType())
return true;
if (const EnumType *ET = Ty->getAs<EnumType>())
return ET->getDecl()->getIntegerType()->isBooleanType();
if (const AtomicType *AT = Ty->getAs<AtomicType>())
return hasBooleanRepresentation(AT->getValueType());
return false;
}
CIRGenCallee CIRGenFunction::buildCallee(const clang::Expr *E) {
E = E->IgnoreParens();
// Look through function-to-pointer decay.
if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
return buildCallee(ICE->getSubExpr());
}
// Resolve direct calls.
} else if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
const auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
assert(FD &&
"DeclRef referring to FunctionDecl only thing supported so far");
return buildDirectCallee(CGM, FD);
}
assert(!dyn_cast<MemberExpr>(E) && "NYI");
assert(!dyn_cast<SubstNonTypeTemplateParmExpr>(E) && "NYI");
assert(!dyn_cast<CXXPseudoDestructorExpr>(E) && "NYI");
// Otherwise, we have an indirect reference.
mlir::Value calleePtr;
QualType functionType;
if (auto ptrType = E->getType()->getAs<clang::PointerType>()) {
calleePtr = buildScalarExpr(E);
functionType = ptrType->getPointeeType();
} else {
functionType = E->getType();
calleePtr = buildLValue(E).getPointer();
}
assert(functionType->isFunctionType());
GlobalDecl GD;
if (const auto *VD =
dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee()))
GD = GlobalDecl(VD);
CIRGenCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD);
CIRGenCallee callee(calleeInfo, calleePtr.getDefiningOp());
return callee;
assert(false && "Nothing else supported yet!");
}
mlir::Value CIRGenFunction::buildToMemory(mlir::Value Value, QualType Ty) {
// Bool has a different representation in memory than in registers.
return Value;
}
void CIRGenFunction::buildStoreOfScalar(mlir::Value value, LValue lvalue) {
// TODO: constant matrix type, volatile, no init, non temporal, TBAA
buildStoreOfScalar(value, lvalue.getAddress(), false, lvalue.getType(),
lvalue.getBaseInfo(), false, false);
}
void CIRGenFunction::buildStoreOfScalar(mlir::Value Value, Address Addr,
bool Volatile, QualType Ty,
LValueBaseInfo BaseInfo, bool isInit,
bool isNontemporal) {
if (!CGM.getCodeGenOpts().PreserveVec3Type) {
if (Ty->isVectorType()) {
llvm_unreachable("NYI");
}
}
Value = buildToMemory(Value, Ty);
if (Ty->isAtomicType()) {
llvm_unreachable("NYI");
}
// Update the alloca with more info on initialization.
assert(Addr.getPointer() && "expected pointer to exist");
auto SrcAlloca =
dyn_cast_or_null<mlir::cir::AllocaOp>(Addr.getPointer().getDefiningOp());
if (currVarDecl && SrcAlloca) {
const VarDecl *VD = currVarDecl;
assert(VD && "VarDecl expected");
if (VD->hasInit())
SrcAlloca.setInitAttr(mlir::UnitAttr::get(builder.getContext()));
}
assert(currSrcLoc && "must pass in source location");
builder.create<mlir::cir::StoreOp>(*currSrcLoc, Value, Addr.getPointer());
if (isNontemporal) {
llvm_unreachable("NYI");
}
if (UnimplementedFeature::tbaa())
llvm_unreachable("NYI");
}
void CIRGenFunction::buildStoreOfScalar(mlir::Value value, LValue lvalue,
bool isInit) {
if (lvalue.getType()->isConstantMatrixType()) {
llvm_unreachable("NYI");
}
buildStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
lvalue.getType(), lvalue.getBaseInfo(), isInit,
lvalue.isNontemporal());
}
/// Given an expression that represents a value lvalue, this
/// method emits the address of the lvalue, then loads the result as an rvalue,
/// returning the rvalue.
RValue CIRGenFunction::buildLoadOfLValue(LValue LV, SourceLocation Loc) {
assert(LV.isSimple() && "not implemented");
assert(!LV.getType()->isFunctionType());
assert(!(LV.getType()->isConstantMatrixType()) && "not implemented");
// Everything needs a load.
return RValue::get(buildLoadOfScalar(LV, Loc));
}
void CIRGenFunction::buildStoreThroughLValue(RValue Src, LValue Dst) {
assert(Dst.isSimple() && "only implemented simple");
// There's special magic for assigning into an ARC-qualified l-value.
if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
llvm_unreachable("NYI");
}
if (Dst.isObjCWeak() && !Dst.isNonGC()) {
llvm_unreachable("NYI");
}
if (Dst.isObjCStrong() && !Dst.isNonGC()) {
llvm_unreachable("NYI");
}
assert(Src.isScalar() && "Can't emit an agg store with this method");
buildStoreOfScalar(Src.getScalarVal(), Dst);
}
static LValue buildGlobalVarDeclLValue(CIRGenFunction &CGF, const Expr *E,
const VarDecl *VD) {
QualType T = E->getType();
// If it's thread_local, emit a call to its wrapper function instead.
if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
CGF.CGM.getCXXABI().usesThreadWrapperFunction(VD))
assert(0 && "not implemented");
// Check if the variable is marked as declare target with link clause in
// device codegen.
if (CGF.getLangOpts().OpenMPIsDevice) {
assert(0 && "not implemented");
}
auto V = CGF.CGM.getAddrOfGlobalVar(VD);
auto RealVarTy = CGF.getTypes().convertTypeForMem(VD->getType());
// TODO(cir): do we need this for CIR?
// V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
Address Addr(V, RealVarTy, Alignment);
// Emit reference to the private copy of the variable if it is an OpenMP
// threadprivate variable.
if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
VD->hasAttr<clang::OMPThreadPrivateDeclAttr>()) {
assert(0 && "NYI");
}
LValue LV;
if (VD->getType()->isReferenceType())
assert(0 && "NYI");
else
LV = CGF.makeAddrLValue(Addr, T, AlignmentSource::Decl);
assert(!UnimplementedFeature::setObjCGCLValueClass() && "NYI");
return LV;
}
static LValue buildCapturedFieldLValue(CIRGenFunction &CGF, const FieldDecl *FD,
mlir::Value ThisValue) {
QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
return CGF.buildLValueForField(LV, FD);
}
static LValue buildFunctionDeclLValue(CIRGenFunction &CGF, const Expr *E,
GlobalDecl GD) {
const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
auto funcOp = buildFunctionDeclPointer(CGF.CGM, GD);
auto loc = CGF.getLoc(E->getSourceRange());
CharUnits align = CGF.getContext().getDeclAlign(FD);
auto fnTy = funcOp.getFunctionType();
auto ptrTy = mlir::cir::PointerType::get(CGF.getBuilder().getContext(), fnTy);
auto addr = CGF.getBuilder().create<mlir::cir::GetGlobalOp>(
loc, ptrTy, funcOp.getSymName());
return CGF.makeAddrLValue(Address(addr, fnTy, align), E->getType(),
AlignmentSource::Decl);
}
LValue CIRGenFunction::buildDeclRefLValue(const DeclRefExpr *E) {
const NamedDecl *ND = E->getDecl();
QualType T = E->getType();
assert(E->isNonOdrUse() != NOUR_Unevaluated &&
"should not emit an unevaluated operand");
if (const auto *VD = dyn_cast<VarDecl>(ND)) {
// Global Named registers access via intrinsics only
assert(VD->getStorageClass() != SC_Register && "not implemented");
assert(E->isNonOdrUse() != NOUR_Constant && "not implemented");
// Check for captured variables.
if (E->refersToEnclosingVariableOrCapture()) {
VD = VD->getCanonicalDecl();
if (auto *FD = LambdaCaptureFields.lookup(VD))
return buildCapturedFieldLValue(*this, FD, CXXABIThisValue);
assert(!UnimplementedFeature::CGCapturedStmtInfo() && "NYI");
llvm_unreachable("NYI");
// LLVM codegen:
// Address addr = GetAddrOfBlockDecl(VD);
// return MakeAddrLValue(addr, T, AlignmentSource::Decl);
}
}
// FIXME(CIR): We should be able to assert this for FunctionDecls as well!
// FIXME(CIR): We should be able to assert this for all DeclRefExprs, not just
// those with a valid source location.
assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() ||
!E->getLocation().isValid()) &&
"Should not use decl without marking it used!");
if (ND->hasAttr<WeakRefAttr>()) {
llvm_unreachable("NYI");
}
if (const auto *VD = dyn_cast<VarDecl>(ND)) {
// Check if this is a global variable
if (VD->hasLinkage() || VD->isStaticDataMember())
return buildGlobalVarDeclLValue(*this, E, VD);
Address addr = Address::invalid();
// The variable should generally be present in the local decl map.
auto iter = LocalDeclMap.find(VD);
if (iter != LocalDeclMap.end()) {
addr = iter->second;
}
// Otherwise, it might be static local we haven't emitted yet for some
// reason; most likely, because it's in an outer function.
else if (VD->isStaticLocal()) {
llvm_unreachable("NYI");
} else {
llvm_unreachable("DeclRefExpr for decl not entered in LocalDeclMap?");
}
// Check for OpenMP threadprivate variables.
if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
llvm_unreachable("NYI");
}
// Drill into block byref variables.
bool isBlockByref = VD->isEscapingByref();
if (isBlockByref) {
llvm_unreachable("NYI");
}
// Drill into reference types.
LValue LV =
VD->getType()->isReferenceType()
? buildLoadOfReferenceLValue(addr, getLoc(E->getSourceRange()),
VD->getType(), AlignmentSource::Decl)
: makeAddrLValue(addr, T, AlignmentSource::Decl);
assert(symbolTable.count(VD) && "should be already mapped");
bool isLocalStorage = VD->hasLocalStorage();
bool NonGCable =
isLocalStorage && !VD->getType()->isReferenceType() && !isBlockByref;
if (NonGCable) {
// TODO: nongcable
}
bool isImpreciseLifetime =
(isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
if (isImpreciseLifetime)
; // TODO: LV.setARCPreciseLifetime
// TODO: setObjCGCLValueClass(getContext(), E, LV);
mlir::Value V = symbolTable.lookup(VD);
assert(V && "Name lookup must succeed");
return LV;
}
if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
LValue LV = buildFunctionDeclLValue(*this, E, FD);
// Emit debuginfo for the function declaration if the target wants to.
if (getContext().getTargetInfo().allowDebugInfoForExternalRef())
assert(!UnimplementedFeature::generateDebugInfo());
return LV;
}
// FIXME: While we're emitting a binding from an enclosing scope, all other
// DeclRefExprs we see should be implicitly treated as if they also refer to
// an enclosing scope.
if (const auto *BD = dyn_cast<BindingDecl>(ND)) {
llvm_unreachable("NYI");
}
// We can form DeclRefExprs naming GUID declarations when reconstituting
// non-type template parameters into expressions.
if (const auto *GD = dyn_cast<MSGuidDecl>(ND))
llvm_unreachable("NYI");
if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND))
llvm_unreachable("NYI");
llvm_unreachable("Unhandled DeclRefExpr");
}
LValue CIRGenFunction::buildBinaryOperatorLValue(const BinaryOperator *E) {
// Comma expressions just emit their LHS then their RHS as an l-value.
if (E->getOpcode() == BO_Comma) {
assert(0 && "not implemented");
}
if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
assert(0 && "not implemented");
assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
// Note that in all of these cases, __block variables need the RHS
// evaluated first just in case the variable gets moved by the RHS.
switch (CIRGenFunction::getEvaluationKind(E->getType())) {
case TEK_Scalar: {
assert(E->getLHS()->getType().getObjCLifetime() ==
clang::Qualifiers::ObjCLifetime::OCL_None &&
"not implemented");
RValue RV = buildAnyExpr(E->getRHS());
LValue LV = buildLValue(E->getLHS());
SourceLocRAIIObject Loc{*this, getLoc(E->getSourceRange())};
buildStoreThroughLValue(RV, LV);
assert(!getContext().getLangOpts().OpenMP &&
"last priv cond not implemented");
return LV;
}
case TEK_Complex:
assert(0 && "not implemented");
case TEK_Aggregate:
assert(0 && "not implemented");
}
llvm_unreachable("bad evaluation kind");
}
/// Given an expression of pointer type, try to
/// derive a more accurate bound on the alignment of the pointer.
Address CIRGenFunction::buildPointerWithAlignment(const Expr *E,
LValueBaseInfo *BaseInfo) {
// We allow this with ObjC object pointers because of fragile ABIs.
assert(E->getType()->isPointerType() ||
E->getType()->isObjCObjectPointerType());
E = E->IgnoreParens();
// Casts:
if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
assert(0 && "not implemented");
switch (CE->getCastKind()) {
default: {
llvm::errs() << CE->getCastKindName() << "\n";
assert(0 && "not implemented");
}
// Nothing to do here...
case CK_LValueToRValue:
break;
case CK_UncheckedDerivedToBase:
case CK_DerivedToBase: {
// TODO: Support accesses to members of base classes in TBAA. For now, we
// conservatively pretend that the complete object is of the base class
// type.
assert(!UnimplementedFeature::tbaa());
Address Addr = buildPointerWithAlignment(CE->getSubExpr(), BaseInfo);
auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
return getAddressOfBaseClass(
Addr, Derived, CE->path_begin(), CE->path_end(),
shouldNullCheckClassCastValue(CE), CE->getExprLoc());
}
}
}
// Unary &.
if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
assert(0 && "not implemented");
// if (UO->getOpcode() == UO_AddrOf) {
// LValue LV = buildLValue(UO->getSubExpr());
// if (BaseInfo)
// *BaseInfo = LV.getBaseInfo();
// // TODO: TBBA info
// return LV.getAddress();
// }
}
// TODO: conditional operators, comma.
// Otherwise, use the alignment of the type.
CharUnits Align = CGM.getNaturalPointeeTypeAlignment(E->getType(), BaseInfo);
return Address(buildScalarExpr(E), Align);
}
/// Perform the usual unary conversions on the specified
/// expression and compare the result against zero, returning an Int1Ty value.
mlir::Value CIRGenFunction::evaluateExprAsBool(const Expr *E) {
// TODO(cir): PGO
if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
assert(0 && "not implemented");
}
QualType BoolTy = getContext().BoolTy;
SourceLocation Loc = E->getExprLoc();
// TODO(cir): CGFPOptionsRAII for FP stuff.
if (!E->getType()->isAnyComplexType())
return buildScalarConversion(buildScalarExpr(E), E->getType(), BoolTy, Loc);
llvm_unreachable("complex to scalar not implemented");
}
LValue CIRGenFunction::buildUnaryOpLValue(const UnaryOperator *E) {
// __extension__ doesn't affect lvalue-ness.
assert(E->getOpcode() != UO_Extension && "not implemented");
switch (E->getOpcode()) {
default:
llvm_unreachable("Unknown unary operator lvalue!");
case UO_Deref: {
QualType T = E->getSubExpr()->getType()->getPointeeType();
assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
LValueBaseInfo BaseInfo;
// TODO: add TBAAInfo
Address Addr = buildPointerWithAlignment(E->getSubExpr(), &BaseInfo);
// Tag 'load' with deref attribute.
if (auto loadOp =
dyn_cast<::mlir::cir::LoadOp>(Addr.getPointer().getDefiningOp())) {
loadOp.setIsDerefAttr(mlir::UnitAttr::get(builder.getContext()));
}
LValue LV = LValue::makeAddr(Addr, T, BaseInfo);
// TODO: set addr space
// TODO: ObjC/GC/__weak write barrier stuff.
return LV;
}
case UO_Real:
case UO_Imag: {
assert(0 && "not implemented");
}
case UO_PreInc:
case UO_PreDec: {
bool isInc = E->isIncrementOp();
bool isPre = E->isPrefix();
LValue LV = buildLValue(E->getSubExpr());
if (E->getType()->isAnyComplexType()) {
assert(0 && "not implemented");
} else {
buildScalarPrePostIncDec(E, LV, isInc, isPre);
}
return LV;
}
}
}
/// Emit code to compute the specified expression which
/// can have any type. The result is returned as an RValue struct.
RValue CIRGenFunction::buildAnyExpr(const Expr *E, AggValueSlot aggSlot,
bool ignoreResult) {
switch (CIRGenFunction::getEvaluationKind(E->getType())) {
case TEK_Scalar:
return RValue::get(buildScalarExpr(E));
case TEK_Complex:
assert(0 && "not implemented");
case TEK_Aggregate: {
if (!ignoreResult && aggSlot.isIgnored())
aggSlot = CreateAggTemp(E->getType(), getLoc(E->getSourceRange()),
getCounterAggTmpAsString());
buildAggExpr(E, aggSlot);
return aggSlot.asRValue();
}
}
llvm_unreachable("bad evaluation kind");
}
RValue CIRGenFunction::buildCallExpr(const clang::CallExpr *E,
ReturnValueSlot ReturnValue) {
assert(!E->getCallee()->getType()->isBlockPointerType() && "ObjC Blocks NYI");
if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
return buildCXXMemberCallExpr(CE, ReturnValue);
assert(!dyn_cast<CUDAKernelCallExpr>(E) && "CUDA NYI");
if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
if (const CXXMethodDecl *MD =
dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
return buildCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
CIRGenCallee callee = buildCallee(E->getCallee());
if (callee.isBuiltin())
return buildBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(), E,
ReturnValue);
assert(!callee.isPsuedoDestructor() && "NYI");
return buildCall(E->getCallee()->getType(), callee, E, ReturnValue);
}
RValue CIRGenFunction::buildCall(clang::QualType CalleeType,
const CIRGenCallee &OrigCallee,
const clang::CallExpr *E,
ReturnValueSlot ReturnValue,
mlir::Value Chain) {
// Get the actual function type. The callee type will always be a pointer to
// function type or a block pointer type.
assert(CalleeType->isFunctionPointerType() &&
"Call must have function pointer type!");
auto *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl().getDecl();
(void)TargetDecl;
CalleeType = getContext().getCanonicalType(CalleeType);
auto PointeeType = cast<clang::PointerType>(CalleeType)->getPointeeType();
CIRGenCallee Callee = OrigCallee;
if (getLangOpts().CPlusPlus)
assert(!SanOpts.has(SanitizerKind::Function) && "Sanitizers NYI");
const auto *FnType = cast<FunctionType>(PointeeType);
assert(!SanOpts.has(SanitizerKind::CFIICall) && "Sanitizers NYI");
CallArgList Args;
assert(!Chain && "FIX THIS");
// C++17 requires that we evaluate arguments to a call using assignment syntax
// right-to-left, and that we evaluate arguments to certain other operators
// left-to-right. Note that we allow this to override the order dictated by
// the calling convention on the MS ABI, which means that parameter
// destruction order is not necessarily reverse construction order.
// FIXME: Revisit this based on C++ committee response to unimplementability.
EvaluationOrder Order = EvaluationOrder::Default;
if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
if (OCE->isAssignmentOp())
Order = EvaluationOrder::ForceRightToLeft;
else {
switch (OCE->getOperator()) {
case OO_LessLess:
case OO_GreaterGreater:
case OO_AmpAmp:
case OO_PipePipe:
case OO_Comma:
case OO_ArrowStar:
Order = EvaluationOrder::ForceLeftToRight;
break;
default:
break;
}
}
}
buildCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
const CIRGenFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
Args, FnType, /*ChainCall=*/Chain.getAsOpaquePointer());
// C99 6.5.2.2p6:
// If the expression that denotes the called function has a type that does
// not include a prototype, [the default argument promotions are performed].
// If the number of arguments does not equal the number of parameters, the
// behavior is undefined. If the function is defined with at type that
// includes a prototype, and either the prototype ends with an ellipsis (,
// ...) or the types of the arguments after promotion are not compatible
// with the types of the parameters, the behavior is undefined. If the
// function is defined with a type that does not include a prototype, and
// the types of the arguments after promotion are not compatible with those
// of the parameters after promotion, the behavior is undefined [except in
// some trivial cases].
// That is, in the general case, we should assume that a call through an
// unprototyped function type works like a *non-variadic* call. The way we
// make this work is to cast to the exxact type fo the promoted arguments.
//
// Chain calls use the same code path to add the inviisble chain parameter to
// the function type.
assert(!isa<FunctionNoProtoType>(FnType) && "NYI");
// if (isa<FunctionNoProtoType>(FnType) || Chain) {
// mlir::FunctionType CalleeTy = getTypes().GetFunctionType(FnInfo);
// int AS = Callee.getFunctionPointer()->getType()->getPointerAddressSpace();
// CalleeTy = CalleeTy->getPointerTo(AS);
// llvm::Value *CalleePtr = Callee.getFunctionPointer();
// CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
// Callee.setFunctionPointer(CalleePtr);
// }
assert(!CGM.getLangOpts().HIP && "HIP NYI");
assert(!MustTailCall && "Must tail NYI");
mlir::cir::CallOp callOP = nullptr;
RValue Call = buildCall(FnInfo, Callee, ReturnValue, Args, &callOP,
E == MustTailCall, getLoc(E->getExprLoc()));
assert(!getDebugInfo() && "Debug Info NYI");
return Call;
}
/// Emit code to compute the specified expression, ignoring the result.
void CIRGenFunction::buildIgnoredExpr(const Expr *E) {
if (E->isPRValue())
return (void)buildAnyExpr(E);
// Just emit it as an l-value and drop the result.
buildLValue(E);
}
static mlir::Value maybeBuildArrayDecay(mlir::OpBuilder &builder,
mlir::Location loc,
mlir::Value arrayPtr,
mlir::Type eltTy) {
auto arrayPtrTy = arrayPtr.getType().dyn_cast<::mlir::cir::PointerType>();
assert(arrayPtrTy && "expected pointer type");
auto arrayTy = arrayPtrTy.getPointee().dyn_cast<::mlir::cir::ArrayType>();
if (arrayTy) {
mlir::cir::PointerType flatPtrTy =
mlir::cir::PointerType::get(builder.getContext(), arrayTy.getEltType());
return builder.create<mlir::cir::CastOp>(
loc, flatPtrTy, mlir::cir::CastKind::array_to_ptrdecay, arrayPtr);
}
assert(arrayPtrTy.getPointee() == eltTy &&
"flat pointee type must match original array element type");
return arrayPtr;
}
Address CIRGenFunction::buildArrayToPointerDecay(const Expr *E,
LValueBaseInfo *BaseInfo) {
assert(E->getType()->isArrayType() &&
"Array to pointer decay must have array source type!");
// Expressions of array type can't be bitfields or vector elements.
LValue LV = buildLValue(E);
Address Addr = LV.getAddress();
// If the array type was an incomplete type, we need to make sure
// the decay ends up being the right type.
auto lvalueAddrTy =
Addr.getPointer().getType().dyn_cast<mlir::cir::PointerType>();
assert(lvalueAddrTy && "expected pointer");
auto pointeeTy = lvalueAddrTy.getPointee().dyn_cast<mlir::cir::ArrayType>();
assert(pointeeTy && "expected array");
mlir::Type arrayTy = convertType(E->getType());
assert(arrayTy.isa<mlir::cir::ArrayType>() && "expected array");
assert(pointeeTy == arrayTy);
// TODO(cir): in LLVM codegen VLA pointers are always decayed, so we don't
// need to do anything here. Revisit this for VAT when its supported in CIR.
assert(!E->getType()->isVariableArrayType() && "what now?");
// The result of this decay conversion points to an array element within the
// base lvalue. However, since TBAA currently does not support representing
// accesses to elements of member arrays, we conservatively represent accesses
// to the pointee object as if it had no any base lvalue specified.
// TODO: Support TBAA for member arrays.
QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
if (BaseInfo)
*BaseInfo = LV.getBaseInfo();
assert(!UnimplementedFeature::tbaa() && "NYI");
mlir::Value ptr = maybeBuildArrayDecay(
CGM.getBuilder(), CGM.getLoc(E->getSourceRange()), Addr.getPointer(),
getTypes().convertTypeForMem(EltType));
return Address(ptr, Addr.getAlignment());
}
/// If the specified expr is a simple decay from an array to pointer,
/// return the array subexpression.
/// FIXME: this could be abstracted into a commeon AST helper.
static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
// If this isn't just an array->pointer decay, bail out.
const auto *CE = dyn_cast<CastExpr>(E);
if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
return nullptr;
// If this is a decay from variable width array, bail out.
const Expr *SubExpr = CE->getSubExpr();
if (SubExpr->getType()->isVariableArrayType())
return nullptr;
return SubExpr;
}
/// Given an array base, check whether its member access belongs to a record
/// with preserve_access_index attribute or not.
/// TODO(cir): don't need to be specific to LLVM's codegen, refactor into common