-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathCIRGenCall.cpp
1644 lines (1386 loc) · 64 KB
/
CIRGenCall.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
//===--- CIRGenCall.cpp - Encapsulate calling convention details ----------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// These classes wrap the information about a call or function
// definition used to handle ABI compliancy.
//
//===----------------------------------------------------------------------===//
#include "CIRGenCall.h"
#include "CIRGenBuilder.h"
#include "CIRGenCXXABI.h"
#include "CIRGenFunction.h"
#include "CIRGenFunctionInfo.h"
#include "CIRGenTypes.h"
#include "TargetInfo.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Attrs.inc"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/GlobalDecl.h"
#include "clang/CIR/ABIArgInfo.h"
#include "clang/CIR/Dialect/IR/CIRDialect.h"
#include "clang/CIR/Dialect/IR/CIRTypes.h"
#include "clang/CIR/FnInfoOpts.h"
#include "llvm/Support/ErrorHandling.h"
#include <cassert>
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Location.h"
#include "mlir/IR/SymbolTable.h"
#include "mlir/IR/Types.h"
#include "clang/CIR/MissingFeatures.h"
using namespace clang;
using namespace clang::CIRGen;
CIRGenFunctionInfo *CIRGenFunctionInfo::create(
cir::CallingConv cirCC, bool instanceMethod, bool chainCall,
const FunctionType::ExtInfo &info,
llvm::ArrayRef<ExtParameterInfo> paramInfos, CanQualType resultType,
llvm::ArrayRef<CanQualType> argTypes, RequiredArgs required) {
assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
assert(!required.allowsOptionalArgs() ||
required.getNumRequiredArgs() <= argTypes.size());
void *buffer = operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
argTypes.size() + 1, paramInfos.size()));
CIRGenFunctionInfo *FI = new (buffer) CIRGenFunctionInfo();
FI->CallingConvention = cirCC;
FI->EffectiveCallingConvention = cirCC;
FI->ASTCallingConvention = info.getCC();
FI->InstanceMethod = instanceMethod;
FI->ChainCall = chainCall;
FI->CmseNSCall = info.getCmseNSCall();
FI->NoReturn = info.getNoReturn();
FI->ReturnsRetained = info.getProducesResult();
FI->NoCallerSavedRegs = info.getNoCallerSavedRegs();
FI->NoCfCheck = info.getNoCfCheck();
FI->Required = required;
FI->HasRegParm = info.getHasRegParm();
FI->RegParm = info.getRegParm();
FI->ArgStruct = nullptr;
FI->ArgStructAlign = 0;
FI->NumArgs = argTypes.size();
FI->HasExtParameterInfos = !paramInfos.empty();
FI->getArgsBuffer()[0].type = resultType;
for (unsigned i = 0; i < argTypes.size(); ++i)
FI->getArgsBuffer()[i + 1].type = argTypes[i];
for (unsigned i = 0; i < paramInfos.size(); ++i)
FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
return FI;
}
namespace {
/// Encapsulates information about the way function arguments from
/// CIRGenFunctionInfo should be passed to actual CIR function.
class ClangToCIRArgMapping {
static const unsigned InvalidIndex = ~0U;
unsigned InallocaArgNo;
unsigned SRetArgNo;
unsigned TotalCIRArgs;
/// Arguments of CIR function corresponding to single Clang argument.
struct CIRArgs {
unsigned PaddingArgIndex = 0;
// Argument is expanded to CIR arguments at positions
// [FirstArgIndex, FirstArgIndex + NumberOfArgs).
unsigned FirstArgIndex = 0;
unsigned NumberOfArgs = 0;
CIRArgs()
: PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
NumberOfArgs(0) {}
};
SmallVector<CIRArgs, 8> ArgInfo;
public:
ClangToCIRArgMapping(const ASTContext &astContext,
const CIRGenFunctionInfo &FI,
bool OnlyRequiredArgs = false)
: InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalCIRArgs(0),
ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
construct(astContext, FI, OnlyRequiredArgs);
}
bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
unsigned totalCIRArgs() const { return TotalCIRArgs; }
bool hasPaddingArg(unsigned ArgNo) const {
assert(ArgNo < ArgInfo.size());
return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
}
/// Returns index of first CIR argument corresponding to ArgNo, and their
/// quantity.
std::pair<unsigned, unsigned> getCIRArgs(unsigned ArgNo) const {
assert(ArgNo < ArgInfo.size());
return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
ArgInfo[ArgNo].NumberOfArgs);
}
private:
void construct(const ASTContext &astContext, const CIRGenFunctionInfo &FI,
bool OnlyRequiredArgs);
};
void ClangToCIRArgMapping::construct(const ASTContext &astContext,
const CIRGenFunctionInfo &FI,
bool OnlyRequiredArgs) {
unsigned CIRArgNo = 0;
bool SwapThisWithSRet = false;
const cir::ABIArgInfo &RetAI = FI.getReturnInfo();
assert(RetAI.getKind() != cir::ABIArgInfo::Indirect && "NYI");
unsigned ArgNo = 0;
unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
for (CIRGenFunctionInfo::const_arg_iterator I = FI.arg_begin();
ArgNo < NumArgs; ++I, ++ArgNo) {
assert(I != FI.arg_end());
const cir::ABIArgInfo &AI = I->info;
// Collect data about CIR arguments corresponding to Clang argument ArgNo.
auto &CIRArgs = ArgInfo[ArgNo];
assert(!AI.getPaddingType() && "NYI");
switch (AI.getKind()) {
default:
llvm_unreachable("NYI");
case cir::ABIArgInfo::Extend:
case cir::ABIArgInfo::Direct: {
// Postpone splitting structs into elements since this makes it way
// more complicated for analysis to obtain information on the original
// arguments.
//
// TODO(cir): a LLVM lowering prepare pass should break this down into
// the appropriated pieces.
assert(!cir::MissingFeatures::constructABIArgDirectExtend());
CIRArgs.NumberOfArgs = 1;
break;
}
}
if (CIRArgs.NumberOfArgs > 0) {
CIRArgs.FirstArgIndex = CIRArgNo;
CIRArgNo += CIRArgs.NumberOfArgs;
}
assert(!SwapThisWithSRet && "NYI");
}
assert(ArgNo == ArgInfo.size());
assert(!FI.usesInAlloca() && "NYI");
TotalCIRArgs = CIRArgNo;
}
} // namespace
static bool hasInAllocaArgs(CIRGenModule &CGM, CallingConv ExplicitCC,
ArrayRef<QualType> ArgTypes) {
assert(ExplicitCC != CC_Swift && ExplicitCC != CC_SwiftAsync && "Swift NYI");
assert(!CGM.getTarget().getCXXABI().isMicrosoft() && "MSABI NYI");
return false;
}
cir::FuncType CIRGenTypes::GetFunctionType(GlobalDecl GD) {
const CIRGenFunctionInfo &FI = arrangeGlobalDeclaration(GD);
return GetFunctionType(FI);
}
cir::FuncType CIRGenTypes::GetFunctionType(const CIRGenFunctionInfo &FI) {
bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
(void)Inserted;
assert(Inserted && "Recursively being processed?");
mlir::Type resultType = nullptr;
const cir::ABIArgInfo &retAI = FI.getReturnInfo();
switch (retAI.getKind()) {
case cir::ABIArgInfo::Ignore:
// TODO(CIR): This should probably be the None type from the builtin
// dialect.
resultType = nullptr;
break;
case cir::ABIArgInfo::Extend:
case cir::ABIArgInfo::Direct:
resultType = retAI.getCoerceToType();
break;
default:
assert(false && "NYI");
}
ClangToCIRArgMapping CIRFunctionArgs(getContext(), FI, true);
SmallVector<mlir::Type, 8> ArgTypes(CIRFunctionArgs.totalCIRArgs());
assert(!CIRFunctionArgs.hasSRetArg() && "NYI");
assert(!CIRFunctionArgs.hasInallocaArg() && "NYI");
// Add in all of the required arguments.
unsigned ArgNo = 0;
CIRGenFunctionInfo::const_arg_iterator it = FI.arg_begin(),
ie = it + FI.getNumRequiredArgs();
for (; it != ie; ++it, ++ArgNo) {
const auto &ArgInfo = it->info;
assert(!CIRFunctionArgs.hasPaddingArg(ArgNo) && "NYI");
unsigned FirstCIRArg, NumCIRArgs;
std::tie(FirstCIRArg, NumCIRArgs) = CIRFunctionArgs.getCIRArgs(ArgNo);
switch (ArgInfo.getKind()) {
default:
llvm_unreachable("NYI");
case cir::ABIArgInfo::Extend:
case cir::ABIArgInfo::Direct: {
mlir::Type argType = ArgInfo.getCoerceToType();
// TODO: handle the test against llvm::StructType from codegen
assert(NumCIRArgs == 1);
ArgTypes[FirstCIRArg] = argType;
break;
}
}
}
bool Erased = FunctionsBeingProcessed.erase(&FI);
(void)Erased;
assert(Erased && "Not in set?");
return cir::FuncType::get(ArgTypes,
(resultType ? resultType : Builder.getVoidTy()),
FI.isVariadic());
}
cir::FuncType CIRGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
if (!isFuncTypeConvertible(FPT)) {
llvm_unreachable("NYI");
// return llvm::StructType::get(getLLVMContext());
}
return GetFunctionType(GD);
}
CIRGenCallee CIRGenCallee::prepareConcreteCallee(CIRGenFunction &CGF) const {
if (isVirtual()) {
const CallExpr *CE = getVirtualCallExpr();
return CGF.CGM.getCXXABI().getVirtualFunctionPointer(
CGF, getVirtualMethodDecl(), getThisAddress(), getVirtualFunctionType(),
CE ? CE->getBeginLoc() : SourceLocation());
}
return *this;
}
void CIRGenFunction::emitAggregateStore(mlir::Value Val, Address Dest,
bool DestIsVolatile) {
// In LLVM codegen:
// Function to store a first-class aggregate into memory. We prefer to
// store the elements rather than the aggregate to be more friendly to
// fast-isel.
// In CIR codegen:
// Emit the most simple cir.store possible (e.g. a store for a whole
// struct), which can later be broken down in other CIR levels (or prior
// to dialect codegen).
(void)DestIsVolatile;
// Stored result for the callers of this function expected to be in the same
// scope as the value, don't make assumptions about current insertion point.
mlir::OpBuilder::InsertionGuard guard(builder);
builder.setInsertionPointAfter(Val.getDefiningOp());
builder.createStore(*currSrcLoc, Val, Dest);
}
static Address emitAddressAtOffset(CIRGenFunction &CGF, Address addr,
const cir::ABIArgInfo &info) {
if (unsigned offset = info.getDirectOffset()) {
llvm_unreachable("NYI");
}
return addr;
}
static void AddAttributesFromFunctionProtoType(CIRGenBuilderTy &builder,
ASTContext &astContext,
mlir::NamedAttrList &FuncAttrs,
const FunctionProtoType *FPT) {
if (!FPT)
return;
if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
FPT->isNothrow()) {
auto nu = cir::NoThrowAttr::get(builder.getContext());
FuncAttrs.set(nu.getMnemonic(), nu);
}
}
/// Construct the CIR attribute list of a function or call.
///
/// When adding an attribute, please consider where it should be handled:
///
/// - getDefaultFunctionAttributes is for attributes that are essentially
/// part of the global target configuration (but perhaps can be
/// overridden on a per-function basis). Adding attributes there
/// will cause them to also be set in frontends that build on Clang's
/// target-configuration logic, as well as for code defined in library
/// modules such as CUDA's libdevice.
///
/// - constructAttributeList builds on top of getDefaultFunctionAttributes
/// and adds declaration-specific, convention-specific, and
/// frontend-specific logic. The last is of particular importance:
/// attributes that restrict how the frontend generates code must be
/// added here rather than getDefaultFunctionAttributes.
///
void CIRGenModule::constructAttributeList(StringRef Name,
const CIRGenFunctionInfo &FI,
CIRGenCalleeInfo CalleeInfo,
mlir::NamedAttrList &funcAttrs,
cir::CallingConv &callingConv,
bool AttrOnCallSite, bool IsThunk) {
// Implementation Disclaimer
//
// UnimplementedFeature and asserts are used throughout the code to track
// unsupported and things not yet implemented. However, most of the content of
// this function is on detecting attributes, which doesn't not cope with
// existing approaches to track work because its too big.
//
// That said, for the most part, the approach here is very specific compared
// to the rest of CIRGen and attributes and other handling should be done upon
// demand.
// Collect function CIR attributes from the CC lowering.
callingConv = FI.getEffectiveCallingConvention();
// TODO: NoReturn, cmse_nonsecure_call
// Collect function CIR attributes from the callee prototype if we have one.
AddAttributesFromFunctionProtoType(getBuilder(), astContext, funcAttrs,
CalleeInfo.getCalleeFunctionProtoType());
const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl();
// TODO(cir): Attach assumption attributes to the declaration. If this is a
// call site, attach assumptions from the caller to the call as well.
bool HasOptnone = false;
(void)HasOptnone;
// The NoBuiltinAttr attached to the target FunctionDecl.
mlir::Attribute *NBA;
if (TargetDecl) {
if (TargetDecl->hasAttr<NoThrowAttr>()) {
auto nu = cir::NoThrowAttr::get(&getMLIRContext());
funcAttrs.set(nu.getMnemonic(), nu);
}
if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
AddAttributesFromFunctionProtoType(
getBuilder(), astContext, funcAttrs,
Fn->getType()->getAs<FunctionProtoType>());
if (AttrOnCallSite && Fn->isReplaceableGlobalAllocationFunction()) {
// A sane operator new returns a non-aliasing pointer.
auto Kind = Fn->getDeclName().getCXXOverloadedOperator();
if (getCodeGenOpts().AssumeSaneOperatorNew &&
(Kind == OO_New || Kind == OO_Array_New))
; // llvm::Attribute::NoAlias
}
const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
const bool IsVirtualCall = MD && MD->isVirtual();
// Don't use [[noreturn]], _Noreturn or [[no_builtin]] for a call to a
// virtual function. These attributes are not inherited by overloads.
if (!(AttrOnCallSite && IsVirtualCall)) {
if (Fn->isNoReturn())
; // NoReturn
// NBA = Fn->getAttr<NoBuiltinAttr>();
(void)NBA;
}
}
if (isa<FunctionDecl>(TargetDecl) || isa<VarDecl>(TargetDecl)) {
// Only place nomerge attribute on call sites, never functions. This
// allows it to work on indirect virtual function calls.
if (AttrOnCallSite && TargetDecl->hasAttr<NoMergeAttr>())
;
}
// 'const', 'pure' and 'noalias' attributed functions are also nounwind.
if (TargetDecl->hasAttr<ConstAttr>()) {
// gcc specifies that 'const' functions have greater restrictions than
// 'pure' functions, so they also cannot have infinite loops.
} else if (TargetDecl->hasAttr<PureAttr>()) {
// gcc specifies that 'pure' functions cannot have infinite loops.
} else if (TargetDecl->hasAttr<NoAliasAttr>()) {
}
HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
std::optional<unsigned> NumElemsParam;
if (AllocSize->getNumElemsParam().isValid())
NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
// TODO(cir): add alloc size attr.
}
if (TargetDecl->hasAttr<OpenCLKernelAttr>()) {
auto cirKernelAttr = cir::OpenCLKernelAttr::get(&getMLIRContext());
funcAttrs.set(cirKernelAttr.getMnemonic(), cirKernelAttr);
auto uniformAttr =
cir::OpenCLKernelUniformWorkGroupSizeAttr::get(&getMLIRContext());
if (getLangOpts().OpenCLVersion <= 120) {
// OpenCL v1.2 Work groups are always uniform
funcAttrs.set(uniformAttr.getMnemonic(), uniformAttr);
} else {
// OpenCL v2.0 Work groups may be whether uniform or not.
// '-cl-uniform-work-group-size' compile option gets a hint
// to the compiler that the global work-size be a multiple of
// the work-group size specified to clEnqueueNDRangeKernel
// (i.e. work groups are uniform).
if (getLangOpts().OffloadUniformBlock) {
funcAttrs.set(uniformAttr.getMnemonic(), uniformAttr);
}
}
}
if (TargetDecl->hasAttr<CUDAGlobalAttr>() &&
getLangOpts().OffloadUniformBlock)
assert(!cir::MissingFeatures::CUDA());
if (TargetDecl->hasAttr<ArmLocallyStreamingAttr>())
;
}
getDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite, funcAttrs);
}
static cir::CIRCallOpInterface emitCallLikeOp(
CIRGenFunction &CGF, mlir::Location callLoc, cir::FuncType indirectFuncTy,
mlir::Value indirectFuncVal, cir::FuncOp directFuncOp,
SmallVectorImpl<mlir::Value> &CIRCallArgs, bool isInvoke,
cir::CallingConv callingConv, cir::ExtraFuncAttributesAttr extraFnAttrs) {
auto &builder = CGF.getBuilder();
auto getOrCreateSurroundingTryOp = [&]() {
// In OG, we build the landing pad for this scope. In CIR, we emit a
// synthetic cir.try because this didn't come from codegenerating from a
// try/catch in C++.
assert(CGF.currLexScope && "expected scope");
cir::TryOp op = CGF.currLexScope->getClosestTryParent();
if (op)
return op;
op = builder.create<cir::TryOp>(
*CGF.currSrcLoc, /*scopeBuilder=*/
[&](mlir::OpBuilder &b, mlir::Location loc) {},
// Don't emit the code right away for catch clauses, for
// now create the regions and consume the try scope result.
// Note that clauses are later populated in
// CIRGenFunction::emitLandingPad.
[&](mlir::OpBuilder &b, mlir::Location loc,
mlir::OperationState &result) {
// Since this didn't come from an explicit try, we only need one
// handler: unwind.
auto *r = result.addRegion();
builder.createBlock(r);
});
op.setSynthetic(true);
return op;
};
if (isInvoke) {
// This call can throw, few options:
// - If this call does not have an associated cir.try, use the
// one provided by InvokeDest,
// - User written try/catch clauses require calls to handle
// exceptions under cir.try.
auto tryOp = getOrCreateSurroundingTryOp();
assert(tryOp && "expected");
mlir::OpBuilder::InsertPoint ip = builder.saveInsertionPoint();
if (tryOp.getSynthetic()) {
mlir::Block *lastBlock = &tryOp.getTryRegion().back();
builder.setInsertionPointToStart(lastBlock);
} else {
assert(builder.getInsertionBlock() && "expected valid basic block");
}
cir::CallOp callOpWithExceptions;
// TODO(cir): Set calling convention for `cir.try_call`.
assert(callingConv == cir::CallingConv::C && "NYI");
if (indirectFuncTy) {
callOpWithExceptions = builder.createIndirectTryCallOp(
callLoc, indirectFuncVal, indirectFuncTy, CIRCallArgs);
} else {
callOpWithExceptions =
builder.createTryCallOp(callLoc, directFuncOp, CIRCallArgs);
}
callOpWithExceptions->setAttr("extra_attrs", extraFnAttrs);
CGF.callWithExceptionCtx = callOpWithExceptions;
auto *invokeDest = CGF.getInvokeDest(tryOp);
(void)invokeDest;
CGF.callWithExceptionCtx = nullptr;
if (tryOp.getSynthetic()) {
builder.create<cir::YieldOp>(tryOp.getLoc());
builder.restoreInsertionPoint(ip);
}
return callOpWithExceptions;
}
assert(builder.getInsertionBlock() && "expected valid basic block");
if (indirectFuncTy) {
// TODO(cir): Set calling convention for indirect calls.
assert(callingConv == cir::CallingConv::C && "NYI");
return builder.createIndirectCallOp(callLoc, indirectFuncVal,
indirectFuncTy, CIRCallArgs,
cir::CallingConv::C, extraFnAttrs);
}
return builder.createCallOp(callLoc, directFuncOp, CIRCallArgs, callingConv,
extraFnAttrs);
}
RValue CIRGenFunction::emitCall(const CIRGenFunctionInfo &CallInfo,
const CIRGenCallee &Callee,
ReturnValueSlot ReturnValue,
const CallArgList &CallArgs,
cir::CIRCallOpInterface *callOrTryCall,
bool IsMustTail, mlir::Location loc,
std::optional<const clang::CallExpr *> E) {
auto builder = CGM.getBuilder();
// FIXME: We no longer need the types from CallArgs; lift up and simplify
assert(Callee.isOrdinary() || Callee.isVirtual());
// Handle struct-return functions by passing a pointer to the location that we
// would like to return info.
QualType RetTy = CallInfo.getReturnType();
const auto &RetAI = CallInfo.getReturnInfo();
cir::FuncType CIRFuncTy = getTypes().GetFunctionType(CallInfo);
const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
// This is not always tied to a FunctionDecl (e.g. builtins that are xformed
// into calls to other functions)
if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
// We can only guarantee that a function is called from the correct
// context/function based on the appropriate target attributes,
// so only check in the case where we have both always_inline and target
// since otherwise we could be making a conditional call after a check for
// the proper cpu features (and it won't cause code generation issues due to
// function based code generation).
if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
(TargetDecl->hasAttr<TargetAttr>() ||
(CurFuncDecl && CurFuncDecl->hasAttr<TargetAttr>()))) {
// FIXME(cir): somehow refactor this function to use SourceLocation?
SourceLocation Loc;
checkTargetFeatures(Loc, FD);
}
// Some architectures (such as x86-64) have the ABI changed based on
// attribute-target/features. Give them a chance to diagnose.
assert(!cir::MissingFeatures::checkFunctionCallABI());
}
// TODO: add DNEBUG code
// 1. Set up the arguments
// If we're using inalloca, insert the allocation after the stack save.
// FIXME: Do this earlier rather than hacking it in here!
Address ArgMemory = Address::invalid();
assert(!CallInfo.getArgStruct() && "NYI");
ClangToCIRArgMapping CIRFunctionArgs(CGM.getASTContext(), CallInfo);
SmallVector<mlir::Value, 16> CIRCallArgs(CIRFunctionArgs.totalCIRArgs());
// If the call returns a temporary with struct return, create a temporary
// alloca to hold the result, unless one is given to us.
assert(!RetAI.isIndirect() && !RetAI.isInAlloca() &&
!RetAI.isCoerceAndExpand() && "NYI");
// When passing arguments using temporary allocas, we need to add the
// appropriate lifetime markers. This vector keeps track of all the lifetime
// markers that need to be ended right after the call.
assert(!cir::MissingFeatures::shouldEmitLifetimeMarkers() && "NYI");
// Translate all of the arguments as necessary to match the CIR lowering.
assert(CallInfo.arg_size() == CallArgs.size() &&
"Mismatch between function signature & arguments.");
unsigned ArgNo = 0;
CIRGenFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
I != E; ++I, ++info_it, ++ArgNo) {
const cir::ABIArgInfo &ArgInfo = info_it->info;
// Insert a padding argument to ensure proper alignment.
assert(!CIRFunctionArgs.hasPaddingArg(ArgNo) && "Padding args NYI");
unsigned FirstCIRArg, NumCIRArgs;
std::tie(FirstCIRArg, NumCIRArgs) = CIRFunctionArgs.getCIRArgs(ArgNo);
switch (ArgInfo.getKind()) {
case cir::ABIArgInfo::Direct: {
if (!mlir::isa<cir::StructType>(ArgInfo.getCoerceToType()) &&
ArgInfo.getCoerceToType() == convertType(info_it->type) &&
ArgInfo.getDirectOffset() == 0) {
assert(NumCIRArgs == 1);
mlir::Value V;
assert(!I->isAggregate() && "Aggregate NYI");
V = I->getKnownRValue().getScalarVal();
assert(CallInfo.getExtParameterInfo(ArgNo).getABI() !=
ParameterABI::SwiftErrorResult &&
"swift NYI");
// We might have to widen integers, but we should never truncate.
if (ArgInfo.getCoerceToType() != V.getType() &&
mlir::isa<cir::IntType>(V.getType()))
llvm_unreachable("NYI");
// If the argument doesn't match, perform a bitcast to coerce it. This
// can happen due to trivial type mismatches.
if (FirstCIRArg < CIRFuncTy.getNumInputs() &&
V.getType() != CIRFuncTy.getInput(FirstCIRArg))
V = builder.createBitcast(V, CIRFuncTy.getInput(FirstCIRArg));
CIRCallArgs[FirstCIRArg] = V;
break;
}
// FIXME: Avoid the conversion through memory if possible.
Address Src = Address::invalid();
if (!I->isAggregate()) {
llvm_unreachable("NYI");
} else {
Src = I->hasLValue() ? I->getKnownLValue().getAddress()
: I->getKnownRValue().getAggregateAddress();
}
// If the value is offset in memory, apply the offset now.
Src = emitAddressAtOffset(*this, Src, ArgInfo);
// Fast-isel and the optimizer generally like scalar values better than
// FCAs, so we flatten them if this is safe to do for this argument.
auto STy = dyn_cast<cir::StructType>(ArgInfo.getCoerceToType());
if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
auto SrcTy = Src.getElementType();
// FIXME(cir): get proper location for each argument.
auto argLoc = loc;
// If the source type is smaller than the destination type of the
// coerce-to logic, copy the source value into a temp alloca the size
// of the destination type to allow loading all of it. The bits past
// the source value are left undef.
// FIXME(cir): add data layout info and compare sizes instead of
// matching the types.
//
// uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
// uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
// if (SrcSize < DstSize) {
if (SrcTy != STy)
llvm_unreachable("NYI");
else {
// FIXME(cir): this currently only runs when the types are different,
// but should be when alloc sizes are different, fix this as soon as
// datalayout gets introduced.
Src = builder.createElementBitCast(argLoc, Src, STy);
}
// assert(NumCIRArgs == STy.getMembers().size());
// In LLVMGen: Still only pass the struct without any gaps but mark it
// as such somehow.
//
// In CIRGen: Emit a load from the "whole" struct,
// which shall be broken later by some lowering step into multiple
// loads.
assert(NumCIRArgs == 1 && "dont break up arguments here!");
CIRCallArgs[FirstCIRArg] = builder.createLoad(argLoc, Src);
} else {
llvm_unreachable("NYI");
}
break;
}
default:
assert(false && "Only Direct support so far");
}
}
const CIRGenCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this);
auto CalleePtr = ConcreteCallee.getFunctionPointer();
// If we're using inalloca, set up that argument.
assert(!ArgMemory.isValid() && "inalloca NYI");
// 2. Prepare the function pointer.
// TODO: simplifyVariadicCallee
// 3. Perform the actual call.
// TODO: Deactivate any cleanups that we're supposed to do immediately before
// the call.
// if (!CallArgs.getCleanupsToDeactivate().empty())
// deactivateArgCleanupsBeforeCall(*this, CallArgs);
// TODO: Update the largest vector width if any arguments have vector types.
// Compute the calling convention and attributes.
mlir::NamedAttrList Attrs;
StringRef FnName;
if (auto calleeFnOp = dyn_cast<cir::FuncOp>(CalleePtr))
FnName = calleeFnOp.getName();
cir::CallingConv callingConv;
CGM.constructAttributeList(FnName, CallInfo, Callee.getAbstractInfo(), Attrs,
callingConv,
/*AttrOnCallSite=*/true,
/*IsThunk=*/false);
// TODO: strictfp
// TODO: Add call-site nomerge, noinline, always_inline attribute if exists.
// Apply some call-site-specific attributes.
// TODO: work this into building the attribute set.
// Apply always_inline to all calls within flatten functions.
// FIXME: should this really take priority over __try, below?
// assert(!CurCodeDecl->hasAttr<FlattenAttr>() &&
// !TargetDecl->hasAttr<NoInlineAttr>() && "NYI");
// Disable inlining inside SEH __try blocks.
if (isSEHTryScope())
llvm_unreachable("NYI");
// Decide whether to use a call or an invoke.
bool CannotThrow;
if (currentFunctionUsesSEHTry()) {
// SEH cares about asynchronous exceptions, so everything can "throw."
CannotThrow = false;
} else if (isCleanupPadScope() &&
EHPersonality::get(*this).isMSVCXXPersonality()) {
// The MSVC++ personality will implicitly terminate the program if an
// exception is thrown during a cleanup outside of a try/catch.
// We don't need to model anything in IR to get this behavior.
CannotThrow = true;
} else {
// Otherwise, nounwind call sites will never throw.
auto noThrowAttr = cir::NoThrowAttr::get(&getMLIRContext());
CannotThrow = Attrs.getNamed(noThrowAttr.getMnemonic()).has_value();
if (auto fptr = dyn_cast<cir::FuncOp>(CalleePtr))
if (fptr.getExtraAttrs().getElements().contains(
noThrowAttr.getMnemonic()))
CannotThrow = true;
}
bool isInvoke = CannotThrow ? false : isInvokeDest();
// TODO: UnusedReturnSizePtr
if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
assert(!FD->hasAttr<StrictFPAttr>() && "NYI");
// TODO: alignment attributes
auto callLoc = loc;
cir::CIRCallOpInterface theCall = [&]() {
cir::FuncType indirectFuncTy;
mlir::Value indirectFuncVal;
cir::FuncOp directFuncOp;
if (auto fnOp = dyn_cast<cir::FuncOp>(CalleePtr)) {
directFuncOp = fnOp;
} else if (auto getGlobalOp = dyn_cast<cir::GetGlobalOp>(CalleePtr)) {
// FIXME(cir): This peephole optimization to avoids indirect calls for
// builtins. This should be fixed in the builting declaration instead by
// not emitting an unecessary get_global in the first place.
auto *globalOp = mlir::SymbolTable::lookupSymbolIn(CGM.getModule(),
getGlobalOp.getName());
assert(getGlobalOp && "undefined global function");
directFuncOp = llvm::dyn_cast<cir::FuncOp>(globalOp);
assert(directFuncOp && "operation is not a function");
} else {
[[maybe_unused]] auto resultTypes = CalleePtr->getResultTypes();
[[maybe_unused]] auto FuncPtrTy =
mlir::dyn_cast<cir::PointerType>(resultTypes.front());
assert(FuncPtrTy && mlir::isa<cir::FuncType>(FuncPtrTy.getPointee()) &&
"expected pointer to function");
indirectFuncTy = CIRFuncTy;
indirectFuncVal = CalleePtr->getResult(0);
}
auto extraFnAttrs = cir::ExtraFuncAttributesAttr::get(
&getMLIRContext(), Attrs.getDictionary(&getMLIRContext()));
cir::CIRCallOpInterface callLikeOp = emitCallLikeOp(
*this, callLoc, indirectFuncTy, indirectFuncVal, directFuncOp,
CIRCallArgs, isInvoke, callingConv, extraFnAttrs);
if (E)
callLikeOp->setAttr("ast",
cir::ASTCallExprAttr::get(&getMLIRContext(), *E));
if (callOrTryCall)
*callOrTryCall = callLikeOp;
return callLikeOp;
}();
if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
assert(!FD->getAttr<CFGuardAttr>() && "NYI");
// TODO: set attributes on callop
// assert(!theCall.getResults().getType().front().isSignlessInteger() &&
// "Vector NYI");
// TODO: LLVM models indirect calls via a null callee, how should we do this?
assert(!CGM.getLangOpts().ObjCAutoRefCount && "Not supported");
assert((!TargetDecl || !TargetDecl->hasAttr<NotTailCalledAttr>()) && "NYI");
assert(!getDebugInfo() && "No debug info yet");
assert((!TargetDecl || !TargetDecl->hasAttr<ErrorAttr>()) && "NYI");
// 4. Finish the call.
// If the call doesn't return, finish the basic block and clear the insertion
// point; this allows the rest of CIRGen to discard unreachable code.
// TODO: figure out how to support doesNotReturn
assert(!IsMustTail && "NYI");
// TODO: figure out writebacks? seems like ObjC only __autorelease
// TODO: cleanup argument memory at the end
// Extract the return value.
RValue ret = [&] {
switch (RetAI.getKind()) {
case cir::ABIArgInfo::Direct: {
mlir::Type RetCIRTy = convertType(RetTy);
if (RetAI.getCoerceToType() == RetCIRTy && RetAI.getDirectOffset() == 0) {
switch (getEvaluationKind(RetTy)) {
case cir::TEK_Aggregate: {
Address DestPtr = ReturnValue.getValue();
bool DestIsVolatile = ReturnValue.isVolatile();
if (!DestPtr.isValid()) {
DestPtr = CreateMemTemp(RetTy, callLoc, getCounterAggTmpAsString());
DestIsVolatile = false;
}
auto Results = theCall->getOpResults();
assert(Results.size() <= 1 && "multiple returns NYI");
SourceLocRAIIObject Loc{*this, callLoc};
emitAggregateStore(Results[0], DestPtr, DestIsVolatile);
return RValue::getAggregate(DestPtr);
}
case cir::TEK_Scalar: {
// If the argument doesn't match, perform a bitcast to coerce it. This
// can happen due to trivial type mismatches.
auto Results = theCall->getOpResults();
assert(Results.size() <= 1 && "multiple returns NYI");
assert(Results[0].getType() == RetCIRTy && "Bitcast support NYI");
return RValue::get(Results[0]);
}
default:
llvm_unreachable("NYI");
}
} else {
llvm_unreachable("No other forms implemented yet.");
}
}
case cir::ABIArgInfo::Ignore:
// If we are ignoring an argument that had a result, make sure to
// construct the appropriate return value for our caller.
return GetUndefRValue(RetTy);
default:
llvm_unreachable("NYI");
}
llvm_unreachable("NYI");
return RValue{};
}();
// TODO: implement assumed_aligned
// TODO: implement lifetime extensions
assert(RetTy.isDestructedType() != QualType::DK_nontrivial_c_struct && "NYI");
return ret;
}
mlir::Value CIRGenFunction::emitRuntimeCall(mlir::Location loc,
cir::FuncOp callee,
ArrayRef<mlir::Value> args) {
// TODO(cir): set the calling convention to this runtime call.
assert(!cir::MissingFeatures::setCallingConv());
auto call = builder.createCallOp(loc, callee, args);
assert(call->getNumResults() <= 1 &&
"runtime functions have at most 1 result");
if (call->getNumResults() == 0)
return nullptr;
return call->getResult(0);
}
void CIRGenFunction::emitCallArg(CallArgList &args, const Expr *E,
QualType type) {
// TODO: Add the DisableDebugLocationUpdates helper
assert(!dyn_cast<ObjCIndirectCopyRestoreExpr>(E) && "NYI");
assert(type->isReferenceType() == E->isGLValue() &&
"reference binding to unmaterialized r-value!");
if (E->isGLValue()) {
assert(E->getObjectKind() == OK_Ordinary);
return args.add(emitReferenceBindingToExpr(E), type);
}
bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
// In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
// However, we still have to push an EH-only cleanup in case we unwind before
// we make it to the call.
if (type->isRecordType() &&
type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
llvm_unreachable("Microsoft C++ ABI is NYI");
}
if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
LValue L = emitLValue(cast<CastExpr>(E)->getSubExpr());
assert(L.isSimple());
args.addUncopiedAggregate(L, type);
return;
}
args.add(emitAnyExprToTemp(E), type);
}
QualType CIRGenFunction::getVarArgType(const Expr *Arg) {
// System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
// implicitly widens null pointer constants that are arguments to varargs
// functions to pointer-sized ints.
if (!getTarget().getTriple().isOSWindows())
return Arg->getType();
if (Arg->getType()->isIntegerType() &&
getContext().getTypeSize(Arg->getType()) <
getContext().getTargetInfo().getPointerWidth(LangAS::Default) &&
Arg->isNullPointerConstant(getContext(),
Expr::NPC_ValueDependentIsNotNull)) {
return getContext().getIntPtrType();
}
return Arg->getType();
}
/// Similar to emitAnyExpr(), however, the result will always be accessible
/// even if no aggregate location is provided.
RValue CIRGenFunction::emitAnyExprToTemp(const Expr *E) {
AggValueSlot AggSlot = AggValueSlot::ignored();