-
Notifications
You must be signed in to change notification settings - Fork 100
/
CIRGenFunction.h
1697 lines (1394 loc) · 66.5 KB
/
CIRGenFunction.h
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
//===-- CIRGenFunction.h - Per-Function state for CIR gen -------*- C++ -*-===//
//
// 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 is the internal per-function state used for CIR translation.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_LIB_CIR_CIRGENFUNCTION_H
#define LLVM_CLANG_LIB_CIR_CIRGENFUNCTION_H
#include "CIRGenBuilder.h"
#include "CIRGenCall.h"
#include "CIRGenModule.h"
#include "CIRGenTypeCache.h"
#include "CIRGenValue.h"
#include "EHScopeStack.h"
#include "clang/AST/BaseSubobject.h"
#include "clang/AST/CurrentSourceLocExprScope.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/Type.h"
#include "clang/Basic/ABI.h"
#include "clang/Basic/TargetInfo.h"
#include "mlir/IR/TypeRange.h"
#include "mlir/IR/Value.h"
namespace clang {
class Expr;
} // namespace clang
namespace mlir {
namespace func {
class CallOp;
}
} // namespace mlir
namespace {
class ScalarExprEmitter;
class AggExprEmitter;
}
namespace cir {
// FIXME: for now we are reusing this from lib/Clang/CIRGenFunction.h, which
// isn't available in the include dir. Same for getEvaluationKind below.
enum TypeEvaluationKind { TEK_Scalar, TEK_Complex, TEK_Aggregate };
struct CGCoroData;
class CIRGenFunction : public CIRGenTypeCache {
public:
CIRGenModule &CGM;
private:
friend class ::ScalarExprEmitter;
friend class ::AggExprEmitter;
/// The builder is a helper class to create IR inside a function. The
/// builder is stateful, in particular it keeps an "insertion point": this
/// is where the next operations will be introduced.
CIRGenBuilderTy &builder;
/// -------
/// Goto
/// -------
/// A jump destination is an abstract label, branching to which may
/// require a jump out through normal cleanups.
struct JumpDest {
JumpDest() = default;
JumpDest(mlir::Block *Block) : Block(Block) {}
bool isValid() const { return Block != nullptr; }
mlir::Block *getBlock() const { return Block; }
mlir::Block *Block = nullptr;
};
/// Track mlir Blocks for each C/C++ label.
llvm::DenseMap<const clang::LabelDecl *, JumpDest> LabelMap;
JumpDest &getJumpDestForLabel(const clang::LabelDecl *D);
/// -------
/// Lexical Scope: to be read as in the meaning in CIR, a scope is always
/// related with initialization and destruction of objects.
/// -------
public:
// Represents a cir.scope, cir.if, and then/else regions. I.e. lexical
// scopes that require cleanups.
struct LexicalScopeContext {
private:
// Block containing cleanup code for things initialized in this
// lexical context (scope).
mlir::Block *CleanupBlock = nullptr;
// Points to scope entry block. This is useful, for instance, for
// helping to insert allocas before finalizing any recursive codegen
// from switches.
mlir::Block *EntryBlock;
// On a coroutine body, the OnFallthrough sub stmt holds the handler
// (CoreturnStmt) for control flow falling off the body. Keep track
// of emitted co_return in this scope and allow OnFallthrough to be
// skipeed.
bool HasCoreturn = false;
// FIXME: perhaps we can use some info encoded in operations.
enum Kind {
Regular, // cir.if, cir.scope, if_regions
Ternary, // cir.ternary
Switch // cir.switch
} ScopeKind = Regular;
public:
unsigned Depth = 0;
bool HasReturn = false;
LexicalScopeContext(mlir::Location b, mlir::Location e, mlir::Block *eb)
: EntryBlock(eb), BeginLoc(b), EndLoc(e) {
assert(EntryBlock && "expected valid block");
}
~LexicalScopeContext() = default;
// ---
// Coroutine tracking
// ---
bool hasCoreturn() const { return HasCoreturn; }
void setCoreturn() { HasCoreturn = true; }
// ---
// Kind
// ---
bool isRegular() { return ScopeKind == Kind::Regular; }
bool isSwitch() { return ScopeKind == Kind::Switch; }
bool isTernary() { return ScopeKind == Kind::Ternary; }
void setAsSwitch() { ScopeKind = Kind::Switch; }
void setAsTernary() { ScopeKind = Kind::Ternary; }
// ---
// Goto handling
// ---
// Lazy create cleanup block or return what's available.
mlir::Block *getOrCreateCleanupBlock(mlir::OpBuilder &builder) {
if (CleanupBlock)
return getCleanupBlock(builder);
return createCleanupBlock(builder);
}
mlir::Block *getCleanupBlock(mlir::OpBuilder &builder) {
return CleanupBlock;
}
mlir::Block *createCleanupBlock(mlir::OpBuilder &builder) {
{
// Create the cleanup block but dont hook it up around just yet.
mlir::OpBuilder::InsertionGuard guard(builder);
CleanupBlock = builder.createBlock(builder.getBlock()->getParent());
}
assert(builder.getInsertionBlock() && "Should be valid");
return CleanupBlock;
}
// Goto's introduced in this scope but didn't get fixed.
llvm::SmallVector<std::pair<mlir::Operation *, const clang::LabelDecl *>, 4>
PendingGotos;
// Labels solved inside this scope.
llvm::SmallPtrSet<const clang::LabelDecl *, 4> SolvedLabels;
// ---
// Return handling
// ---
private:
// On switches we need one return block per region, since cases don't
// have their own scopes but are distinct regions nonetheless.
llvm::SmallVector<mlir::Block *> RetBlocks;
llvm::SmallVector<llvm::Optional<mlir::Location>> RetLocs;
unsigned int CurrentSwitchRegionIdx = -1;
// There's usually only one ret block per scope, but this needs to be
// get or create because of potential unreachable return statements, note
// that for those, all source location maps to the first one found.
mlir::Block *createRetBlock(CIRGenFunction &CGF, mlir::Location loc) {
assert((isSwitch() || RetBlocks.size() == 0) &&
"only switches can hold more than one ret block");
// Create the cleanup block but dont hook it up around just yet.
mlir::OpBuilder::InsertionGuard guard(CGF.builder);
auto *b = CGF.builder.createBlock(CGF.builder.getBlock()->getParent());
RetBlocks.push_back(b);
RetLocs.push_back(loc);
return b;
}
public:
void updateCurrentSwitchCaseRegion() { CurrentSwitchRegionIdx++; }
llvm::ArrayRef<mlir::Block *> getRetBlocks() { return RetBlocks; }
llvm::ArrayRef<llvm::Optional<mlir::Location>> getRetLocs() {
return RetLocs;
}
mlir::Block *getOrCreateRetBlock(CIRGenFunction &CGF, mlir::Location loc) {
unsigned int regionIdx = 0;
if (isSwitch())
regionIdx = CurrentSwitchRegionIdx;
if (regionIdx >= RetBlocks.size())
return createRetBlock(CGF, loc);
return &*RetBlocks.back();
}
// Scope entry block tracking
mlir::Block *getEntryBlock() { return EntryBlock; }
mlir::Location BeginLoc, EndLoc;
};
private:
class LexicalScopeGuard {
CIRGenFunction &CGF;
LexicalScopeContext *OldVal = nullptr;
public:
LexicalScopeGuard(CIRGenFunction &c, LexicalScopeContext *L) : CGF(c) {
if (CGF.currLexScope) {
OldVal = CGF.currLexScope;
L->Depth++;
}
CGF.currLexScope = L;
}
LexicalScopeGuard(const LexicalScopeGuard &) = delete;
LexicalScopeGuard &operator=(const LexicalScopeGuard &) = delete;
LexicalScopeGuard &operator=(LexicalScopeGuard &&other) = delete;
void cleanup();
void restore() { CGF.currLexScope = OldVal; }
~LexicalScopeGuard() {
cleanup();
restore();
}
};
LexicalScopeContext *currLexScope = nullptr;
// ---------------------
// Opaque value handling
// ---------------------
/// Keeps track of the current set of opaque value expressions.
llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
public:
/// A non-RAII class containing all the information about a bound
/// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
/// this which makes individual mappings very simple; using this
/// class directly is useful when you have a variable number of
/// opaque values or don't want the RAII functionality for some
/// reason.
class OpaqueValueMappingData {
const OpaqueValueExpr *OpaqueValue;
bool BoundLValue;
OpaqueValueMappingData(const OpaqueValueExpr *ov, bool boundLValue)
: OpaqueValue(ov), BoundLValue(boundLValue) {}
public:
OpaqueValueMappingData() : OpaqueValue(nullptr) {}
static bool shouldBindAsLValue(const Expr *expr) {
// gl-values should be bound as l-values for obvious reasons.
// Records should be bound as l-values because IR generation
// always keeps them in memory. Expressions of function type
// act exactly like l-values but are formally required to be
// r-values in C.
return expr->isGLValue() || expr->getType()->isFunctionType() ||
hasAggregateEvaluationKind(expr->getType());
}
static OpaqueValueMappingData
bind(CIRGenFunction &CGF, const OpaqueValueExpr *ov, const Expr *e) {
if (shouldBindAsLValue(ov))
return bind(CGF, ov, CGF.buildLValue(e));
return bind(CGF, ov, CGF.buildAnyExpr(e));
}
static OpaqueValueMappingData
bind(CIRGenFunction &CGF, const OpaqueValueExpr *ov, const LValue &lv) {
assert(shouldBindAsLValue(ov));
CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
return OpaqueValueMappingData(ov, true);
}
static OpaqueValueMappingData
bind(CIRGenFunction &CGF, const OpaqueValueExpr *ov, const RValue &rv) {
assert(!shouldBindAsLValue(ov));
CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
OpaqueValueMappingData data(ov, false);
// Work around an extremely aggressive peephole optimization in
// EmitScalarConversion which assumes that all other uses of a
// value are extant.
assert(!UnimplementedFeature::peepholeProtection() && "NYI");
return data;
}
bool isValid() const { return OpaqueValue != nullptr; }
void clear() { OpaqueValue = nullptr; }
void unbind(CIRGenFunction &CGF) {
assert(OpaqueValue && "no data to unbind!");
if (BoundLValue) {
CGF.OpaqueLValues.erase(OpaqueValue);
} else {
CGF.OpaqueRValues.erase(OpaqueValue);
assert(!UnimplementedFeature::peepholeProtection() && "NYI");
}
}
};
/// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
class OpaqueValueMapping {
CIRGenFunction &CGF;
OpaqueValueMappingData Data;
public:
static bool shouldBindAsLValue(const Expr *expr) {
return OpaqueValueMappingData::shouldBindAsLValue(expr);
}
/// Build the opaque value mapping for the given conditional
/// operator if it's the GNU ?: extension. This is a common
/// enough pattern that the convenience operator is really
/// helpful.
///
OpaqueValueMapping(CIRGenFunction &CGF,
const AbstractConditionalOperator *op)
: CGF(CGF) {
if (isa<ConditionalOperator>(op))
// Leave Data empty.
return;
const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
e->getCommon());
}
/// Build the opaque value mapping for an OpaqueValueExpr whose source
/// expression is set to the expression the OVE represents.
OpaqueValueMapping(CIRGenFunction &CGF, const OpaqueValueExpr *OV)
: CGF(CGF) {
if (OV) {
assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used "
"for OVE with no source expression");
Data = OpaqueValueMappingData::bind(CGF, OV, OV->getSourceExpr());
}
}
OpaqueValueMapping(CIRGenFunction &CGF, const OpaqueValueExpr *opaqueValue,
LValue lvalue)
: CGF(CGF),
Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {}
OpaqueValueMapping(CIRGenFunction &CGF, const OpaqueValueExpr *opaqueValue,
RValue rvalue)
: CGF(CGF),
Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {}
void pop() {
Data.unbind(CGF);
Data.clear();
}
~OpaqueValueMapping() {
if (Data.isValid())
Data.unbind(CGF);
}
};
private:
/// Declare a variable in the current scope, return success if the variable
/// wasn't declared yet.
mlir::LogicalResult declare(const clang::Decl *var, clang::QualType ty,
mlir::Location loc, clang::CharUnits alignment,
mlir::Value &addr, bool isParam = false);
/// Declare a variable in the current scope but take an Address as input.
mlir::LogicalResult declare(Address addr, const clang::Decl *var,
clang::QualType ty, mlir::Location loc,
clang::CharUnits alignment, mlir::Value &addrVal,
bool isParam = false);
public:
// FIXME(cir): move this to CIRGenBuider.h
mlir::Value buildAlloca(llvm::StringRef name, clang::QualType ty,
mlir::Location loc, clang::CharUnits alignment);
mlir::Value buildAlloca(llvm::StringRef name, mlir::Type ty,
mlir::Location loc, clang::CharUnits alignment);
mlir::Value buildAlloca(llvm::StringRef name, mlir::Type ty,
mlir::Location loc, clang::CharUnits alignment,
mlir::OpBuilder::InsertPoint ip);
private:
void buildAndUpdateRetAlloca(clang::QualType ty, mlir::Location loc,
clang::CharUnits alignment);
// Track current variable initialization (if there's one)
const clang::VarDecl *currVarDecl = nullptr;
class VarDeclContext {
CIRGenFunction &P;
const clang::VarDecl *OldVal = nullptr;
public:
VarDeclContext(CIRGenFunction &p, const VarDecl *Value) : P(p) {
if (P.currVarDecl)
OldVal = P.currVarDecl;
P.currVarDecl = Value;
}
/// Can be used to restore the state early, before the dtor
/// is run.
void restore() { P.currVarDecl = OldVal; }
~VarDeclContext() { restore(); }
};
/// -------
/// Source Location tracking
/// -------
public:
/// Use to track source locations across nested visitor traversals.
/// Always use a `SourceLocRAIIObject` to change currSrcLoc.
llvm::Optional<mlir::Location> currSrcLoc;
class SourceLocRAIIObject {
CIRGenFunction &P;
llvm::Optional<mlir::Location> OldVal;
public:
SourceLocRAIIObject(CIRGenFunction &p, mlir::Location Value) : P(p) {
if (P.currSrcLoc)
OldVal = P.currSrcLoc;
P.currSrcLoc = Value;
}
/// Can be used to restore the state early, before the dtor
/// is run.
void restore() { P.currSrcLoc = OldVal; }
~SourceLocRAIIObject() { restore(); }
};
using SymTableScopeTy =
llvm::ScopedHashTableScope<const clang::Decl *, mlir::Value>;
enum class EvaluationOrder {
///! No langauge constraints on evaluation order.
Default,
///! Language semantics require left-to-right evaluation
ForceLeftToRight,
///! Language semantics require right-to-left evaluation.
ForceRightToLeft
};
/// Situations in which we might emit a check for the suitability of a pointer
/// or glvalue. Needs to be kept in sync with ubsan_handlers.cpp in
/// compiler-rt.
enum TypeCheckKind {
/// Checking the operand of a load. Must be suitably sized and aligned.
TCK_Load,
/// Checking the destination of a store. Must be suitably sized and aligned.
TCK_Store,
/// Checking the bound value in a reference binding. Must be suitably sized
/// and aligned, but is not required to refer to an object (until the
/// reference is used), per core issue 453.
TCK_ReferenceBinding,
/// Checking the object expression in a non-static data member access. Must
/// be an object within its lifetime.
TCK_MemberAccess,
/// Checking the 'this' pointer for a call to a non-static member function.
/// Must be an object within its lifetime.
TCK_MemberCall,
/// Checking the 'this' pointer for a constructor call.
TCK_ConstructorCall,
};
// Holds coroutine data if the current function is a coroutine. We use a
// wrapper to manage its lifetime, so that we don't have to define CGCoroData
// in this header.
struct CGCoroInfo {
std::unique_ptr<CGCoroData> Data;
CGCoroInfo();
~CGCoroInfo();
};
CGCoroInfo CurCoro;
bool isCoroutine() const { return CurCoro.Data != nullptr; }
/// The GlobalDecl for the current function being compiled.
clang::GlobalDecl CurGD;
/// Unified return block.
/// Not that for LLVM codegen this is a memeber variable instead.
JumpDest ReturnBlock() {
return JumpDest(currLexScope->getOrCreateCleanupBlock(builder));
}
/// The temporary alloca to hold the return value. This is
/// invalid iff the function has no return value.
Address ReturnValue = Address::invalid();
/// Tracks function scope overall cleanup handling.
EHScopeStack EHStack;
llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
/// A mapping from NRVO variables to the flags used to indicate
/// when the NRVO has been applied to this variable.
llvm::DenseMap<const VarDecl *, mlir::Value> NRVOFlags;
/// Counts of the number return expressions in the function.
unsigned NumReturnExprs = 0;
clang::QualType FnRetQualTy;
std::optional<mlir::Type> FnRetCIRTy;
std::optional<mlir::Value> FnRetAlloca;
llvm::DenseMap<const clang::ValueDecl *, clang::FieldDecl *>
LambdaCaptureFields;
clang::FieldDecl *LambdaThisCaptureField = nullptr;
void buildForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
CallArgList &CallArgs);
void buildLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
void buildLambdaStaticInvokeBody(const CXXMethodDecl *MD);
LValue buildPredefinedLValue(const PredefinedExpr *E);
/// When generating code for a C++ member function, this will
/// hold the implicit 'this' declaration.
clang::ImplicitParamDecl *CXXABIThisDecl = nullptr;
mlir::Value CXXABIThisValue = nullptr;
mlir::Value CXXThisValue = nullptr;
clang::CharUnits CXXABIThisAlignment;
clang::CharUnits CXXThisAlignment;
/// When generating code for a constructor or destructor, this will hold the
/// implicit argument (e.g. VTT).
ImplicitParamDecl *CXXStructorImplicitParamDecl{};
mlir::Value CXXStructorImplicitParamValue{};
/// The value of 'this' to sue when evaluating CXXDefaultInitExprs within this
/// expression.
Address CXXDefaultInitExprThis = Address::invalid();
// Holds the Decl for the current outermost non-closure context
const clang::Decl *CurFuncDecl = nullptr;
/// This is the inner-most code context, which includes blocks.
const clang::Decl *CurCodeDecl;
const CIRGenFunctionInfo *CurFnInfo;
clang::QualType FnRetTy;
mlir::cir::FuncOp CurFn = nullptr;
/// Save Parameter Decl for coroutine.
llvm::SmallVector<const ParmVarDecl *, 4> FnArgs;
// The CallExpr within the current statement that the musttail attribute
// applies to. nullptr if there is no 'musttail' on the current statement.
const clang::CallExpr *MustTailCall = nullptr;
clang::ASTContext &getContext() const;
CIRGenBuilderTy &getBuilder() { return builder; }
CIRGenModule &getCIRGenModule() { return CGM; }
/// Sanitizers enabled for this function.
clang::SanitizerSet SanOpts;
class CIRGenFPOptionsRAII {
public:
CIRGenFPOptionsRAII(CIRGenFunction &CGF, FPOptions FPFeatures);
CIRGenFPOptionsRAII(CIRGenFunction &CGF, const clang::Expr *E);
~CIRGenFPOptionsRAII();
private:
void ConstructorHelper(clang::FPOptions FPFeatures);
CIRGenFunction &CGF;
clang::FPOptions OldFPFeatures;
fp::ExceptionBehavior OldExcept;
llvm::RoundingMode OldRounding;
};
clang::FPOptions CurFPFeatures;
/// The symbol table maps a variable name to a value in the current scope.
/// Entering a function creates a new scope, and the function arguments are
/// added to the mapping. When the processing of a function is terminated,
/// the scope is destroyed and the mappings created in this scope are
/// dropped.
using SymTableTy = llvm::ScopedHashTable<const clang::Decl *, mlir::Value>;
SymTableTy symbolTable;
/// True if we need to emit the life-time markers. This is initially set in
/// the constructor, but could be overwrriten to true if this is a coroutine.
bool ShouldEmitLifetimeMarkers;
using DeclMapTy = llvm::DenseMap<const clang::Decl *, Address>;
/// This keeps track of the CIR allocas or globals for local C
/// delcs.
DeclMapTy LocalDeclMap;
/// Whether llvm.stacksave has been called. Used to avoid
/// calling llvm.stacksave for multiple VLAs in the same scope.
/// TODO: Translate to MLIR
bool DidCallStackSave = false;
/// Whether we processed a Microsoft-style asm block during CIRGen. These can
/// potentially set the return value.
bool SawAsmBlock = false;
/// True if CodeGen currently emits code inside preserved access index region.
bool IsInPreservedAIRegion = false;
/// In C++, whether we are code generating a thunk. This controls whether we
/// should emit cleanups.
bool CurFuncIsThunk = false;
/// Hold counters for incrementally naming temporaries
unsigned CounterRefTmp = 0;
unsigned CounterAggTmp = 0;
std::string getCounterRefTmpAsString();
std::string getCounterAggTmpAsString();
mlir::Type ConvertType(clang::QualType T);
mlir::Type ConvertType(const TypeDecl *T) {
return ConvertType(getContext().getTypeDeclType(T));
}
/// Return the TypeEvaluationKind of QualType \c T.
static TypeEvaluationKind getEvaluationKind(clang::QualType T);
static bool hasScalarEvaluationKind(clang::QualType T) {
return getEvaluationKind(T) == TEK_Scalar;
}
static bool hasAggregateEvaluationKind(clang::QualType T) {
return getEvaluationKind(T) == TEK_Aggregate;
}
CIRGenFunction(CIRGenModule &CGM, CIRGenBuilderTy &builder,
bool suppressNewContext = false);
CIRGenTypes &getTypes() const { return CGM.getTypes(); }
const TargetInfo &getTarget() const { return CGM.getTarget(); }
/// Helpers to convert Clang's SourceLocation to a MLIR Location.
mlir::Location getLoc(clang::SourceLocation SLoc);
mlir::Location getLoc(clang::SourceRange SLoc);
mlir::Location getLoc(mlir::Location lhs, mlir::Location rhs);
const clang::LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
// TODO: This is currently just a dumb stub. But we want to be able to clearly
// assert where we arne't doing things that we know we should and will crash
// as soon as we add a DebugInfo type to this class.
std::nullptr_t *getDebugInfo() { return nullptr; }
void buildReturnOfRValue(mlir::Location loc, RValue RV, QualType Ty);
/// Set the address of a local variable.
void setAddrOfLocalVar(const clang::VarDecl *VD, Address Addr) {
assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!");
LocalDeclMap.insert({VD, Addr});
}
/// True if an insertion point is defined. If not, this indicates that the
/// current code being emitted is unreachable.
/// FIXME(cir): we need to inspect this and perhaps use a cleaner mechanism
/// since we don't yet force null insertion point to designate behavior (like
/// LLVM's codegen does) and we probably shouldn't.
bool HaveInsertPoint() const {
return builder.getInsertionBlock() != nullptr;
}
/// Whether any type-checking sanitizers are enabled. If \c false, calls to
/// buildTypeCheck can be skipped.
bool sanitizePerformTypeCheck() const;
void buildTypeCheck(TypeCheckKind TCK, clang::SourceLocation Loc,
mlir::Value V, clang::QualType Type,
clang::CharUnits Alignment = clang::CharUnits::Zero(),
clang::SanitizerSet SkippedChecks = clang::SanitizerSet(),
llvm::Optional<mlir::Value> ArraySize = std::nullopt);
void buildAggExpr(const clang::Expr *E, AggValueSlot Slot);
/// Emits a reference binding to the passed in expression.
RValue buildReferenceBindingToExpr(const Expr *E);
LValue buildCastLValue(const CastExpr *E);
void buildCXXConstructExpr(const clang::CXXConstructExpr *E,
AggValueSlot Dest);
void buildCXXConstructorCall(const clang::CXXConstructorDecl *D,
clang::CXXCtorType Type, bool ForVirtualBase,
bool Delegating, AggValueSlot ThisAVS,
const clang::CXXConstructExpr *E);
void buildCXXConstructorCall(const clang::CXXConstructorDecl *D,
clang::CXXCtorType Type, bool ForVirtualBase,
bool Delegating, Address This, CallArgList &Args,
AggValueSlot::Overlap_t Overlap,
clang::SourceLocation Loc,
bool NewPointerIsChecked);
RValue buildCXXMemberOrOperatorCall(
const clang::CXXMethodDecl *Method, const CIRGenCallee &Callee,
ReturnValueSlot ReturnValue, mlir::Value This, mlir::Value ImplicitParam,
clang::QualType ImplicitParamTy, const clang::CallExpr *E,
CallArgList *RtlArgs);
RValue buildCXXMemberCallExpr(const clang::CXXMemberCallExpr *E,
ReturnValueSlot ReturnValue);
RValue buildCXXMemberOrOperatorMemberCallExpr(
const clang::CallExpr *CE, const clang::CXXMethodDecl *MD,
ReturnValueSlot ReturnValue, bool HasQualifier,
clang::NestedNameSpecifier *Qualifier, bool IsArrow,
const clang::Expr *Base);
RValue buildCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
const CXXMethodDecl *MD,
ReturnValueSlot ReturnValue);
void buildNullInitialization(mlir::Location loc, Address DestPtr,
QualType Ty);
bool shouldNullCheckClassCastValue(const CastExpr *CE);
void buildCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
Address Ptr);
mlir::Value buildCXXNewExpr(const CXXNewExpr *E);
void buildDeleteCall(const FunctionDecl *DeleteFD, mlir::Value Ptr,
QualType DeleteTy, mlir::Value NumElements = nullptr,
CharUnits CookieSize = CharUnits());
mlir::Value createLoad(const clang::VarDecl *VD, const char *Name);
// Wrapper for function prototype sources. Wraps either a FunctionProtoType or
// an ObjCMethodDecl.
struct PrototypeWrapper {
llvm::PointerUnion<const clang::FunctionProtoType *,
const clang::ObjCMethodDecl *>
P;
PrototypeWrapper(const clang::FunctionProtoType *FT) : P(FT) {}
PrototypeWrapper(const clang::ObjCMethodDecl *MD) : P(MD) {}
};
bool LValueIsSuitableForInlineAtomic(LValue Src);
/// An abstract representation of regular/ObjC call/message targets.
class AbstractCallee {
/// The function declaration of the callee.
const clang::Decl *CalleeDecl;
public:
AbstractCallee() : CalleeDecl(nullptr) {}
AbstractCallee(const clang::FunctionDecl *FD) : CalleeDecl(FD) {}
AbstractCallee(const clang::ObjCMethodDecl *OMD) : CalleeDecl(OMD) {}
bool hasFunctionDecl() const {
return llvm::isa_and_nonnull<clang::FunctionDecl>(CalleeDecl);
}
const clang::Decl *getDecl() const { return CalleeDecl; }
unsigned getNumParams() const {
if (const auto *FD = llvm::dyn_cast<clang::FunctionDecl>(CalleeDecl))
return FD->getNumParams();
return llvm::cast<clang::ObjCMethodDecl>(CalleeDecl)->param_size();
}
const clang::ParmVarDecl *getParamDecl(unsigned I) const {
if (const auto *FD = llvm::dyn_cast<clang::FunctionDecl>(CalleeDecl))
return FD->getParamDecl(I);
return *(llvm::cast<clang::ObjCMethodDecl>(CalleeDecl)->param_begin() +
I);
}
};
RValue convertTempToRValue(Address addr, clang::QualType type,
clang::SourceLocation Loc);
/// 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 buildLoadOfLValue(LValue LV, SourceLocation Loc);
mlir::Value buildLoadOfScalar(Address Addr, bool Volatile, clang::QualType Ty,
clang::SourceLocation Loc,
LValueBaseInfo BaseInfo,
bool isNontemporal = false);
/// Load a scalar value from an address, taking care to appropriately convert
/// form the memory representation to the CIR value representation. The
/// l-value must be a simple l-value.
mlir::Value buildLoadOfScalar(LValue lvalue, clang::SourceLocation Loc);
Address buildLoadOfReference(LValue RefLVal, mlir::Location Loc,
LValueBaseInfo *PointeeBaseInfo = nullptr);
LValue buildLoadOfReferenceLValue(LValue RefLVal, mlir::Location Loc);
LValue
buildLoadOfReferenceLValue(Address RefAddr, mlir::Location Loc,
QualType RefTy,
AlignmentSource Source = AlignmentSource::Type) {
LValue RefLVal = makeAddrLValue(RefAddr, RefTy, LValueBaseInfo(Source));
return buildLoadOfReferenceLValue(RefLVal, Loc);
}
void buildImplicitAssignmentOperatorBody(FunctionArgList &Args);
void buildAggregateStore(mlir::Value Val, Address Dest, bool DestIsVolatile);
void buildCallArgs(
CallArgList &Args, PrototypeWrapper Prototype,
llvm::iterator_range<clang::CallExpr::const_arg_iterator> ArgRange,
AbstractCallee AC = AbstractCallee(), unsigned ParamsToSkip = 0,
EvaluationOrder Order = EvaluationOrder::Default);
/// Generate a call of the given function, expecting the given
/// result type, and using the given argument list which specifies both the
/// LLVM arguments and the types they were derived from.
RValue buildCall(const CIRGenFunctionInfo &CallInfo,
const CIRGenCallee &Callee, ReturnValueSlot ReturnValue,
const CallArgList &Args, mlir::cir::CallOp *callOrInvoke,
bool IsMustTail, mlir::Location loc);
RValue buildCall(const CIRGenFunctionInfo &CallInfo,
const CIRGenCallee &Callee, ReturnValueSlot ReturnValue,
const CallArgList &Args,
mlir::cir::CallOp *callOrInvoke = nullptr,
bool IsMustTail = false) {
assert(currSrcLoc && "source location must have been set");
return buildCall(CallInfo, Callee, ReturnValue, Args, callOrInvoke,
IsMustTail, *currSrcLoc);
}
RValue buildCall(clang::QualType FnType, const CIRGenCallee &Callee,
const clang::CallExpr *E, ReturnValueSlot returnValue,
mlir::Value Chain = nullptr);
RValue buildCallExpr(const clang::CallExpr *E,
ReturnValueSlot ReturnValue = ReturnValueSlot());
void buildCallArg(CallArgList &args, const clang::Expr *E,
clang::QualType ArgType);
LValue buildCallExprLValue(const CallExpr *E);
/// Similarly to buildAnyExpr(), however, the result will always be accessible
/// even if no aggregate location is provided.
RValue buildAnyExprToTemp(const clang::Expr *E);
CIRGenCallee buildCallee(const clang::Expr *E);
/// Emit code to compute the specified expression which can have any type. The
/// result is returned as an RValue struct. If this is an aggregate
/// expression, the aggloc/agglocvolatile arguments indicate where the result
/// should be returned.
RValue buildAnyExpr(const clang::Expr *E,
AggValueSlot aggSlot = AggValueSlot::ignored(),
bool ignoreResult = false);
mlir::LogicalResult buildFunctionBody(const clang::Stmt *Body);
mlir::LogicalResult buildCoroutineBody(const CoroutineBodyStmt &S);
mlir::LogicalResult buildCoreturnStmt(const CoreturnStmt &S);
mlir::cir::CallOp buildCoroIDBuiltinCall(mlir::Location loc,
mlir::Value nullPtr);
mlir::cir::CallOp buildCoroAllocBuiltinCall(mlir::Location loc);
mlir::cir::CallOp buildCoroBeginBuiltinCall(mlir::Location loc,
mlir::Value coroframeAddr);
mlir::cir::CallOp buildCoroEndBuiltinCall(mlir::Location loc,
mlir::Value nullPtr);
RValue buildCoawaitExpr(const CoawaitExpr &E,
AggValueSlot aggSlot = AggValueSlot::ignored(),
bool ignoreResult = false);
RValue buildCoroutineIntrinsic(const CallExpr *E, unsigned int IID);
RValue buildCoroutineFrame();
// Build CIR for a statement. useCurrentScope should be true if no
// new scopes need be created when finding a compound statement.
mlir::LogicalResult buildStmt(const clang::Stmt *S, bool useCurrentScope);
mlir::LogicalResult buildSimpleStmt(const clang::Stmt *S,
bool useCurrentScope);
mlir::LogicalResult buildForStmt(const clang::ForStmt &S);
mlir::LogicalResult buildWhileStmt(const clang::WhileStmt &S);
mlir::LogicalResult buildDoStmt(const clang::DoStmt &S);
mlir::LogicalResult buildSwitchStmt(const clang::SwitchStmt &S);
mlir::LogicalResult buildCompoundStmt(const clang::CompoundStmt &S);
mlir::LogicalResult
buildCompoundStmtWithoutScope(const clang::CompoundStmt &S);
/// Emit code to compute the specified expression,
/// ignoring the result.
void buildIgnoredExpr(const clang::Expr *E);
LValue buildArraySubscriptExpr(const clang::ArraySubscriptExpr *E,
bool Accessed = false);
mlir::LogicalResult buildDeclStmt(const clang::DeclStmt &S);
/// Determine whether a return value slot may overlap some other object.
AggValueSlot::Overlap_t getOverlapForReturnValue() {
// FIXME: Assuming no overlap here breaks guaranteed copy elision for base
// class subobjects. These cases may need to be revisited depending on the
// resolution of the relevant core issue.
return AggValueSlot::DoesNotOverlap;
}
/// Determine whether a base class initialization may overlap some other
/// object.
AggValueSlot::Overlap_t getOverlapForBaseInit(const CXXRecordDecl *RD,
const CXXRecordDecl *BaseRD,
bool IsVirtual);
/// Get an appropriate 'undef' rvalue for the given type.
/// TODO: What's the equivalent for MLIR? Currently we're only using this for
/// void types so it just returns RValue::get(nullptr) but it'll need
/// addressed later.
RValue GetUndefRValue(clang::QualType Ty);
mlir::Value buildFromMemory(mlir::Value Value, clang::QualType Ty);
mlir::Type convertType(clang::QualType T);
mlir::LogicalResult buildIfStmt(const clang::IfStmt &S);
mlir::LogicalResult buildReturnStmt(const clang::ReturnStmt &S);
mlir::LogicalResult buildGotoStmt(const clang::GotoStmt &S);
mlir::LogicalResult buildLabel(const clang::LabelDecl *D);
mlir::LogicalResult buildLabelStmt(const clang::LabelStmt &S);
mlir::LogicalResult buildBreakStmt(const clang::BreakStmt &S);
mlir::LogicalResult buildContinueStmt(const clang::ContinueStmt &S);
LValue buildOpaqueValueLValue(const OpaqueValueExpr *e);
/// Emit code to compute a designator that specifies the location
/// of the expression.
/// FIXME: document this function better.
LValue buildLValue(const clang::Expr *E);
void buildDecl(const clang::Decl &D);
/// If the specified expression does not fold to a constant, or if it does but
/// contains a label, return false. If it constant folds return true and set
/// the boolean result in Result.
bool ConstantFoldsToSimpleInteger(const clang::Expr *Cond, bool &ResultBool,
bool AllowLabels = false);
bool ConstantFoldsToSimpleInteger(const clang::Expr *Cond,
llvm::APSInt &ResultInt,
bool AllowLabels = false);
/// Return true if the statement contains a label in it. If
/// this statement is not executed normally, it not containing a label means
/// that we can just remove the code.
bool ContainsLabel(const clang::Stmt *S, bool IgnoreCaseStmts = false);
/// Emit an if on a boolean condition to the specified blocks.
/// FIXME: Based on the condition, this might try to simplify the codegen of
/// the conditional based on the branch. TrueCount should be the number of
/// times we expect the condition to evaluate to true based on PGO data. We
/// might decide to leave this as a separate pass (see EmitBranchOnBoolExpr
/// for extra ideas).
mlir::LogicalResult buildIfOnBoolExpr(const clang::Expr *cond,
mlir::Location loc,
const clang::Stmt *thenS,
const clang::Stmt *elseS);
mlir::Value buildTernaryOnBoolExpr(const clang::Expr *cond,
mlir::Location loc,
const clang::Stmt *thenS,
const clang::Stmt *elseS);
mlir::Value buildOpOnBoolExpr(const clang::Expr *cond, mlir::Location loc,
const clang::Stmt *thenS,
const clang::Stmt *elseS);
class ConstantEmission {
// Cannot use mlir::TypedAttr directly here because of bit availability.
llvm::PointerIntPair<mlir::Attribute, 1, bool> ValueAndIsReference;
ConstantEmission(mlir::TypedAttr C, bool isReference)
: ValueAndIsReference(C, isReference) {}
public: