-
Notifications
You must be signed in to change notification settings - Fork 13.2k
/
Copy pathConvertCall.cpp
2892 lines (2706 loc) · 132 KB
/
ConvertCall.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
//===-- ConvertCall.cpp ---------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/
//
//===----------------------------------------------------------------------===//
#include "flang/Lower/ConvertCall.h"
#include "flang/Lower/Allocatable.h"
#include "flang/Lower/ConvertExprToHLFIR.h"
#include "flang/Lower/ConvertProcedureDesignator.h"
#include "flang/Lower/ConvertVariable.h"
#include "flang/Lower/CustomIntrinsicCall.h"
#include "flang/Lower/HlfirIntrinsics.h"
#include "flang/Lower/StatementContext.h"
#include "flang/Lower/SymbolMap.h"
#include "flang/Optimizer/Builder/BoxValue.h"
#include "flang/Optimizer/Builder/Character.h"
#include "flang/Optimizer/Builder/FIRBuilder.h"
#include "flang/Optimizer/Builder/HLFIRTools.h"
#include "flang/Optimizer/Builder/IntrinsicCall.h"
#include "flang/Optimizer/Builder/LowLevelIntrinsics.h"
#include "flang/Optimizer/Builder/MutableBox.h"
#include "flang/Optimizer/Builder/Runtime/Derived.h"
#include "flang/Optimizer/Builder/Todo.h"
#include "flang/Optimizer/Dialect/CUF/CUFOps.h"
#include "flang/Optimizer/Dialect/FIROpsSupport.h"
#include "flang/Optimizer/HLFIR/HLFIROps.h"
#include "mlir/IR/IRMapping.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include <optional>
#define DEBUG_TYPE "flang-lower-expr"
static llvm::cl::opt<bool> useHlfirIntrinsicOps(
"use-hlfir-intrinsic-ops", llvm::cl::init(true),
llvm::cl::desc("Lower via HLFIR transformational intrinsic operations such "
"as hlfir.sum"));
static constexpr char tempResultName[] = ".tmp.func_result";
/// Helper to package a Value and its properties into an ExtendedValue.
static fir::ExtendedValue toExtendedValue(mlir::Location loc, mlir::Value base,
llvm::ArrayRef<mlir::Value> extents,
llvm::ArrayRef<mlir::Value> lengths) {
mlir::Type type = base.getType();
if (mlir::isa<fir::BaseBoxType>(type))
return fir::BoxValue(base, /*lbounds=*/{}, lengths, extents);
type = fir::unwrapRefType(type);
if (mlir::isa<fir::BaseBoxType>(type))
return fir::MutableBoxValue(base, lengths, /*mutableProperties*/ {});
if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(type)) {
if (seqTy.getDimension() != extents.size())
fir::emitFatalError(loc, "incorrect number of extents for array");
if (mlir::isa<fir::CharacterType>(seqTy.getEleTy())) {
if (lengths.empty())
fir::emitFatalError(loc, "missing length for character");
assert(lengths.size() == 1);
return fir::CharArrayBoxValue(base, lengths[0], extents);
}
return fir::ArrayBoxValue(base, extents);
}
if (mlir::isa<fir::CharacterType>(type)) {
if (lengths.empty())
fir::emitFatalError(loc, "missing length for character");
assert(lengths.size() == 1);
return fir::CharBoxValue(base, lengths[0]);
}
return base;
}
/// Lower a type(C_PTR/C_FUNPTR) argument with VALUE attribute into a
/// reference. A C pointer can correspond to a Fortran dummy argument of type
/// C_PTR with the VALUE attribute. (see 18.3.6 note 3).
static mlir::Value genRecordCPtrValueArg(fir::FirOpBuilder &builder,
mlir::Location loc, mlir::Value rec,
mlir::Type ty) {
mlir::Value cAddr = fir::factory::genCPtrOrCFunptrAddr(builder, loc, rec, ty);
mlir::Value cVal = builder.create<fir::LoadOp>(loc, cAddr);
return builder.createConvert(loc, cAddr.getType(), cVal);
}
// Find the argument that corresponds to the host associations.
// Verify some assumptions about how the signature was built here.
[[maybe_unused]] static unsigned findHostAssocTuplePos(mlir::func::FuncOp fn) {
// Scan the argument list from last to first as the host associations are
// appended for now.
for (unsigned i = fn.getNumArguments(); i > 0; --i)
if (fn.getArgAttr(i - 1, fir::getHostAssocAttrName())) {
// Host assoc tuple must be last argument (for now).
assert(i == fn.getNumArguments() && "tuple must be last");
return i - 1;
}
llvm_unreachable("anyFuncArgsHaveAttr failed");
}
mlir::Value
Fortran::lower::argumentHostAssocs(Fortran::lower::AbstractConverter &converter,
mlir::Value arg) {
if (auto addr = mlir::dyn_cast_or_null<fir::AddrOfOp>(arg.getDefiningOp())) {
auto &builder = converter.getFirOpBuilder();
if (auto funcOp = builder.getNamedFunction(addr.getSymbol()))
if (fir::anyFuncArgsHaveAttr(funcOp, fir::getHostAssocAttrName()))
return converter.hostAssocTupleValue();
}
return {};
}
static bool mustCastFuncOpToCopeWithImplicitInterfaceMismatch(
mlir::Location loc, Fortran::lower::AbstractConverter &converter,
mlir::FunctionType callSiteType, mlir::FunctionType funcOpType) {
// Deal with argument number mismatch by making a function pointer so
// that function type cast can be inserted. Do not emit a warning here
// because this can happen in legal program if the function is not
// defined here and it was first passed as an argument without any more
// information.
if (callSiteType.getNumResults() != funcOpType.getNumResults() ||
callSiteType.getNumInputs() != funcOpType.getNumInputs())
return true;
// Implicit interface result type mismatch are not standard Fortran, but
// some compilers are not complaining about it. The front end is not
// protecting lowering from this currently. Support this with a
// discouraging warning.
// Cast the actual function to the current caller implicit type because
// that is the behavior we would get if we could not see the definition.
if (callSiteType.getResults() != funcOpType.getResults()) {
LLVM_DEBUG(mlir::emitWarning(
loc, "a return type mismatch is not standard compliant and may "
"lead to undefined behavior."));
return true;
}
// In HLFIR, there is little attempt to cope with implicit interface
// mismatch on the arguments. The argument are always prepared according
// to the implicit interface. Cast the actual function if any of the
// argument mismatch cannot be dealt with a simple fir.convert.
if (converter.getLoweringOptions().getLowerToHighLevelFIR())
for (auto [actualType, dummyType] :
llvm::zip(callSiteType.getInputs(), funcOpType.getInputs()))
if (actualType != dummyType &&
!fir::ConvertOp::canBeConverted(actualType, dummyType))
return true;
return false;
}
static mlir::Value readDim3Value(fir::FirOpBuilder &builder, mlir::Location loc,
mlir::Value dim3Addr, llvm::StringRef comp) {
mlir::Type i32Ty = builder.getI32Type();
mlir::Type refI32Ty = fir::ReferenceType::get(i32Ty);
llvm::SmallVector<mlir::Value> lenParams;
mlir::Value designate = builder.create<hlfir::DesignateOp>(
loc, refI32Ty, dim3Addr, /*component=*/comp,
/*componentShape=*/mlir::Value{}, hlfir::DesignateOp::Subscripts{},
/*substring=*/mlir::ValueRange{}, /*complexPartAttr=*/std::nullopt,
mlir::Value{}, lenParams);
return hlfir::loadTrivialScalar(loc, builder, hlfir::Entity{designate});
}
static mlir::Value remapActualToDummyDescriptor(
mlir::Location loc, Fortran::lower::AbstractConverter &converter,
Fortran::lower::SymMap &symMap,
const Fortran::lower::CallerInterface::PassedEntity &arg,
Fortran::lower::CallerInterface &caller, bool isBindcCall) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::IndexType idxTy = builder.getIndexType();
mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0);
Fortran::lower::StatementContext localStmtCtx;
auto lowerSpecExpr = [&](const auto &expr,
bool isAssumedSizeExtent) -> mlir::Value {
mlir::Value convertExpr = builder.createConvert(
loc, idxTy, fir::getBase(converter.genExprValue(expr, localStmtCtx)));
if (isAssumedSizeExtent)
return convertExpr;
return fir::factory::genMaxWithZero(builder, loc, convertExpr);
};
bool mapSymbols = caller.mustMapInterfaceSymbolsForDummyArgument(arg);
if (mapSymbols) {
symMap.pushScope();
const Fortran::semantics::Symbol *sym = caller.getDummySymbol(arg);
assert(sym && "call must have explicit interface to map interface symbols");
Fortran::lower::mapCallInterfaceSymbolsForDummyArgument(converter, caller,
symMap, *sym);
}
llvm::SmallVector<mlir::Value> extents;
llvm::SmallVector<mlir::Value> lengths;
mlir::Type dummyBoxType = caller.getDummyArgumentType(arg);
mlir::Type dummyBaseType = fir::unwrapPassByRefType(dummyBoxType);
if (mlir::isa<fir::SequenceType>(dummyBaseType))
caller.walkDummyArgumentExtents(
arg, [&](const Fortran::lower::SomeExpr &e, bool isAssumedSizeExtent) {
extents.emplace_back(lowerSpecExpr(e, isAssumedSizeExtent));
});
mlir::Value shape;
if (!extents.empty()) {
if (isBindcCall) {
// Preserve zero lower bounds (see F'2023 18.5.3).
llvm::SmallVector<mlir::Value> lowerBounds(extents.size(), zero);
shape = builder.genShape(loc, lowerBounds, extents);
} else {
shape = builder.genShape(loc, extents);
}
}
hlfir::Entity explicitArgument = hlfir::Entity{caller.getInput(arg)};
mlir::Type dummyElementType = fir::unwrapSequenceType(dummyBaseType);
if (auto recType = llvm::dyn_cast<fir::RecordType>(dummyElementType))
if (recType.getNumLenParams() > 0)
TODO(loc, "sequence association of length parameterized derived type "
"dummy arguments");
if (fir::isa_char(dummyElementType))
lengths.emplace_back(hlfir::genCharLength(loc, builder, explicitArgument));
mlir::Value baseAddr =
hlfir::genVariableRawAddress(loc, builder, explicitArgument);
baseAddr = builder.createConvert(loc, fir::ReferenceType::get(dummyBaseType),
baseAddr);
mlir::Value mold;
if (fir::isPolymorphicType(dummyBoxType))
mold = explicitArgument;
mlir::Value remapped =
builder.create<fir::EmboxOp>(loc, dummyBoxType, baseAddr, shape,
/*slice=*/mlir::Value{}, lengths, mold);
if (mapSymbols)
symMap.popScope();
return remapped;
}
/// Create a descriptor for sequenced associated descriptor that are passed
/// by descriptor. Sequence association (F'2023 15.5.2.12) implies that the
/// dummy shape and rank need to not be the same as the actual argument. This
/// helper creates a descriptor based on the dummy shape and rank (sequence
/// association can only happen with explicit and assumed-size array) so that it
/// is safe to assume the rank of the incoming descriptor inside the callee.
/// This helper must be called once all the actual arguments have been lowered
/// and placed inside "caller". Copy-in/copy-out must already have been
/// generated if needed using the actual argument shape (the dummy shape may be
/// assumed-size).
static void remapActualToDummyDescriptors(
mlir::Location loc, Fortran::lower::AbstractConverter &converter,
Fortran::lower::SymMap &symMap,
const Fortran::lower::PreparedActualArguments &loweredActuals,
Fortran::lower::CallerInterface &caller, bool isBindcCall) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
for (auto [preparedActual, arg] :
llvm::zip(loweredActuals, caller.getPassedArguments())) {
if (arg.isSequenceAssociatedDescriptor()) {
if (!preparedActual.value().handleDynamicOptional()) {
mlir::Value remapped = remapActualToDummyDescriptor(
loc, converter, symMap, arg, caller, isBindcCall);
caller.placeInput(arg, remapped);
} else {
// Absent optional actual argument descriptor cannot be read and
// remapped unconditionally.
mlir::Type dummyType = caller.getDummyArgumentType(arg);
mlir::Value isPresent = preparedActual.value().getIsPresent();
auto &argLambdaCapture = arg;
mlir::Value remapped =
builder
.genIfOp(loc, {dummyType}, isPresent,
/*withElseRegion=*/true)
.genThen([&]() {
mlir::Value newBox = remapActualToDummyDescriptor(
loc, converter, symMap, argLambdaCapture, caller,
isBindcCall);
builder.create<fir::ResultOp>(loc, newBox);
})
.genElse([&]() {
mlir::Value absent =
builder.create<fir::AbsentOp>(loc, dummyType);
builder.create<fir::ResultOp>(loc, absent);
})
.getResults()[0];
caller.placeInput(arg, remapped);
}
}
}
}
std::pair<Fortran::lower::LoweredResult, bool>
Fortran::lower::genCallOpAndResult(
mlir::Location loc, Fortran::lower::AbstractConverter &converter,
Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx,
Fortran::lower::CallerInterface &caller, mlir::FunctionType callSiteType,
std::optional<mlir::Type> resultType, bool isElemental) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
using PassBy = Fortran::lower::CallerInterface::PassEntityBy;
bool mustPopSymMap = false;
if (caller.mustMapInterfaceSymbolsForResult()) {
symMap.pushScope();
mustPopSymMap = true;
Fortran::lower::mapCallInterfaceSymbolsForResult(converter, caller, symMap);
}
// If this is an indirect call, retrieve the function address. Also retrieve
// the result length if this is a character function (note that this length
// will be used only if there is no explicit length in the local interface).
mlir::Value funcPointer;
mlir::Value charFuncPointerLength;
if (const Fortran::evaluate::ProcedureDesignator *procDesignator =
caller.getIfIndirectCall()) {
if (mlir::Value passedArg = caller.getIfPassedArg()) {
// Procedure pointer component call with PASS argument. To avoid
// "double" lowering of the ComponentRef, semantics only place the
// ComponentRef in the ActualArguments, not in the ProcedureDesignator (
// that is only the component symbol).
// Fetch the passed argument and addresses of its procedure pointer
// component.
funcPointer = Fortran::lower::derefPassProcPointerComponent(
loc, converter, *procDesignator, passedArg, symMap, stmtCtx);
} else {
Fortran::lower::SomeExpr expr{*procDesignator};
fir::ExtendedValue loweredProc =
converter.genExprAddr(loc, expr, stmtCtx);
funcPointer = fir::getBase(loweredProc);
// Dummy procedure may have assumed length, in which case the result
// length was passed along the dummy procedure.
// This is not possible with procedure pointer components.
if (const fir::CharBoxValue *charBox = loweredProc.getCharBox())
charFuncPointerLength = charBox->getLen();
}
}
const bool isExprCall =
converter.getLoweringOptions().getLowerToHighLevelFIR() &&
callSiteType.getNumResults() == 1 &&
llvm::isa<fir::SequenceType>(callSiteType.getResult(0));
mlir::IndexType idxTy = builder.getIndexType();
auto lowerSpecExpr = [&](const auto &expr) -> mlir::Value {
mlir::Value convertExpr = builder.createConvert(
loc, idxTy, fir::getBase(converter.genExprValue(expr, stmtCtx)));
return fir::factory::genMaxWithZero(builder, loc, convertExpr);
};
llvm::SmallVector<mlir::Value> resultLengths;
mlir::Value arrayResultShape;
hlfir::EvaluateInMemoryOp evaluateInMemory;
auto allocatedResult = [&]() -> std::optional<fir::ExtendedValue> {
llvm::SmallVector<mlir::Value> extents;
llvm::SmallVector<mlir::Value> lengths;
if (!caller.callerAllocateResult())
return {};
mlir::Type type = caller.getResultStorageType();
if (mlir::isa<fir::SequenceType>(type))
caller.walkResultExtents(
[&](const Fortran::lower::SomeExpr &e, bool isAssumedSizeExtent) {
assert(!isAssumedSizeExtent && "result cannot be assumed-size");
extents.emplace_back(lowerSpecExpr(e));
});
caller.walkResultLengths(
[&](const Fortran::lower::SomeExpr &e, bool isAssumedSizeExtent) {
assert(!isAssumedSizeExtent && "result cannot be assumed-size");
lengths.emplace_back(lowerSpecExpr(e));
});
// Result length parameters should not be provided to box storage
// allocation and save_results, but they are still useful information to
// keep in the ExtendedValue if non-deferred.
if (!mlir::isa<fir::BoxType>(type)) {
if (fir::isa_char(fir::unwrapSequenceType(type)) && lengths.empty()) {
// Calling an assumed length function. This is only possible if this
// is a call to a character dummy procedure.
if (!charFuncPointerLength)
fir::emitFatalError(loc, "failed to retrieve character function "
"length while calling it");
lengths.push_back(charFuncPointerLength);
}
resultLengths = lengths;
}
if (!extents.empty())
arrayResultShape = builder.genShape(loc, extents);
if (isExprCall) {
mlir::Type exprType = hlfir::getExprType(type);
evaluateInMemory = builder.create<hlfir::EvaluateInMemoryOp>(
loc, exprType, arrayResultShape, resultLengths);
builder.setInsertionPointToStart(&evaluateInMemory.getBody().front());
return toExtendedValue(loc, evaluateInMemory.getMemory(), extents,
lengths);
}
if ((!extents.empty() || !lengths.empty()) && !isElemental) {
// Note: in the elemental context, the alloca ownership inside the
// elemental region is implicit, and later pass in lowering (stack
// reclaim) fir.do_loop will be in charge of emitting any stack
// save/restore if needed.
auto *bldr = &converter.getFirOpBuilder();
mlir::Value sp = bldr->genStackSave(loc);
stmtCtx.attachCleanup(
[bldr, loc, sp]() { bldr->genStackRestore(loc, sp); });
}
mlir::Value temp =
builder.createTemporary(loc, type, ".result", extents, resultLengths);
return toExtendedValue(loc, temp, extents, lengths);
}();
if (mustPopSymMap)
symMap.popScope();
// Place allocated result
if (allocatedResult) {
if (std::optional<Fortran::lower::CallInterface<
Fortran::lower::CallerInterface>::PassedEntity>
resultArg = caller.getPassedResult()) {
if (resultArg->passBy == PassBy::AddressAndLength)
caller.placeAddressAndLengthInput(*resultArg,
fir::getBase(*allocatedResult),
fir::getLen(*allocatedResult));
else if (resultArg->passBy == PassBy::BaseAddress)
caller.placeInput(*resultArg, fir::getBase(*allocatedResult));
else
fir::emitFatalError(
loc, "only expect character scalar result to be passed by ref");
}
}
// In older Fortran, procedure argument types are inferred. This may lead
// different view of what the function signature is in different locations.
// Casts are inserted as needed below to accommodate this.
// The mlir::func::FuncOp type prevails, unless it has a different number of
// arguments which can happen in legal program if it was passed as a dummy
// procedure argument earlier with no further type information.
mlir::SymbolRefAttr funcSymbolAttr;
bool addHostAssociations = false;
if (!funcPointer) {
mlir::FunctionType funcOpType = caller.getFuncOp().getFunctionType();
mlir::SymbolRefAttr symbolAttr =
builder.getSymbolRefAttr(caller.getMangledName());
if (callSiteType.getNumResults() == funcOpType.getNumResults() &&
callSiteType.getNumInputs() + 1 == funcOpType.getNumInputs() &&
fir::anyFuncArgsHaveAttr(caller.getFuncOp(),
fir::getHostAssocAttrName())) {
// The number of arguments is off by one, and we're lowering a function
// with host associations. Modify call to include host associations
// argument by appending the value at the end of the operands.
assert(funcOpType.getInput(findHostAssocTuplePos(caller.getFuncOp())) ==
converter.hostAssocTupleValue().getType());
addHostAssociations = true;
}
// When this is not a call to an internal procedure (where there is a
// mismatch due to the extra argument, but the interface is otherwise
// explicit and safe), handle interface mismatch due to F77 implicit
// interface "abuse" with a function address cast if needed.
if (!addHostAssociations &&
mustCastFuncOpToCopeWithImplicitInterfaceMismatch(
loc, converter, callSiteType, funcOpType))
funcPointer = builder.create<fir::AddrOfOp>(loc, funcOpType, symbolAttr);
else
funcSymbolAttr = symbolAttr;
// Issue a warning if the procedure name conflicts with
// a runtime function name a call to which has been already
// lowered (implying that the FuncOp has been created).
// The behavior is undefined in this case.
if (caller.getFuncOp()->hasAttrOfType<mlir::UnitAttr>(
fir::FIROpsDialect::getFirRuntimeAttrName()))
LLVM_DEBUG(mlir::emitWarning(
loc,
llvm::Twine("function name '") +
llvm::Twine(symbolAttr.getLeafReference()) +
llvm::Twine("' conflicts with a runtime function name used by "
"Flang - this may lead to undefined behavior")));
}
mlir::FunctionType funcType =
funcPointer ? callSiteType : caller.getFuncOp().getFunctionType();
llvm::SmallVector<mlir::Value> operands;
// First operand of indirect call is the function pointer. Cast it to
// required function type for the call to handle procedures that have a
// compatible interface in Fortran, but that have different signatures in
// FIR.
if (funcPointer) {
operands.push_back(
mlir::isa<fir::BoxProcType>(funcPointer.getType())
? builder.create<fir::BoxAddrOp>(loc, funcType, funcPointer)
: builder.createConvert(loc, funcType, funcPointer));
}
// Deal with potential mismatches in arguments types. Passing an array to a
// scalar argument should for instance be tolerated here.
bool callingImplicitInterface = caller.canBeCalledViaImplicitInterface();
for (auto [fst, snd] : llvm::zip(caller.getInputs(), funcType.getInputs())) {
// When passing arguments to a procedure that can be called by implicit
// interface, allow any character actual arguments to be passed to dummy
// arguments of any type and vice versa.
mlir::Value cast;
auto *context = builder.getContext();
if (mlir::isa<fir::BoxProcType>(snd) &&
mlir::isa<mlir::FunctionType>(fst.getType())) {
auto funcTy =
mlir::FunctionType::get(context, std::nullopt, std::nullopt);
auto boxProcTy = builder.getBoxProcType(funcTy);
if (mlir::Value host = argumentHostAssocs(converter, fst)) {
cast = builder.create<fir::EmboxProcOp>(
loc, boxProcTy, llvm::ArrayRef<mlir::Value>{fst, host});
} else {
cast = builder.create<fir::EmboxProcOp>(loc, boxProcTy, fst);
}
} else {
mlir::Type fromTy = fir::unwrapRefType(fst.getType());
if (fir::isa_builtin_cptr_type(fromTy) &&
Fortran::lower::isCPtrArgByValueType(snd)) {
cast = genRecordCPtrValueArg(builder, loc, fst, fromTy);
} else if (fir::isa_derived(snd) && !fir::isa_derived(fst.getType())) {
// TODO: remove this TODO once the old lowering is gone.
TODO(loc, "derived type argument passed by value");
} else {
// With the lowering to HLFIR, box arguments have already been built
// according to the attributes, rank, bounds, and type they should have.
// Do not attempt any reboxing here that could break this.
bool legacyLowering =
!converter.getLoweringOptions().getLowerToHighLevelFIR();
cast = builder.convertWithSemantics(loc, snd, fst,
callingImplicitInterface,
/*allowRebox=*/legacyLowering);
}
}
operands.push_back(cast);
}
// Add host associations as necessary.
if (addHostAssociations)
operands.push_back(converter.hostAssocTupleValue());
mlir::Value callResult;
unsigned callNumResults;
fir::FortranProcedureFlagsEnumAttr procAttrs =
caller.getProcedureAttrs(builder.getContext());
if (!caller.getCallDescription().chevrons().empty()) {
// A call to a CUDA kernel with the chevron syntax.
mlir::Type i32Ty = builder.getI32Type();
mlir::Value one = builder.createIntegerConstant(loc, i32Ty, 1);
mlir::Value grid_x, grid_y, grid_z;
if (caller.getCallDescription().chevrons()[0].GetType()->category() ==
Fortran::common::TypeCategory::Integer) {
// If grid is an integer, it is converted to dim3(grid,1,1). Since z is
// not used for the number of thread blocks, it is omitted in the op.
grid_x = builder.createConvert(
loc, i32Ty,
fir::getBase(converter.genExprValue(
caller.getCallDescription().chevrons()[0], stmtCtx)));
grid_y = one;
grid_z = one;
} else {
auto dim3Addr = converter.genExprAddr(
caller.getCallDescription().chevrons()[0], stmtCtx);
grid_x = readDim3Value(builder, loc, fir::getBase(dim3Addr), "x");
grid_y = readDim3Value(builder, loc, fir::getBase(dim3Addr), "y");
grid_z = readDim3Value(builder, loc, fir::getBase(dim3Addr), "z");
}
mlir::Value block_x, block_y, block_z;
if (caller.getCallDescription().chevrons()[1].GetType()->category() ==
Fortran::common::TypeCategory::Integer) {
// If block is an integer, it is converted to dim3(block,1,1).
block_x = builder.createConvert(
loc, i32Ty,
fir::getBase(converter.genExprValue(
caller.getCallDescription().chevrons()[1], stmtCtx)));
block_y = one;
block_z = one;
} else {
auto dim3Addr = converter.genExprAddr(
caller.getCallDescription().chevrons()[1], stmtCtx);
block_x = readDim3Value(builder, loc, fir::getBase(dim3Addr), "x");
block_y = readDim3Value(builder, loc, fir::getBase(dim3Addr), "y");
block_z = readDim3Value(builder, loc, fir::getBase(dim3Addr), "z");
}
mlir::Value bytes; // bytes is optional.
if (caller.getCallDescription().chevrons().size() > 2)
bytes = builder.createConvert(
loc, i32Ty,
fir::getBase(converter.genExprValue(
caller.getCallDescription().chevrons()[2], stmtCtx)));
mlir::Value stream; // stream is optional.
if (caller.getCallDescription().chevrons().size() > 3)
stream = builder.createConvert(
loc, i32Ty,
fir::getBase(converter.genExprValue(
caller.getCallDescription().chevrons()[3], stmtCtx)));
builder.create<cuf::KernelLaunchOp>(
loc, funcType.getResults(), funcSymbolAttr, grid_x, grid_y, grid_z,
block_x, block_y, block_z, bytes, stream, operands,
/*arg_attrs=*/nullptr, /*res_attrs=*/nullptr);
callNumResults = 0;
} else if (caller.requireDispatchCall()) {
// Procedure call requiring a dynamic dispatch. Call is created with
// fir.dispatch.
// Get the raw procedure name. The procedure name is not mangled in the
// binding table, but there can be a suffix to distinguish bindings of
// the same name (which happens only when PRIVATE bindings exist in
// ancestor types in other modules).
const auto &ultimateSymbol =
caller.getCallDescription().proc().GetSymbol()->GetUltimate();
std::string procName = ultimateSymbol.name().ToString();
if (const auto &binding{
ultimateSymbol.get<Fortran::semantics::ProcBindingDetails>()};
binding.numPrivatesNotOverridden() > 0)
procName += "."s + std::to_string(binding.numPrivatesNotOverridden());
fir::DispatchOp dispatch;
if (std::optional<unsigned> passArg = caller.getPassArgIndex()) {
// PASS, PASS(arg-name)
// Note that caller.getInputs is used instead of operands to get the
// passed object because interface mismatch issues may have inserted a
// cast to the operand with a different declared type, which would break
// later type bound call resolution in the FIR to FIR pass.
dispatch = builder.create<fir::DispatchOp>(
loc, funcType.getResults(), builder.getStringAttr(procName),
caller.getInputs()[*passArg], operands,
builder.getI32IntegerAttr(*passArg), /*arg_attrs=*/nullptr,
/*res_attrs=*/nullptr, procAttrs);
} else {
// NOPASS
const Fortran::evaluate::Component *component =
caller.getCallDescription().proc().GetComponent();
assert(component && "expect component for type-bound procedure call.");
fir::ExtendedValue dataRefValue = Fortran::lower::convertDataRefToValue(
loc, converter, component->base(), symMap, stmtCtx);
mlir::Value passObject = fir::getBase(dataRefValue);
if (fir::isa_ref_type(passObject.getType()))
passObject = builder.create<fir::LoadOp>(loc, passObject);
dispatch = builder.create<fir::DispatchOp>(
loc, funcType.getResults(), builder.getStringAttr(procName),
passObject, operands, nullptr, /*arg_attrs=*/nullptr,
/*res_attrs=*/nullptr, procAttrs);
}
callNumResults = dispatch.getNumResults();
if (callNumResults != 0)
callResult = dispatch.getResult(0);
} else {
// Standard procedure call with fir.call.
auto call = builder.create<fir::CallOp>(
loc, funcType.getResults(), funcSymbolAttr, operands,
/*arg_attrs=*/nullptr, /*res_attrs=*/nullptr, procAttrs);
callNumResults = call.getNumResults();
if (callNumResults != 0)
callResult = call.getResult(0);
}
std::optional<Fortran::evaluate::DynamicType> retTy =
caller.getCallDescription().proc().GetType();
// With HLFIR lowering, isElemental must be set to true
// if we are producing an elemental call. In this case,
// the elemental results must not be destroyed, instead,
// the resulting array result will be finalized/destroyed
// as needed by hlfir.destroy.
const bool mustFinalizeResult =
!isElemental && callSiteType.getNumResults() > 0 &&
!fir::isPointerType(callSiteType.getResult(0)) && retTy.has_value() &&
(retTy->category() == Fortran::common::TypeCategory::Derived ||
retTy->IsPolymorphic() || retTy->IsUnlimitedPolymorphic());
if (caller.mustSaveResult()) {
assert(allocatedResult.has_value());
builder.create<fir::SaveResultOp>(loc, callResult,
fir::getBase(*allocatedResult),
arrayResultShape, resultLengths);
}
if (evaluateInMemory) {
builder.setInsertionPointAfter(evaluateInMemory);
mlir::Value expr = evaluateInMemory.getResult();
fir::FirOpBuilder *bldr = &converter.getFirOpBuilder();
if (!isElemental)
stmtCtx.attachCleanup([bldr, loc, expr, mustFinalizeResult]() {
bldr->create<hlfir::DestroyOp>(loc, expr,
/*finalize=*/mustFinalizeResult);
});
return {LoweredResult{hlfir::EntityWithAttributes{expr}},
mustFinalizeResult};
}
if (allocatedResult) {
// The result must be optionally destroyed (if it is of a derived type
// that may need finalization or deallocation of the components).
// For an allocatable result we have to free the memory allocated
// for the top-level entity. Note that the Destroy calls below
// do not deallocate the top-level entity. The two clean-ups
// must be pushed in reverse order, so that the final order is:
// Destroy(desc)
// free(desc->base_addr)
allocatedResult->match(
[&](const fir::MutableBoxValue &box) {
if (box.isAllocatable()) {
// 9.7.3.2 point 4. Deallocate allocatable results. Note that
// finalization was done independently by calling
// genDerivedTypeDestroy above and is not triggered by this inline
// deallocation.
fir::FirOpBuilder *bldr = &converter.getFirOpBuilder();
stmtCtx.attachCleanup([bldr, loc, box]() {
fir::factory::genFreememIfAllocated(*bldr, loc, box);
});
}
},
[](const auto &) {});
// 7.5.6.3 point 5. Derived-type finalization for nonpointer function.
bool resultIsFinalized = false;
// Check if the derived-type is finalizable if it is a monomorphic
// derived-type.
// For polymorphic and unlimited polymorphic enities call the runtime
// in any cases.
if (mustFinalizeResult) {
if (retTy->IsPolymorphic() || retTy->IsUnlimitedPolymorphic()) {
auto *bldr = &converter.getFirOpBuilder();
stmtCtx.attachCleanup([bldr, loc, allocatedResult]() {
fir::runtime::genDerivedTypeDestroy(*bldr, loc,
fir::getBase(*allocatedResult));
});
resultIsFinalized = true;
} else {
const Fortran::semantics::DerivedTypeSpec &typeSpec =
retTy->GetDerivedTypeSpec();
// If the result type may require finalization
// or have allocatable components, we need to make sure
// everything is properly finalized/deallocated.
if (Fortran::semantics::MayRequireFinalization(typeSpec) ||
// We can use DerivedTypeDestroy even if finalization is not needed.
hlfir::mayHaveAllocatableComponent(funcType.getResults()[0])) {
auto *bldr = &converter.getFirOpBuilder();
stmtCtx.attachCleanup([bldr, loc, allocatedResult]() {
mlir::Value box = bldr->createBox(loc, *allocatedResult);
fir::runtime::genDerivedTypeDestroy(*bldr, loc, box);
});
resultIsFinalized = true;
}
}
}
return {LoweredResult{*allocatedResult}, resultIsFinalized};
}
// subroutine call
if (!resultType)
return {LoweredResult{fir::ExtendedValue{mlir::Value{}}},
/*resultIsFinalized=*/false};
// For now, Fortran return values are implemented with a single MLIR
// function return value.
assert(callNumResults == 1 && "Expected exactly one result in FUNCTION call");
(void)callNumResults;
// Call a BIND(C) function that return a char.
if (caller.characterize().IsBindC() &&
mlir::isa<fir::CharacterType>(funcType.getResults()[0])) {
fir::CharacterType charTy =
mlir::dyn_cast<fir::CharacterType>(funcType.getResults()[0]);
mlir::Value len = builder.createIntegerConstant(
loc, builder.getCharacterLengthType(), charTy.getLen());
return {
LoweredResult{fir::ExtendedValue{fir::CharBoxValue{callResult, len}}},
/*resultIsFinalized=*/false};
}
return {LoweredResult{fir::ExtendedValue{callResult}},
/*resultIsFinalized=*/false};
}
static hlfir::EntityWithAttributes genStmtFunctionRef(
mlir::Location loc, Fortran::lower::AbstractConverter &converter,
Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx,
const Fortran::evaluate::ProcedureRef &procRef) {
const Fortran::semantics::Symbol *symbol = procRef.proc().GetSymbol();
assert(symbol && "expected symbol in ProcedureRef of statement functions");
const auto &details = symbol->get<Fortran::semantics::SubprogramDetails>();
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
// Statement functions have their own scope, we just need to associate
// the dummy symbols to argument expressions. There are no
// optional/alternate return arguments. Statement functions cannot be
// recursive (directly or indirectly) so it is safe to add dummy symbols to
// the local map here.
symMap.pushScope();
llvm::SmallVector<hlfir::AssociateOp> exprAssociations;
for (auto [arg, bind] : llvm::zip(details.dummyArgs(), procRef.arguments())) {
assert(arg && "alternate return in statement function");
assert(bind && "optional argument in statement function");
const auto *expr = bind->UnwrapExpr();
// TODO: assumed type in statement function, that surprisingly seems
// allowed, probably because nobody thought of restricting this usage.
// gfortran/ifort compiles this.
assert(expr && "assumed type used as statement function argument");
// As per Fortran 2018 C1580, statement function arguments can only be
// scalars.
// The only care is to use the dummy character explicit length if any
// instead of the actual argument length (that can be bigger).
hlfir::EntityWithAttributes loweredArg = Fortran::lower::convertExprToHLFIR(
loc, converter, *expr, symMap, stmtCtx);
fir::FortranVariableOpInterface variableIface = loweredArg.getIfVariable();
if (!variableIface) {
// So far only FortranVariableOpInterface can be mapped to symbols.
// Create an hlfir.associate to create a variable from a potential
// value argument.
mlir::Type argType = converter.genType(*arg);
auto associate = hlfir::genAssociateExpr(
loc, builder, loweredArg, argType, toStringRef(arg->name()));
exprAssociations.push_back(associate);
variableIface = associate;
}
const Fortran::semantics::DeclTypeSpec *type = arg->GetType();
if (type &&
type->category() == Fortran::semantics::DeclTypeSpec::Character) {
// Instantiate character as if it was a normal dummy argument so that the
// statement function dummy character length is applied and dealt with
// correctly.
symMap.addSymbol(*arg, variableIface.getBase());
Fortran::lower::mapSymbolAttributes(converter, *arg, symMap, stmtCtx);
} else {
// No need to create an extra hlfir.declare otherwise for
// numerical and logical scalar dummies.
symMap.addVariableDefinition(*arg, variableIface);
}
}
// Explicitly map statement function host associated symbols to their
// parent scope lowered symbol box.
for (const Fortran::semantics::SymbolRef &sym :
Fortran::evaluate::CollectSymbols(*details.stmtFunction()))
if (const auto *details =
sym->detailsIf<Fortran::semantics::HostAssocDetails>())
converter.copySymbolBinding(details->symbol(), sym);
hlfir::Entity result = Fortran::lower::convertExprToHLFIR(
loc, converter, details.stmtFunction().value(), symMap, stmtCtx);
symMap.popScope();
// The result must not be a variable.
result = hlfir::loadTrivialScalar(loc, builder, result);
if (result.isVariable())
result = hlfir::Entity{builder.create<hlfir::AsExprOp>(loc, result)};
for (auto associate : exprAssociations)
builder.create<hlfir::EndAssociateOp>(loc, associate);
return hlfir::EntityWithAttributes{result};
}
namespace {
// Structure to hold the information about the call and the lowering context.
// This structure is intended to help threading the information
// through the various lowering calls without having to pass every
// required structure one by one.
struct CallContext {
CallContext(const Fortran::evaluate::ProcedureRef &procRef,
std::optional<mlir::Type> resultType, mlir::Location loc,
Fortran::lower::AbstractConverter &converter,
Fortran::lower::SymMap &symMap,
Fortran::lower::StatementContext &stmtCtx)
: procRef{procRef}, converter{converter}, symMap{symMap},
stmtCtx{stmtCtx}, resultType{resultType}, loc{loc} {}
fir::FirOpBuilder &getBuilder() { return converter.getFirOpBuilder(); }
std::string getProcedureName() const {
if (const Fortran::semantics::Symbol *sym = procRef.proc().GetSymbol())
return sym->GetUltimate().name().ToString();
return procRef.proc().GetName();
}
/// Is this a call to an elemental procedure with at least one array argument?
bool isElementalProcWithArrayArgs() const {
if (procRef.IsElemental())
for (const std::optional<Fortran::evaluate::ActualArgument> &arg :
procRef.arguments())
if (arg && arg->Rank() != 0)
return true;
return false;
}
/// Is this a statement function reference?
bool isStatementFunctionCall() const {
if (const Fortran::semantics::Symbol *symbol = procRef.proc().GetSymbol())
if (const auto *details =
symbol->detailsIf<Fortran::semantics::SubprogramDetails>())
return details->stmtFunction().has_value();
return false;
}
/// Is this a call to a BIND(C) procedure?
bool isBindcCall() const {
if (const Fortran::semantics::Symbol *symbol = procRef.proc().GetSymbol())
return Fortran::semantics::IsBindCProcedure(*symbol);
return false;
}
const Fortran::evaluate::ProcedureRef &procRef;
Fortran::lower::AbstractConverter &converter;
Fortran::lower::SymMap &symMap;
Fortran::lower::StatementContext &stmtCtx;
std::optional<mlir::Type> resultType;
mlir::Location loc;
};
using ExvAndCleanup =
std::pair<fir::ExtendedValue, std::optional<hlfir::CleanupFunction>>;
} // namespace
// Helper to transform a fir::ExtendedValue to an hlfir::EntityWithAttributes.
static hlfir::EntityWithAttributes
extendedValueToHlfirEntity(mlir::Location loc, fir::FirOpBuilder &builder,
const fir::ExtendedValue &exv,
llvm::StringRef name) {
mlir::Value firBase = fir::getBase(exv);
mlir::Type firBaseTy = firBase.getType();
if (fir::isa_trivial(firBaseTy))
return hlfir::EntityWithAttributes{firBase};
if (auto charTy = mlir::dyn_cast<fir::CharacterType>(firBase.getType())) {
// CHAR() intrinsic and BIND(C) procedures returning CHARACTER(1)
// are lowered to a fir.char<kind,1> that is not in memory.
// This tends to cause a lot of bugs because the rest of the
// infrastructure is mostly tested with characters that are
// in memory.
// To avoid having to deal with this special case here and there,
// place it in memory here. If this turns out to be suboptimal,
// this could be fixed, but for now llvm opt -O1 is able to get
// rid of the memory indirection in a = char(b), so there is
// little incentive to increase the compiler complexity.
hlfir::Entity storage{builder.createTemporary(loc, charTy)};
builder.create<fir::StoreOp>(loc, firBase, storage);
auto asExpr = builder.create<hlfir::AsExprOp>(
loc, storage, /*mustFree=*/builder.createBool(loc, false));
return hlfir::EntityWithAttributes{asExpr.getResult()};
}
return hlfir::genDeclare(loc, builder, exv, name,
fir::FortranVariableFlagsAttr{});
}
namespace {
/// Structure to hold the clean-up related to a dummy argument preparation
/// that may have to be done after a call (copy-out or temporary deallocation).
struct CallCleanUp {
struct CopyIn {
void genCleanUp(mlir::Location loc, fir::FirOpBuilder &builder) {
builder.create<hlfir::CopyOutOp>(loc, tempBox, wasCopied, copyBackVar);
}
// address of the descriptor holding the temp if a temp was created.
mlir::Value tempBox;
// Boolean indicating if a copy was made or not.
mlir::Value wasCopied;
// copyBackVar may be null if copy back is not needed.
mlir::Value copyBackVar;
};
struct ExprAssociate {
void genCleanUp(mlir::Location loc, fir::FirOpBuilder &builder) {
builder.create<hlfir::EndAssociateOp>(loc, tempVar, mustFree);
}
mlir::Value tempVar;
mlir::Value mustFree;
};
void genCleanUp(mlir::Location loc, fir::FirOpBuilder &builder) {
Fortran::common::visit([&](auto &c) { c.genCleanUp(loc, builder); },
cleanUp);
}
std::variant<CopyIn, ExprAssociate> cleanUp;
};
/// Structure representing a prepared dummy argument.
/// It holds the value to be passed in the call and any related
/// clean-ups to be done after the call.
struct PreparedDummyArgument {
void pushCopyInCleanUp(mlir::Value tempBox, mlir::Value wasCopied,
mlir::Value copyBackVar) {
cleanups.emplace_back(
CallCleanUp{CallCleanUp::CopyIn{tempBox, wasCopied, copyBackVar}});
}
void pushExprAssociateCleanUp(mlir::Value tempVar, mlir::Value wasCopied) {
cleanups.emplace_back(
CallCleanUp{CallCleanUp::ExprAssociate{tempVar, wasCopied}});
}
void pushExprAssociateCleanUp(hlfir::AssociateOp associate) {
mlir::Value hlfirBase = associate.getBase();
mlir::Value firBase = associate.getFirBase();
cleanups.emplace_back(CallCleanUp{CallCleanUp::ExprAssociate{
hlfir::mayHaveAllocatableComponent(hlfirBase.getType()) ? hlfirBase
: firBase,
associate.getMustFreeStrorageFlag()}});
}
mlir::Value dummy;
// NOTE: the clean-ups are executed in reverse order.
llvm::SmallVector<CallCleanUp, 2> cleanups;
};
/// Structure to help conditionally preparing a dummy argument based
/// on the actual argument presence.
/// It helps "wrapping" the dummy and the clean-up information in
/// an if (present) {...}: