Debian Codegraph @

flang/lib/Lower/CallInterface.cpp

raw
1 //===-- CallInterface.cpp -- Procedure call interface ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "flang/Lower/CallInterface.h"
10 #include "flang/Common/Fortran.h"
11 #include "flang/Evaluate/fold.h"
12 #include "flang/Lower/Bridge.h"
13 #include "flang/Lower/Mangler.h"
14 #include "flang/Lower/PFTBuilder.h"
15 #include "flang/Lower/StatementContext.h"
16 #include "flang/Lower/Support/Utils.h"
17 #include "flang/Optimizer/Builder/Character.h"
18 #include "flang/Optimizer/Builder/FIRBuilder.h"
19 #include "flang/Optimizer/Builder/Todo.h"
20 #include "flang/Optimizer/Dialect/FIRDialect.h"
21 #include "flang/Optimizer/Dialect/FIROpsSupport.h"
22 #include "flang/Optimizer/Support/InternalNames.h"
23 #include "flang/Optimizer/Support/Utils.h"
24 #include "flang/Semantics/symbol.h"
25 #include "flang/Semantics/tools.h"
26 #include <optional>
27
28 static mlir::FunctionType
29 getProcedureType(const Fortran::evaluate::characteristics::Procedure &proc,
30 Fortran::lower::AbstractConverter &converter);
31
32 mlir::Type Fortran::lower::getUntypedBoxProcType(mlir::MLIRContext *context) {
33 llvm::SmallVector<mlir::Type> resultTys;
34 llvm::SmallVector<mlir::Type> inputTys;
35 auto untypedFunc = mlir::FunctionType::get(context, inputTys, resultTys);
36 return fir::BoxProcType::get(context, untypedFunc);
37 }
38
39 /// Return the type of a dummy procedure given its characteristic (if it has
40 /// one).
41 static mlir::Type getProcedureDesignatorType(
42 const Fortran::evaluate::characteristics::Procedure *,
43 Fortran::lower::AbstractConverter &converter) {
44 // TODO: Get actual function type of the dummy procedure, at least when an
45 // interface is given. The result type should be available even if the arity
46 // and type of the arguments is not.
47 // In general, that is a nice to have but we cannot guarantee to find the
48 // function type that will match the one of the calls, we may not even know
49 // how many arguments the dummy procedure accepts (e.g. if a procedure
50 // pointer is only transiting through the current procedure without being
51 // called), so a function type cast must always be inserted.
52 return Fortran::lower::getUntypedBoxProcType(&converter.getMLIRContext());
53 }
54
55 //===----------------------------------------------------------------------===//
56 // Caller side interface implementation
57 //===----------------------------------------------------------------------===//
58
59 bool Fortran::lower::CallerInterface::hasAlternateReturns() const {
60 return procRef.hasAlternateReturns();
61 }
62
63 /// Return the binding label (from BIND(C...)) or the mangled name of the
64 /// symbol.
65 static std::string
66 getProcMangledName(const Fortran::evaluate::ProcedureDesignator &proc,
67 Fortran::lower::AbstractConverter &converter) {
68 if (const Fortran::semantics::Symbol *symbol = proc.GetSymbol())
69 return converter.mangleName(symbol->GetUltimate());
70 assert(proc.GetSpecificIntrinsic() &&
71 "expected intrinsic procedure in designator");
72 return proc.GetName();
73 }
74
75 std::string Fortran::lower::CallerInterface::getMangledName() const {
76 return getProcMangledName(procRef.proc(), converter);
77 }
78
79 const Fortran::semantics::Symbol *
80 Fortran::lower::CallerInterface::getProcedureSymbol() const {
81 return procRef.proc().GetSymbol();
82 }
83
84 bool Fortran::lower::CallerInterface::isIndirectCall() const {
85 if (const Fortran::semantics::Symbol *symbol = procRef.proc().GetSymbol())
86 return Fortran::semantics::IsPointer(*symbol) ||
87 Fortran::semantics::IsDummy(*symbol);
88 return false;
89 }
90
91 bool Fortran::lower::CallerInterface::requireDispatchCall() const {
92 // Procedure pointer component reference do not require dispatch, but
93 // have PASS/NOPASS argument.
94 if (const Fortran::semantics::Symbol *sym = procRef.proc().GetSymbol())
95 if (Fortran::semantics::IsPointer(*sym))
96 return false;
97 // calls with NOPASS attribute still have their component so check if it is
98 // polymorphic.
99 if (const Fortran::evaluate::Component *component =
100 procRef.proc().GetComponent()) {
101 if (Fortran::semantics::IsPolymorphic(component->base().GetLastSymbol()))
102 return true;
103 }
104 // calls with PASS attribute have the passed-object already set in its
105 // arguments. Just check if their is one.
106 std::optional<unsigned> passArg = getPassArgIndex();
107 if (passArg)
108 return true;
109 return false;
110 }
111
112 std::optional<unsigned>
113 Fortran::lower::CallerInterface::getPassArgIndex() const {
114 unsigned passArgIdx = 0;
115 std::optional<unsigned> passArg;
116 for (const auto &arg : getCallDescription().arguments()) {
117 if (arg && arg->isPassedObject()) {
118 passArg = passArgIdx;
119 break;
120 }
121 ++passArgIdx;
122 }
123 if (!passArg)
124 return passArg;
125 // Take into account result inserted as arguments.
126 if (std::optional<Fortran::lower::CallInterface<
127 Fortran::lower::CallerInterface>::PassedEntity>
128 resultArg = getPassedResult()) {
129 if (resultArg->passBy == PassEntityBy::AddressAndLength)
130 passArg = *passArg + 2;
131 else if (resultArg->passBy == PassEntityBy::BaseAddress)
132 passArg = *passArg + 1;
133 }
134 return passArg;
135 }
136
137 mlir::Value Fortran::lower::CallerInterface::getIfPassedArg() const {
138 if (std::optional<unsigned> passArg = getPassArgIndex()) {
139 assert(actualInputs.size() > *passArg && actualInputs[*passArg] &&
140 "passed arg was not set yet");
141 return actualInputs[*passArg];
142 }
143 return {};
144 }
145
146 const Fortran::evaluate::ProcedureDesignator *
147 Fortran::lower::CallerInterface::getIfIndirectCall() const {
148 if (const Fortran::semantics::Symbol *symbol = procRef.proc().GetSymbol())
149 if (Fortran::semantics::IsPointer(*symbol) ||
150 Fortran::semantics::IsDummy(*symbol))
151 return &procRef.proc();
152 return nullptr;
153 }
154
155 static mlir::Location
156 getProcedureDesignatorLoc(const Fortran::evaluate::ProcedureDesignator &proc,
157 Fortran::lower::AbstractConverter &converter) {
158 // Note: If the callee is defined in the same file but after the current
159 // unit we cannot get its location here and the funcOp is created at the
160 // wrong location (i.e, the caller location).
161 // To prevent this, it is up to the bridge to first declare all functions
162 // defined in the translation unit before lowering any calls or procedure
163 // designator references.
164 if (const Fortran::semantics::Symbol *symbol = proc.GetSymbol())
165 return converter.genLocation(symbol->name());
166 // Use current location for intrinsics.
167 return converter.getCurrentLocation();
168 }
169
170 mlir::Location Fortran::lower::CallerInterface::getCalleeLocation() const {
171 return getProcedureDesignatorLoc(procRef.proc(), converter);
172 }
173
174 // Get dummy argument characteristic for a procedure with implicit interface
175 // from the actual argument characteristic. The actual argument may not be a F77
176 // entity. The attribute must be dropped and the shape, if any, must be made
177 // explicit.
178 static Fortran::evaluate::characteristics::DummyDataObject
179 asImplicitArg(Fortran::evaluate::characteristics::DummyDataObject &&dummy) {
180 std::optional<Fortran::evaluate::Shape> shape =
181 dummy.type.attrs().none()
182 ? dummy.type.shape()
183 : std::make_optional<Fortran::evaluate::Shape>(dummy.type.Rank());
184 return Fortran::evaluate::characteristics::DummyDataObject(
185 Fortran::evaluate::characteristics::TypeAndShape(dummy.type.type(),
186 std::move(shape)));
187 }
188
189 static Fortran::evaluate::characteristics::DummyArgument
190 asImplicitArg(Fortran::evaluate::characteristics::DummyArgument &&dummy) {
191 return Fortran::common::visit(
192 Fortran::common::visitors{
193 [&](Fortran::evaluate::characteristics::DummyDataObject &obj) {
194 return Fortran::evaluate::characteristics::DummyArgument(
195 std::move(dummy.name), asImplicitArg(std::move(obj)));
196 },
197 [&](Fortran::evaluate::characteristics::DummyProcedure &proc) {
198 return Fortran::evaluate::characteristics::DummyArgument(
199 std::move(dummy.name), std::move(proc));
200 },
201 [](Fortran::evaluate::characteristics::AlternateReturn &x) {
202 return Fortran::evaluate::characteristics::DummyArgument(
203 std::move(x));
204 }},
205 dummy.u);
206 }
207
208 static bool isExternalDefinedInSameCompilationUnit(
209 const Fortran::evaluate::ProcedureDesignator &proc) {
210 if (const auto *symbol{proc.GetSymbol()})
211 return symbol->has<Fortran::semantics::SubprogramDetails>() &&
212 symbol->owner().IsGlobal();
213 return false;
214 }
215
216 Fortran::evaluate::characteristics::Procedure
217 Fortran::lower::CallerInterface::characterize() const {
218 Fortran::evaluate::FoldingContext &foldingContext =
219 converter.getFoldingContext();
220 std::optional<Fortran::evaluate::characteristics::Procedure> characteristic =
221 Fortran::evaluate::characteristics::Procedure::Characterize(
222 procRef.proc(), foldingContext, /*emitError=*/false);
223 assert(characteristic && "Failed to get characteristic from procRef");
224 // The characteristic may not contain the argument characteristic if the
225 // ProcedureDesignator has no interface, or may mismatch in case of implicit
226 // interface.
227 if (!characteristic->HasExplicitInterface() ||
228 (converter.getLoweringOptions().getLowerToHighLevelFIR() &&
229 isExternalDefinedInSameCompilationUnit(procRef.proc()) &&
230 characteristic->CanBeCalledViaImplicitInterface())) {
231 // In HLFIR lowering, calls to subprogram with implicit interfaces are
232 // always prepared according to the actual arguments. This is to support
233 // cases where the implicit interfaces are "abused" in old and not so old
234 // Fortran code (e.g, passing REAL(8) to CHARACTER(8), passing object
235 // pointers to procedure dummies, passing regular procedure dummies to
236 // character procedure dummies, omitted arguments....).
237 // In all those case, if the subprogram definition is in the same
238 // compilation unit, the "characteristic" from Characterize will be the one
239 // from the definition, in case of "abuses" (for which semantics raise a
240 // warning), lowering will be placed in a difficult position if it is given
241 // the dummy characteristic from the definition and an actual that has
242 // seemingly nothing to do with it: it would need to battle to anticipate
243 // and handle these mismatches (e.g., be able to prepare a fir.boxchar<>
244 // from a fir.real<> and so one). This was the approach of the lowering to
245 // FIR, and usually lead to compiler bug every time a new "abuse" was met in
246 // the wild.
247 // Instead, in HLFIR, the dummy characteristic is always computed from the
248 // actual for subprogram with implicit interfaces, and in case of call site
249 // vs fun.func MLIR function type signature mismatch, a function cast is
250 // done before placing the call. This is a hammer that should cover all
251 // cases and behave like existing compiler that "do not see" the definition
252 // when placing the call.
253 characteristic->dummyArguments.clear();
254 for (const std::optional<Fortran::evaluate::ActualArgument> &arg :
255 procRef.arguments()) {
256 // "arg" may be null if this is a call with missing arguments compared
257 // to the subprogram definition. Do not compute any characteristic
258 // in this case.
259 if (arg.has_value()) {
260 if (arg.value().isAlternateReturn()) {
261 characteristic->dummyArguments.emplace_back(
262 Fortran::evaluate::characteristics::AlternateReturn{});
263 } else {
264 // Argument cannot be optional with implicit interface
265 const Fortran::lower::SomeExpr *expr = arg.value().UnwrapExpr();
266 assert(expr && "argument in call with implicit interface cannot be "
267 "assumed type");
268 std::optional<Fortran::evaluate::characteristics::DummyArgument>
269 argCharacteristic =
270 Fortran::evaluate::characteristics::DummyArgument::FromActual(
271 "actual", *expr, foldingContext,
272 /*forImplicitInterface=*/true);
273 assert(argCharacteristic &&
274 "failed to characterize argument in implicit call");
275 characteristic->dummyArguments.emplace_back(
276 asImplicitArg(std::move(*argCharacteristic)));
277 }
278 }
279 }
280 }
281 return *characteristic;
282 }
283
284 void Fortran::lower::CallerInterface::placeInput(
285 const PassedEntity &passedEntity, mlir::Value arg) {
286 assert(static_cast<int>(actualInputs.size()) > passedEntity.firArgument &&
287 passedEntity.firArgument >= 0 &&
288 passedEntity.passBy != CallInterface::PassEntityBy::AddressAndLength &&
289 "bad arg position");
290 actualInputs[passedEntity.firArgument] = arg;
291 }
292
293 void Fortran::lower::CallerInterface::placeAddressAndLengthInput(
294 const PassedEntity &passedEntity, mlir::Value addr, mlir::Value len) {
295 assert(static_cast<int>(actualInputs.size()) > passedEntity.firArgument &&
296 static_cast<int>(actualInputs.size()) > passedEntity.firLength &&
297 passedEntity.firArgument >= 0 && passedEntity.firLength >= 0 &&
298 passedEntity.passBy == CallInterface::PassEntityBy::AddressAndLength &&
299 "bad arg position");
300 actualInputs[passedEntity.firArgument] = addr;
301 actualInputs[passedEntity.firLength] = len;
302 }
303
304 bool Fortran::lower::CallerInterface::verifyActualInputs() const {
305 if (getNumFIRArguments() != actualInputs.size())
306 return false;
307 for (mlir::Value arg : actualInputs) {
308 if (!arg)
309 return false;
310 }
311 return true;
312 }
313
314 mlir::Value
315 Fortran::lower::CallerInterface::getInput(const PassedEntity &passedEntity) {
316 return actualInputs[passedEntity.firArgument];
317 }
318
319 static void walkLengths(
320 const Fortran::evaluate::characteristics::TypeAndShape &typeAndShape,
321 const Fortran::lower::CallerInterface::ExprVisitor &visitor,
322 Fortran::lower::AbstractConverter &converter) {
323 Fortran::evaluate::DynamicType dynamicType = typeAndShape.type();
324 // Visit length specification expressions that are explicit.
325 if (dynamicType.category() == Fortran::common::TypeCategory::Character) {
326 if (std::optional<Fortran::evaluate::ExtentExpr> length =
327 dynamicType.GetCharLength())
328 visitor(toEvExpr(*length), /*assumedSize=*/false);
329 } else if (dynamicType.category() == Fortran::common::TypeCategory::Derived &&
330 !dynamicType.IsUnlimitedPolymorphic()) {
331 const Fortran::semantics::DerivedTypeSpec &derivedTypeSpec =
332 dynamicType.GetDerivedTypeSpec();
333 if (Fortran::semantics::CountLenParameters(derivedTypeSpec) > 0)
334 TODO(converter.getCurrentLocation(),
335 "function result with derived type length parameters");
336 }
337 }
338
339 void Fortran::lower::CallerInterface::walkResultLengths(
340 const ExprVisitor &visitor) const {
341 assert(characteristic && "characteristic was not computed");
342 const Fortran::evaluate::characteristics::FunctionResult &result =
343 characteristic->functionResult.value();
344 const Fortran::evaluate::characteristics::TypeAndShape *typeAndShape =
345 result.GetTypeAndShape();
346 assert(typeAndShape && "no result type");
347 return walkLengths(*typeAndShape, visitor, converter);
348 }
349
350 void Fortran::lower::CallerInterface::walkDummyArgumentLengths(
351 const PassedEntity &passedEntity, const ExprVisitor &visitor) const {
352 if (!passedEntity.characteristics)
353 return;
354 if (const auto *dummy =
355 std::get_if<Fortran::evaluate::characteristics::DummyDataObject>(
356 &passedEntity.characteristics->u))
357 walkLengths(dummy->type, visitor, converter);
358 }
359
360 // Compute extent expr from shapeSpec of an explicit shape.
361 static Fortran::evaluate::ExtentExpr
362 getExtentExpr(const Fortran::semantics::ShapeSpec &shapeSpec) {
363 if (shapeSpec.ubound().isStar())
364 // F'2023 18.5.3 point 5.
365 return Fortran::evaluate::ExtentExpr{-1};
366 const auto &ubound = shapeSpec.ubound().GetExplicit();
367 const auto &lbound = shapeSpec.lbound().GetExplicit();
368 assert(lbound && ubound && "shape must be explicit");
369 return Fortran::common::Clone(*ubound) - Fortran::common::Clone(*lbound) +
370 Fortran::evaluate::ExtentExpr{1};
371 }
372
373 static void
374 walkExtents(const Fortran::semantics::Symbol &symbol,
375 const Fortran::lower::CallerInterface::ExprVisitor &visitor) {
376 if (const auto *objectDetails =
377 symbol.detailsIf<Fortran::semantics::ObjectEntityDetails>())
378 if (objectDetails->shape().IsExplicitShape() ||
379 Fortran::semantics::IsAssumedSizeArray(symbol))
380 for (const Fortran::semantics::ShapeSpec &shapeSpec :
381 objectDetails->shape())
382 visitor(Fortran::evaluate::AsGenericExpr(getExtentExpr(shapeSpec)),
383 /*assumedSize=*/shapeSpec.ubound().isStar());
384 }
385
386 void Fortran::lower::CallerInterface::walkResultExtents(
387 const ExprVisitor &visitor) const {
388 // Walk directly the result symbol shape (the characteristic shape may contain
389 // descriptor inquiries to it that would fail to lower on the caller side).
390 const Fortran::semantics::SubprogramDetails *interfaceDetails =
391 getInterfaceDetails();
392 if (interfaceDetails) {
393 walkExtents(interfaceDetails->result(), visitor);
394 } else {
395 if (procRef.Rank() != 0)
396 fir::emitFatalError(
397 converter.getCurrentLocation(),
398 "only scalar functions may not have an interface symbol");
399 }
400 }
401
402 void Fortran::lower::CallerInterface::walkDummyArgumentExtents(
403 const PassedEntity &passedEntity, const ExprVisitor &visitor) const {
404 const Fortran::semantics::SubprogramDetails *interfaceDetails =
405 getInterfaceDetails();
406 if (!interfaceDetails)
407 return;
408 const Fortran::semantics::Symbol *dummy = getDummySymbol(passedEntity);
409 assert(dummy && "dummy symbol was not set");
410 walkExtents(*dummy, visitor);
411 }
412
413 bool Fortran::lower::CallerInterface::mustMapInterfaceSymbolsForResult() const {
414 assert(characteristic && "characteristic was not computed");
415 const std::optional<Fortran::evaluate::characteristics::FunctionResult>
416 &result = characteristic->functionResult;
417 if (!result || result->CanBeReturnedViaImplicitInterface() ||
418 !getInterfaceDetails() || result->IsProcedurePointer())
419 return false;
420 bool allResultSpecExprConstant = true;
421 auto visitor = [&](const Fortran::lower::SomeExpr &e, bool) {
422 allResultSpecExprConstant &= Fortran::evaluate::IsConstantExpr(e);
423 };
424 walkResultLengths(visitor);
425 walkResultExtents(visitor);
426 return !allResultSpecExprConstant;
427 }
428
429 bool Fortran::lower::CallerInterface::mustMapInterfaceSymbolsForDummyArgument(
430 const PassedEntity &arg) const {
431 bool allResultSpecExprConstant = true;
432 auto visitor = [&](const Fortran::lower::SomeExpr &e, bool) {
433 allResultSpecExprConstant &= Fortran::evaluate::IsConstantExpr(e);
434 };
435 walkDummyArgumentLengths(arg, visitor);
436 walkDummyArgumentExtents(arg, visitor);
437 return !allResultSpecExprConstant;
438 }
439
440 mlir::Value Fortran::lower::CallerInterface::getArgumentValue(
441 const semantics::Symbol &sym) const {
442 mlir::Location loc = converter.getCurrentLocation();
443 const Fortran::semantics::SubprogramDetails *ifaceDetails =
444 getInterfaceDetails();
445 if (!ifaceDetails)
446 fir::emitFatalError(
447 loc, "mapping actual and dummy arguments requires an interface");
448 const std::vector<Fortran::semantics::Symbol *> &dummies =
449 ifaceDetails->dummyArgs();
450 auto it = std::find(dummies.begin(), dummies.end(), &sym);
451 if (it == dummies.end())
452 fir::emitFatalError(loc, "symbol is not a dummy in this call");
453 FirValue mlirArgIndex = passedArguments[it - dummies.begin()].firArgument;
454 return actualInputs[mlirArgIndex];
455 }
456
457 const Fortran::semantics::Symbol *
458 Fortran::lower::CallerInterface::getDummySymbol(
459 const PassedEntity &passedEntity) const {
460 const Fortran::semantics::SubprogramDetails *ifaceDetails =
461 getInterfaceDetails();
462 if (!ifaceDetails)
463 return nullptr;
464 std::size_t argPosition = 0;
465 for (const auto &arg : getPassedArguments()) {
466 if (&arg == &passedEntity)
467 break;
468 ++argPosition;
469 }
470 if (argPosition >= ifaceDetails->dummyArgs().size())
471 return nullptr;
472 return ifaceDetails->dummyArgs()[argPosition];
473 }
474
475 mlir::Type Fortran::lower::CallerInterface::getResultStorageType() const {
476 if (passedResult)
477 return fir::dyn_cast_ptrEleTy(inputs[passedResult->firArgument].type);
478 assert(saveResult && !outputs.empty());
479 return outputs[0].type;
480 }
481
482 mlir::Type Fortran::lower::CallerInterface::getDummyArgumentType(
483 const PassedEntity &passedEntity) const {
484 return inputs[passedEntity.firArgument].type;
485 }
486
487 const Fortran::semantics::Symbol &
488 Fortran::lower::CallerInterface::getResultSymbol() const {
489 mlir::Location loc = converter.getCurrentLocation();
490 const Fortran::semantics::SubprogramDetails *ifaceDetails =
491 getInterfaceDetails();
492 if (!ifaceDetails)
493 fir::emitFatalError(
494 loc, "mapping actual and dummy arguments requires an interface");
495 return ifaceDetails->result();
496 }
497
498 const Fortran::semantics::SubprogramDetails *
499 Fortran::lower::CallerInterface::getInterfaceDetails() const {
500 if (const Fortran::semantics::Symbol *iface =
501 procRef.proc().GetInterfaceSymbol())
502 return iface->GetUltimate()
503 .detailsIf<Fortran::semantics::SubprogramDetails>();
504 return nullptr;
505 }
506
507 //===----------------------------------------------------------------------===//
508 // Callee side interface implementation
509 //===----------------------------------------------------------------------===//
510
511 bool Fortran::lower::CalleeInterface::hasAlternateReturns() const {
512 return !funit.isMainProgram() &&
513 Fortran::semantics::HasAlternateReturns(funit.getSubprogramSymbol());
514 }
515
516 std::string Fortran::lower::CalleeInterface::getMangledName() const {
517 if (funit.isMainProgram())
518 return fir::NameUniquer::doProgramEntry().str();
519 return converter.mangleName(funit.getSubprogramSymbol());
520 }
521
522 const Fortran::semantics::Symbol *
523 Fortran::lower::CalleeInterface::getProcedureSymbol() const {
524 if (funit.isMainProgram())
525 return funit.getMainProgramSymbol();
526 return &funit.getSubprogramSymbol();
527 }
528
529 mlir::Location Fortran::lower::CalleeInterface::getCalleeLocation() const {
530 // FIXME: do NOT use unknown for the anonymous PROGRAM case. We probably
531 // should just stash the location in the funit regardless.
532 return converter.genLocation(funit.getStartingSourceLoc());
533 }
534
535 Fortran::evaluate::characteristics::Procedure
536 Fortran::lower::CalleeInterface::characterize() const {
537 Fortran::evaluate::FoldingContext &foldingContext =
538 converter.getFoldingContext();
539 std::optional<Fortran::evaluate::characteristics::Procedure> characteristic =
540 Fortran::evaluate::characteristics::Procedure::Characterize(
541 funit.getSubprogramSymbol(), foldingContext);
542 assert(characteristic && "Fail to get characteristic from symbol");
543 return *characteristic;
544 }
545
546 bool Fortran::lower::CalleeInterface::isMainProgram() const {
547 return funit.isMainProgram();
548 }
549
550 mlir::func::FuncOp
551 Fortran::lower::CalleeInterface::addEntryBlockAndMapArguments() {
552 // Check for bugs in the front end. The front end must not present multiple
553 // definitions of the same procedure.
554 if (!func.getBlocks().empty())
555 fir::emitFatalError(func.getLoc(),
556 "cannot process subprogram that was already processed");
557
558 // On the callee side, directly map the mlir::value argument of the function
559 // block to the Fortran symbols.
560 func.addEntryBlock();
561 mapPassedEntities();
562 return func;
563 }
564
565 bool Fortran::lower::CalleeInterface::hasHostAssociated() const {
566 return funit.parentHasTupleHostAssoc();
567 }
568
569 mlir::Type Fortran::lower::CalleeInterface::getHostAssociatedTy() const {
570 assert(hasHostAssociated());
571 return funit.parentHostAssoc().getArgumentType(converter);
572 }
573
574 mlir::Value Fortran::lower::CalleeInterface::getHostAssociatedTuple() const {
575 assert(hasHostAssociated() || !funit.getHostAssoc().empty());
576 return converter.hostAssocTupleValue();
577 }
578
579 //===----------------------------------------------------------------------===//
580 // CallInterface implementation: this part is common to both caller and callee.
581 //===----------------------------------------------------------------------===//
582
583 static void addSymbolAttribute(mlir::func::FuncOp func,
584 const Fortran::semantics::Symbol &sym,
585 mlir::MLIRContext &mlirContext) {
586 const Fortran::semantics::Symbol &ultimate = sym.GetUltimate();
587 // The link between an internal procedure and its host procedure is lost
588 // in FIR if the host is BIND(C) since the internal mangling will not
589 // allow retrieving the host bind(C) name, and therefore func.func symbol.
590 // Preserve it as an attribute so that this can be later retrieved.
591 if (Fortran::semantics::ClassifyProcedure(ultimate) ==
592 Fortran::semantics::ProcedureDefinitionClass::Internal) {
593 if (ultimate.owner().kind() ==
594 Fortran::semantics::Scope::Kind::Subprogram) {
595 if (const Fortran::semantics::Symbol *hostProcedure =
596 ultimate.owner().symbol()) {
597 std::string hostName = Fortran::lower::mangle::mangleName(
598 *hostProcedure, /*keepExternalInScope=*/true);
599 func->setAttr(
600 fir::getHostSymbolAttrName(),
601 mlir::SymbolRefAttr::get(
602 &mlirContext, mlir::StringAttr::get(&mlirContext, hostName)));
603 }
604 } else if (ultimate.owner().kind() ==
605 Fortran::semantics::Scope::Kind::MainProgram) {
606 func->setAttr(fir::getHostSymbolAttrName(),
607 mlir::SymbolRefAttr::get(
608 &mlirContext,
609 mlir::StringAttr::get(
610 &mlirContext, fir::NameUniquer::doProgramEntry())));
611 }
612 }
613
614 // Set procedure attributes to the func op.
615 if (IsPureProcedure(sym))
616 func->setAttr(fir::getFuncPureAttrName(),
617 mlir::UnitAttr::get(&mlirContext));
618 if (IsElementalProcedure(sym))
619 func->setAttr(fir::getFuncElementalAttrName(),
620 mlir::UnitAttr::get(&mlirContext));
621 if (sym.attrs().test(Fortran::semantics::Attr::RECURSIVE))
622 func->setAttr(fir::getFuncRecursiveAttrName(),
623 mlir::UnitAttr::get(&mlirContext));
624
625 // Only add this on bind(C) functions for which the symbol is not reflected in
626 // the current context.
627 if (!Fortran::semantics::IsBindCProcedure(sym))
628 return;
629 std::string name =
630 Fortran::lower::mangle::mangleName(sym, /*keepExternalInScope=*/true);
631 func->setAttr(fir::getSymbolAttrName(),
632 mlir::StringAttr::get(&mlirContext, name));
633 }
634
635 static void
636 setCUDAAttributes(mlir::func::FuncOp func,
637 const Fortran::semantics::Symbol *sym,
638 std::optional<Fortran::evaluate::characteristics::Procedure>
639 characteristic) {
640 if (characteristic && characteristic->cudaSubprogramAttrs) {
641 func.getOperation()->setAttr(
642 cuf::getProcAttrName(),
643 cuf::getProcAttribute(func.getContext(),
644 *characteristic->cudaSubprogramAttrs));
645 }
646
647 if (sym) {
648 if (auto details =
649 sym->GetUltimate()
650 .detailsIf<Fortran::semantics::SubprogramDetails>()) {
651 mlir::Type i64Ty = mlir::IntegerType::get(func.getContext(), 64);
652 if (!details->cudaLaunchBounds().empty()) {
653 assert(details->cudaLaunchBounds().size() >= 2 &&
654 "expect at least 2 values");
655 auto maxTPBAttr =
656 mlir::IntegerAttr::get(i64Ty, details->cudaLaunchBounds()[0]);
657 auto minBPMAttr =
658 mlir::IntegerAttr::get(i64Ty, details->cudaLaunchBounds()[1]);
659 mlir::IntegerAttr ubAttr;
660 if (details->cudaLaunchBounds().size() > 2)
661 ubAttr =
662 mlir::IntegerAttr::get(i64Ty, details->cudaLaunchBounds()[2]);
663 func.getOperation()->setAttr(
664 cuf::getLaunchBoundsAttrName(),
665 cuf::LaunchBoundsAttr::get(func.getContext(), maxTPBAttr,
666 minBPMAttr, ubAttr));
667 }
668
669 if (!details->cudaClusterDims().empty()) {
670 assert(details->cudaClusterDims().size() == 3 && "expect 3 values");
671 auto xAttr =
672 mlir::IntegerAttr::get(i64Ty, details->cudaClusterDims()[0]);
673 auto yAttr =
674 mlir::IntegerAttr::get(i64Ty, details->cudaClusterDims()[1]);
675 auto zAttr =
676 mlir::IntegerAttr::get(i64Ty, details->cudaClusterDims()[2]);
677 func.getOperation()->setAttr(
678 cuf::getClusterDimsAttrName(),
679 cuf::ClusterDimsAttr::get(func.getContext(), xAttr, yAttr, zAttr));
680 }
681 }
682 }
683 }
684
685 /// Declare drives the different actions to be performed while analyzing the
686 /// signature and building/finding the mlir::func::FuncOp.
687 template <typename T>
688 void Fortran::lower::CallInterface<T>::declare() {
689 if (!side().isMainProgram()) {
690 characteristic.emplace(side().characterize());
691 bool isImplicit = characteristic->CanBeCalledViaImplicitInterface();
692 determineInterface(isImplicit, *characteristic);
693 }
694 // No input/output for main program
695
696 // Create / get funcOp for direct calls. For indirect calls (only meaningful
697 // on the caller side), no funcOp has to be created here. The mlir::Value
698 // holding the indirection is used when creating the fir::CallOp.
699 if (!side().isIndirectCall()) {
700 std::string name = side().getMangledName();
701 mlir::ModuleOp module = converter.getModuleOp();
702 mlir::SymbolTable *symbolTable = converter.getMLIRSymbolTable();
703 func = fir::FirOpBuilder::getNamedFunction(module, symbolTable, name);
704 if (!func) {
705 mlir::Location loc = side().getCalleeLocation();
706 mlir::FunctionType ty = genFunctionType();
707 func =
708 fir::FirOpBuilder::createFunction(loc, module, name, ty, symbolTable);
709 if (const Fortran::semantics::Symbol *sym = side().getProcedureSymbol()) {
710 if (side().isMainProgram()) {
711 func->setAttr(fir::getSymbolAttrName(),
712 mlir::StringAttr::get(&converter.getMLIRContext(),
713 sym->name().ToString()));
714 } else {
715 addSymbolAttribute(func, *sym, converter.getMLIRContext());
716 }
717 }
718 for (const auto &placeHolder : llvm::enumerate(inputs))
719 if (!placeHolder.value().attributes.empty())
720 func.setArgAttrs(placeHolder.index(), placeHolder.value().attributes);
721
722 setCUDAAttributes(func, side().getProcedureSymbol(), characteristic);
723 }
724 }
725 }
726
727 /// Once the signature has been analyzed and the mlir::func::FuncOp was
728 /// built/found, map the fir inputs to Fortran entities (the symbols or
729 /// expressions).
730 template <typename T>
731 void Fortran::lower::CallInterface<T>::mapPassedEntities() {
732 // map back fir inputs to passed entities
733 if constexpr (std::is_same_v<T, Fortran::lower::CalleeInterface>) {
734 assert(inputs.size() == func.front().getArguments().size() &&
735 "function previously created with different number of arguments");
736 for (auto [fst, snd] : llvm::zip(inputs, func.front().getArguments()))
737 mapBackInputToPassedEntity(fst, snd);
738 } else {
739 // On the caller side, map the index of the mlir argument position
740 // to Fortran ActualArguments.
741 int firPosition = 0;
742 for (const FirPlaceHolder &placeHolder : inputs)
743 mapBackInputToPassedEntity(placeHolder, firPosition++);
744 }
745 }
746
747 template <typename T>
748 void Fortran::lower::CallInterface<T>::mapBackInputToPassedEntity(
749 const FirPlaceHolder &placeHolder, FirValue firValue) {
750 PassedEntity &passedEntity =
751 placeHolder.passedEntityPosition == FirPlaceHolder::resultEntityPosition
752 ? passedResult.value()
753 : passedArguments[placeHolder.passedEntityPosition];
754 if (placeHolder.property == Property::CharLength)
755 passedEntity.firLength = firValue;
756 else
757 passedEntity.firArgument = firValue;
758 }
759
760 /// Helpers to access ActualArgument/Symbols
761 static const Fortran::evaluate::ActualArguments &
762 getEntityContainer(const Fortran::evaluate::ProcedureRef &proc) {
763 return proc.arguments();
764 }
765
766 static const std::vector<Fortran::semantics::Symbol *> &
767 getEntityContainer(Fortran::lower::pft::FunctionLikeUnit &funit) {
768 return funit.getSubprogramSymbol()
769 .get<Fortran::semantics::SubprogramDetails>()
770 .dummyArgs();
771 }
772
773 static const Fortran::evaluate::ActualArgument *getDataObjectEntity(
774 const std::optional<Fortran::evaluate::ActualArgument> &arg) {
775 if (arg)
776 return &*arg;
777 return nullptr;
778 }
779
780 static const Fortran::semantics::Symbol &
781 getDataObjectEntity(const Fortran::semantics::Symbol *arg) {
782 assert(arg && "expect symbol for data object entity");
783 return *arg;
784 }
785
786 static const Fortran::evaluate::ActualArgument *
787 getResultEntity(const Fortran::evaluate::ProcedureRef &) {
788 return nullptr;
789 }
790
791 static const Fortran::semantics::Symbol &
792 getResultEntity(Fortran::lower::pft::FunctionLikeUnit &funit) {
793 return funit.getSubprogramSymbol()
794 .get<Fortran::semantics::SubprogramDetails>()
795 .result();
796 }
797
798 /// Bypass helpers to manipulate entities since they are not any symbol/actual
799 /// argument to associate. See SignatureBuilder below.
800 using FakeEntity = bool;
801 using FakeEntities = llvm::SmallVector<FakeEntity>;
802 static FakeEntities
803 getEntityContainer(const Fortran::evaluate::characteristics::Procedure &proc) {
804 FakeEntities enities(proc.dummyArguments.size());
805 return enities;
806 }
807 static const FakeEntity &getDataObjectEntity(const FakeEntity &e) { return e; }
808 static FakeEntity
809 getResultEntity(const Fortran::evaluate::characteristics::Procedure &proc) {
810 return false;
811 }
812
813 /// This is the actual part that defines the FIR interface based on the
814 /// characteristic. It directly mutates the CallInterface members.
815 template <typename T>
816 class Fortran::lower::CallInterfaceImpl {
817 using CallInterface = Fortran::lower::CallInterface<T>;
818 using PassEntityBy = typename CallInterface::PassEntityBy;
819 using PassedEntity = typename CallInterface::PassedEntity;
820 using FirValue = typename CallInterface::FirValue;
821 using FortranEntity = typename CallInterface::FortranEntity;
822 using FirPlaceHolder = typename CallInterface::FirPlaceHolder;
823 using Property = typename CallInterface::Property;
824 using TypeAndShape = Fortran::evaluate::characteristics::TypeAndShape;
825 using DummyCharacteristics =
826 Fortran::evaluate::characteristics::DummyArgument;
827
828 public:
829 CallInterfaceImpl(CallInterface &i)
830 : interface(i), mlirContext{i.converter.getMLIRContext()} {}
831
832 void buildImplicitInterface(
833 const Fortran::evaluate::characteristics::Procedure &procedure) {
834 // Handle result
835 if (const std::optional<Fortran::evaluate::characteristics::FunctionResult>
836 &result = procedure.functionResult)
837 handleImplicitResult(*result, procedure.IsBindC());
838 else if (interface.side().hasAlternateReturns())
839 addFirResult(mlir::IndexType::get(&mlirContext),
840 FirPlaceHolder::resultEntityPosition, Property::Value);
841 // Handle arguments
842 const auto &argumentEntities =
843 getEntityContainer(interface.side().getCallDescription());
844 for (auto pair : llvm::zip(procedure.dummyArguments, argumentEntities)) {
845 const Fortran::evaluate::characteristics::DummyArgument
846 &argCharacteristics = std::get<0>(pair);
847 Fortran::common::visit(
848 Fortran::common::visitors{
849 [&](const auto &dummy) {
850 const auto &entity = getDataObjectEntity(std::get<1>(pair));
851 handleImplicitDummy(&argCharacteristics, dummy, entity);
852 },
853 [&](const Fortran::evaluate::characteristics::AlternateReturn &) {
854 // nothing to do
855 },
856 },
857 argCharacteristics.u);
858 }
859 }
860
861 void buildExplicitInterface(
862 const Fortran::evaluate::characteristics::Procedure &procedure) {
863 bool isBindC = procedure.IsBindC();
864 // Handle result
865 if (const std::optional<Fortran::evaluate::characteristics::FunctionResult>
866 &result = procedure.functionResult) {
867 if (result->CanBeReturnedViaImplicitInterface())
868 handleImplicitResult(*result, isBindC);
869 else
870 handleExplicitResult(*result);
871 } else if (interface.side().hasAlternateReturns()) {
872 addFirResult(mlir::IndexType::get(&mlirContext),
873 FirPlaceHolder::resultEntityPosition, Property::Value);
874 }
875 // Handle arguments
876 const auto &argumentEntities =
877 getEntityContainer(interface.side().getCallDescription());
878 for (auto pair : llvm::zip(procedure.dummyArguments, argumentEntities)) {
879 const Fortran::evaluate::characteristics::DummyArgument
880 &argCharacteristics = std::get<0>(pair);
881 Fortran::common::visit(
882 Fortran::common::visitors{
883 [&](const Fortran::evaluate::characteristics::DummyDataObject
884 &dummy) {
885 const auto &entity = getDataObjectEntity(std::get<1>(pair));
886 if (!isBindC && dummy.CanBePassedViaImplicitInterface())
887 handleImplicitDummy(&argCharacteristics, dummy, entity);
888 else
889 handleExplicitDummy(&argCharacteristics, dummy, entity,
890 isBindC);
891 },
892 [&](const Fortran::evaluate::characteristics::DummyProcedure
893 &dummy) {
894 const auto &entity = getDataObjectEntity(std::get<1>(pair));
895 handleImplicitDummy(&argCharacteristics, dummy, entity);
896 },
897 [&](const Fortran::evaluate::characteristics::AlternateReturn &) {
898 // nothing to do
899 },
900 },
901 argCharacteristics.u);
902 }
903 }
904
905 void appendHostAssocTupleArg(mlir::Type tupTy) {
906 mlir::MLIRContext *ctxt = tupTy.getContext();
907 addFirOperand(tupTy, nextPassedArgPosition(), Property::BaseAddress,
908 {mlir::NamedAttribute{
909 mlir::StringAttr::get(ctxt, fir::getHostAssocAttrName()),
910 mlir::UnitAttr::get(ctxt)}});
911 interface.passedArguments.emplace_back(
912 PassedEntity{PassEntityBy::BaseAddress, std::nullopt,
913 interface.side().getHostAssociatedTuple(), emptyValue()});
914 }
915
916 static std::optional<Fortran::evaluate::DynamicType> getResultDynamicType(
917 const Fortran::evaluate::characteristics::Procedure &procedure) {
918 if (const std::optional<Fortran::evaluate::characteristics::FunctionResult>
919 &result = procedure.functionResult)
920 if (const auto *resultTypeAndShape = result->GetTypeAndShape())
921 return resultTypeAndShape->type();
922 return std::nullopt;
923 }
924
925 static bool mustPassLengthWithDummyProcedure(
926 const Fortran::evaluate::characteristics::Procedure &procedure) {
927 // When passing a character function designator `bar` as dummy procedure to
928 // `foo` (e.g. `foo(bar)`), pass the result length of `bar` to `foo` so that
929 // `bar` can be called inside `foo` even if its length is assumed there.
930 // From an ABI perspective, the extra length argument must be handled
931 // exactly as if passing a character object. Using an argument of
932 // fir.boxchar type gives the expected behavior: after codegen, the
933 // fir.boxchar lengths are added after all the arguments as extra value
934 // arguments (the extra arguments order is the order of the fir.boxchar).
935
936 // This ABI is compatible with ifort, nag, nvfortran, and xlf, but not
937 // gfortran. Gfortran does not pass the length and is therefore unable to
938 // handle later call to `bar` in `foo` where the length would be assumed. If
939 // the result is an array, nag and ifort and xlf still pass the length, but
940 // not nvfortran (and gfortran). It is not clear it is possible to call an
941 // array function with assumed length (f18 forbides defining such
942 // interfaces). Hence, passing the length is most likely useless, but stick
943 // with ifort/nag/xlf interface here.
944 if (std::optional<Fortran::evaluate::DynamicType> type =
945 getResultDynamicType(procedure))
946 return type->category() == Fortran::common::TypeCategory::Character;
947 return false;
948 }
949
950 private:
951 void handleImplicitResult(
952 const Fortran::evaluate::characteristics::FunctionResult &result,
953 bool isBindC) {
954 if (auto proc{result.IsProcedurePointer()}) {
955 mlir::Type mlirType = fir::BoxProcType::get(
956 &mlirContext, getProcedureType(*proc, interface.converter));
957 addFirResult(mlirType, FirPlaceHolder::resultEntityPosition,
958 Property::Value);
959 return;
960 }
961 const Fortran::evaluate::characteristics::TypeAndShape *typeAndShape =
962 result.GetTypeAndShape();
963 assert(typeAndShape && "expect type for non proc pointer result");
964 Fortran::evaluate::DynamicType dynamicType = typeAndShape->type();
965 // Character result allocated by caller and passed as hidden arguments
966 if (dynamicType.category() == Fortran::common::TypeCategory::Character) {
967 if (isBindC) {
968 mlir::Type mlirType = translateDynamicType(dynamicType);
969 addFirResult(mlirType, FirPlaceHolder::resultEntityPosition,
970 Property::Value);
971 } else {
972 handleImplicitCharacterResult(dynamicType);
973 }
974 } else if (dynamicType.category() ==
975 Fortran::common::TypeCategory::Derived) {
976 if (!dynamicType.GetDerivedTypeSpec().IsVectorType()) {
977 // Derived result need to be allocated by the caller and the result
978 // value must be saved. Derived type in implicit interface cannot have
979 // length parameters.
980 setSaveResult();
981 }
982 mlir::Type mlirType = translateDynamicType(dynamicType);
983 addFirResult(mlirType, FirPlaceHolder::resultEntityPosition,
984 Property::Value);
985 } else {
986 // All result other than characters/derived are simply returned by value
987 // in implicit interfaces
988 mlir::Type mlirType =
989 getConverter().genType(dynamicType.category(), dynamicType.kind());
990 addFirResult(mlirType, FirPlaceHolder::resultEntityPosition,
991 Property::Value);
992 }
993 }
994 void
995 handleImplicitCharacterResult(const Fortran::evaluate::DynamicType &type) {
996 int resultPosition = FirPlaceHolder::resultEntityPosition;
997 setPassedResult(PassEntityBy::AddressAndLength,
998 getResultEntity(interface.side().getCallDescription()));
999 mlir::Type lenTy = mlir::IndexType::get(&mlirContext);
1000 std::optional<std::int64_t> constantLen = type.knownLength();
1001 fir::CharacterType::LenType len =
1002 constantLen ? *constantLen : fir::CharacterType::unknownLen();
1003 mlir::Type charRefTy = fir::ReferenceType::get(
1004 fir::CharacterType::get(&mlirContext, type.kind(), len));
1005 mlir::Type boxCharTy = fir::BoxCharType::get(&mlirContext, type.kind());
1006 addFirOperand(charRefTy, resultPosition, Property::CharAddress);
1007 addFirOperand(lenTy, resultPosition, Property::CharLength);
1008 /// For now, also return it by boxchar
1009 addFirResult(boxCharTy, resultPosition, Property::BoxChar);
1010 }
1011
1012 /// Return a vector with an attribute with the name of the argument if this
1013 /// is a callee interface and the name is available. Otherwise, just return
1014 /// an empty vector.
1015 llvm::SmallVector<mlir::NamedAttribute>
1016 dummyNameAttr(const FortranEntity &entity) {
1017 if constexpr (std::is_same_v<FortranEntity,
1018 std::optional<Fortran::common::Reference<
1019 const Fortran::semantics::Symbol>>>) {
1020 if (entity.has_value()) {
1021 const Fortran::semantics::Symbol *argument = &*entity.value();
1022 // "fir.bindc_name" is used for arguments for the sake of consistency
1023 // with other attributes carrying surface syntax names in FIR.
1024 return {mlir::NamedAttribute(
1025 mlir::StringAttr::get(&mlirContext, "fir.bindc_name"),
1026 mlir::StringAttr::get(&mlirContext,
1027 toStringRef(argument->name())))};
1028 }
1029 }
1030 return {};
1031 }
1032
1033 mlir::Type
1034 getRefType(Fortran::evaluate::DynamicType dynamicType,
1035 const Fortran::evaluate::characteristics::DummyDataObject &obj) {
1036 mlir::Type type = translateDynamicType(dynamicType);
1037 if (std::optional<fir::SequenceType::Shape> bounds = getBounds(obj.type))
1038 type = fir::SequenceType::get(*bounds, type);
1039 return fir::ReferenceType::get(type);
1040 }
1041
1042 void handleImplicitDummy(
1043 const DummyCharacteristics *characteristics,
1044 const Fortran::evaluate::characteristics::DummyDataObject &obj,
1045 const FortranEntity &entity) {
1046 Fortran::evaluate::DynamicType dynamicType = obj.type.type();
1047 if constexpr (std::is_same_v<FortranEntity,
1048 const Fortran::evaluate::ActualArgument *>) {
1049 if (entity) {
1050 if (entity->isPercentVal()) {
1051 mlir::Type type = translateDynamicType(dynamicType);
1052 addFirOperand(type, nextPassedArgPosition(), Property::Value,
1053 dummyNameAttr(entity));
1054 addPassedArg(PassEntityBy::Value, entity, characteristics);
1055 return;
1056 }
1057 if (entity->isPercentRef()) {
1058 mlir::Type refType = getRefType(dynamicType, obj);
1059 addFirOperand(refType, nextPassedArgPosition(), Property::BaseAddress,
1060 dummyNameAttr(entity));
1061 addPassedArg(PassEntityBy::BaseAddress, entity, characteristics);
1062 return;
1063 }
1064 }
1065 }
1066 if (dynamicType.category() == Fortran::common::TypeCategory::Character) {
1067 mlir::Type boxCharTy =
1068 fir::BoxCharType::get(&mlirContext, dynamicType.kind());
1069 addFirOperand(boxCharTy, nextPassedArgPosition(), Property::BoxChar,
1070 dummyNameAttr(entity));
1071 addPassedArg(PassEntityBy::BoxChar, entity, characteristics);
1072 } else {
1073 // non-PDT derived type allowed in implicit interface.
1074 mlir::Type refType = getRefType(dynamicType, obj);
1075 addFirOperand(refType, nextPassedArgPosition(), Property::BaseAddress,
1076 dummyNameAttr(entity));
1077 addPassedArg(PassEntityBy::BaseAddress, entity, characteristics);
1078 }
1079 }
1080
1081 mlir::Type
1082 translateDynamicType(const Fortran::evaluate::DynamicType &dynamicType) {
1083 Fortran::common::TypeCategory cat = dynamicType.category();
1084 // DERIVED
1085 if (cat == Fortran::common::TypeCategory::Derived) {
1086 if (dynamicType.IsUnlimitedPolymorphic())
1087 return mlir::NoneType::get(&mlirContext);
1088 return getConverter().genType(dynamicType.GetDerivedTypeSpec());
1089 }
1090 // CHARACTER with compile time constant length.
1091 if (cat == Fortran::common::TypeCategory::Character)
1092 if (std::optional<std::int64_t> constantLen =
1093 toInt64(dynamicType.GetCharLength()))
1094 return getConverter().genType(cat, dynamicType.kind(), {*constantLen});
1095 // INTEGER, REAL, LOGICAL, COMPLEX, and CHARACTER with dynamic length.
1096 return getConverter().genType(cat, dynamicType.kind());
1097 }
1098
1099 void handleExplicitDummy(
1100 const DummyCharacteristics *characteristics,
1101 const Fortran::evaluate::characteristics::DummyDataObject &obj,
1102 const FortranEntity &entity, bool isBindC) {
1103 using Attrs = Fortran::evaluate::characteristics::DummyDataObject::Attr;
1104
1105 bool isValueAttr = false;
1106 [[maybe_unused]] mlir::Location loc =
1107 interface.converter.getCurrentLocation();
1108 llvm::SmallVector<mlir::NamedAttribute> attrs = dummyNameAttr(entity);
1109 auto addMLIRAttr = [&](llvm::StringRef attr) {
1110 attrs.emplace_back(mlir::StringAttr::get(&mlirContext, attr),
1111 mlir::UnitAttr::get(&mlirContext));
1112 };
1113 if (obj.attrs.test(Attrs::Optional))
1114 addMLIRAttr(fir::getOptionalAttrName());
1115 // Skipping obj.attrs.test(Attrs::Asynchronous), this does not impact the
1116 // way the argument is passed given flang implement asynch IO synchronously.
1117 // TODO: it would be safer to treat them as volatile because since Fortran
1118 // 2018 asynchronous can also be used for C defined asynchronous user
1119 // processes (see 18.10.4 Asynchronous communication).
1120 if (obj.attrs.test(Attrs::Contiguous))
1121 addMLIRAttr(fir::getContiguousAttrName());
1122 if (obj.attrs.test(Attrs::Value))
1123 isValueAttr = true; // TODO: do we want an mlir::Attribute as well?
1124 if (obj.attrs.test(Attrs::Volatile))
1125 TODO(loc, "VOLATILE in procedure interface");
1126 if (obj.attrs.test(Attrs::Target))
1127 addMLIRAttr(fir::getTargetAttrName());
1128 if (obj.cudaDataAttr)
1129 attrs.emplace_back(
1130 mlir::StringAttr::get(&mlirContext, cuf::getDataAttrName()),
1131 cuf::getDataAttribute(&mlirContext, obj.cudaDataAttr));
1132
1133 // TODO: intents that require special care (e.g finalization)
1134
1135 using ShapeAttr = Fortran::evaluate::characteristics::TypeAndShape::Attr;
1136 const Fortran::evaluate::characteristics::TypeAndShape::Attrs &shapeAttrs =
1137 obj.type.attrs();
1138 if (shapeAttrs.test(ShapeAttr::Coarray))
1139 TODO(loc, "coarray: dummy argument coarray in procedure interface");
1140
1141 // So far assume that if the argument cannot be passed by implicit interface
1142 // it must be by box. That may no be always true (e.g for simple optionals)
1143
1144 Fortran::evaluate::DynamicType dynamicType = obj.type.type();
1145 mlir::Type type = translateDynamicType(dynamicType);
1146 if (std::optional<fir::SequenceType::Shape> bounds = getBounds(obj.type))
1147 type = fir::SequenceType::get(*bounds, type);
1148 if (obj.attrs.test(Attrs::Allocatable))
1149 type = fir::HeapType::get(type);
1150 if (obj.attrs.test(Attrs::Pointer))
1151 type = fir::PointerType::get(type);
1152 mlir::Type boxType = fir::wrapInClassOrBoxType(
1153 type, obj.type.type().IsPolymorphic(), obj.type.type().IsAssumedType());
1154
1155 if (obj.attrs.test(Attrs::Allocatable) || obj.attrs.test(Attrs::Pointer)) {
1156 // Pass as fir.ref<fir.box> or fir.ref<fir.class>
1157 mlir::Type boxRefType = fir::ReferenceType::get(boxType);
1158 addFirOperand(boxRefType, nextPassedArgPosition(), Property::MutableBox,
1159 attrs);
1160 addPassedArg(PassEntityBy::MutableBox, entity, characteristics);
1161 } else if (obj.IsPassedByDescriptor(isBindC)) {
1162 // Pass as fir.box or fir.class
1163 if (isValueAttr &&
1164 !getConverter().getLoweringOptions().getLowerToHighLevelFIR())
1165 TODO(loc, "assumed shape dummy argument with VALUE attribute");
1166 addFirOperand(boxType, nextPassedArgPosition(), Property::Box, attrs);
1167 addPassedArg(PassEntityBy::Box, entity, characteristics);
1168 } else if (dynamicType.category() ==
1169 Fortran::common::TypeCategory::Character) {
1170 if (isValueAttr && isBindC) {
1171 // Pass as fir.char<1>
1172 mlir::Type charTy =
1173 fir::CharacterType::getSingleton(&mlirContext, dynamicType.kind());
1174 addFirOperand(charTy, nextPassedArgPosition(), Property::Value, attrs);
1175 addPassedArg(PassEntityBy::Value, entity, characteristics);
1176 } else {
1177 // Pass as fir.box_char
1178 mlir::Type boxCharTy =
1179 fir::BoxCharType::get(&mlirContext, dynamicType.kind());
1180 addFirOperand(boxCharTy, nextPassedArgPosition(), Property::BoxChar,
1181 attrs);
1182 addPassedArg(isValueAttr ? PassEntityBy::CharBoxValueAttribute
1183 : PassEntityBy::BoxChar,
1184 entity, characteristics);
1185 }
1186 } else {
1187 // Pass as fir.ref unless it's by VALUE and BIND(C). Also pass-by-value
1188 // for numerical/logical scalar without OPTIONAL so that the behavior is
1189 // consistent with gfortran/nvfortran.
1190 // TODO: pass-by-value for derived type is not supported yet
1191 mlir::Type passType = fir::ReferenceType::get(type);
1192 PassEntityBy passBy = PassEntityBy::BaseAddress;
1193 Property prop = Property::BaseAddress;
1194 if (isValueAttr) {
1195 bool isBuiltinCptrType = fir::isa_builtin_cptr_type(type);
1196 if (isBindC || (!mlir::isa<fir::SequenceType>(type) &&
1197 !obj.attrs.test(Attrs::Optional) &&
1198 (dynamicType.category() !=
1199 Fortran::common::TypeCategory::Derived ||
1200 isBuiltinCptrType))) {
1201 passBy = PassEntityBy::Value;
1202 prop = Property::Value;
1203 if (isBuiltinCptrType) {
1204 auto recTy = mlir::dyn_cast<fir::RecordType>(type);
1205 mlir::Type fieldTy = recTy.getTypeList()[0].second;
1206 passType = fir::ReferenceType::get(fieldTy);
1207 } else {
1208 passType = type;
1209 }
1210 } else {
1211 passBy = PassEntityBy::BaseAddressValueAttribute;
1212 }
1213 }
1214 addFirOperand(passType, nextPassedArgPosition(), prop, attrs);
1215 addPassedArg(passBy, entity, characteristics);
1216 }
1217 }
1218
1219 void handleImplicitDummy(
1220 const DummyCharacteristics *characteristics,
1221 const Fortran::evaluate::characteristics::DummyProcedure &proc,
1222 const FortranEntity &entity) {
1223 if (!interface.converter.getLoweringOptions().getLowerToHighLevelFIR() &&
1224 proc.attrs.test(
1225 Fortran::evaluate::characteristics::DummyProcedure::Attr::Pointer))
1226 TODO(interface.converter.getCurrentLocation(),
1227 "procedure pointer arguments");
1228 const Fortran::evaluate::characteristics::Procedure &procedure =
1229 proc.procedure.value();
1230 mlir::Type funcType =
1231 getProcedureDesignatorType(&procedure, interface.converter);
1232 if (proc.attrs.test(Fortran::evaluate::characteristics::DummyProcedure::
1233 Attr::Pointer)) {
1234 // Prodecure pointer dummy argument.
1235 funcType = fir::ReferenceType::get(funcType);
1236 addFirOperand(funcType, nextPassedArgPosition(), Property::BoxProcRef);
1237 addPassedArg(PassEntityBy::BoxProcRef, entity, characteristics);
1238 return;
1239 }
1240 // Otherwise, it is a dummy procedure.
1241 std::optional<Fortran::evaluate::DynamicType> resultTy =
1242 getResultDynamicType(procedure);
1243 if (resultTy && mustPassLengthWithDummyProcedure(procedure)) {
1244 // The result length of dummy procedures that are character functions must
1245 // be passed so that the dummy procedure can be called if it has assumed
1246 // length on the callee side.
1247 mlir::Type tupleType =
1248 fir::factory::getCharacterProcedureTupleType(funcType);
1249 llvm::StringRef charProcAttr = fir::getCharacterProcedureDummyAttrName();
1250 addFirOperand(tupleType, nextPassedArgPosition(), Property::CharProcTuple,
1251 {mlir::NamedAttribute{
1252 mlir::StringAttr::get(&mlirContext, charProcAttr),
1253 mlir::UnitAttr::get(&mlirContext)}});
1254 addPassedArg(PassEntityBy::CharProcTuple, entity, characteristics);
1255 return;
1256 }
1257 addFirOperand(funcType, nextPassedArgPosition(), Property::BaseAddress);
1258 addPassedArg(PassEntityBy::BaseAddress, entity, characteristics);
1259 }
1260
1261 void handleExplicitResult(
1262 const Fortran::evaluate::characteristics::FunctionResult &result) {
1263 using Attr = Fortran::evaluate::characteristics::FunctionResult::Attr;
1264 mlir::Type mlirType;
1265 if (auto proc{result.IsProcedurePointer()}) {
1266 mlirType = fir::BoxProcType::get(
1267 &mlirContext, getProcedureType(*proc, interface.converter));
1268 addFirResult(mlirType, FirPlaceHolder::resultEntityPosition,
1269 Property::Value);
1270 return;
1271 }
1272 const Fortran::evaluate::characteristics::TypeAndShape *typeAndShape =
1273 result.GetTypeAndShape();
1274 assert(typeAndShape && "expect type for non proc pointer result");
1275 mlirType = translateDynamicType(typeAndShape->type());
1276 const auto *resTypeAndShape{result.GetTypeAndShape()};
1277 bool resIsPolymorphic =
1278 resTypeAndShape && resTypeAndShape->type().IsPolymorphic();
1279 bool resIsAssumedType =
1280 resTypeAndShape && resTypeAndShape->type().IsAssumedType();
1281 if (std::optional<fir::SequenceType::Shape> bounds =
1282 getBounds(*typeAndShape))
1283 mlirType = fir::SequenceType::get(*bounds, mlirType);
1284 if (result.attrs.test(Attr::Allocatable))
1285 mlirType = fir::wrapInClassOrBoxType(fir::HeapType::get(mlirType),
1286 resIsPolymorphic, resIsAssumedType);
1287 if (result.attrs.test(Attr::Pointer))
1288 mlirType = fir::wrapInClassOrBoxType(fir::PointerType::get(mlirType),
1289 resIsPolymorphic, resIsAssumedType);
1290
1291 if (fir::isa_char(mlirType)) {
1292 // Character scalar results must be passed as arguments in lowering so
1293 // that an assumed length character function callee can access the
1294 // result length. A function with a result requiring an explicit
1295 // interface does not have to be compatible with assumed length
1296 // function, but most compilers supports it.
1297 handleImplicitCharacterResult(typeAndShape->type());
1298 return;
1299 }
1300
1301 addFirResult(mlirType, FirPlaceHolder::resultEntityPosition,
1302 Property::Value);
1303 // Explicit results require the caller to allocate the storage and save the
1304 // function result in the storage with a fir.save_result.
1305 setSaveResult();
1306 }
1307
1308 // Return nullopt for scalars, empty vector for assumed rank, and a vector
1309 // with the shape (may contain unknown extents) for arrays.
1310 std::optional<fir::SequenceType::Shape> getBounds(
1311 const Fortran::evaluate::characteristics::TypeAndShape &typeAndShape) {
1312 if (typeAndShape.shape() && typeAndShape.shape()->empty())
1313 return std::nullopt;
1314 fir::SequenceType::Shape bounds;
1315 if (typeAndShape.shape())
1316 for (const std::optional<Fortran::evaluate::ExtentExpr> &extent :
1317 *typeAndShape.shape()) {
1318 fir::SequenceType::Extent bound = fir::SequenceType::getUnknownExtent();
1319 if (std::optional<std::int64_t> i = toInt64(extent))
1320 bound = *i;
1321 bounds.emplace_back(bound);
1322 }
1323 return bounds;
1324 }
1325 std::optional<std::int64_t>
1326 toInt64(std::optional<
1327 Fortran::evaluate::Expr<Fortran::evaluate::SubscriptInteger>>
1328 expr) {
1329 if (expr)
1330 return Fortran::evaluate::ToInt64(Fortran::evaluate::Fold(
1331 getConverter().getFoldingContext(), toEvExpr(*expr)));
1332 return std::nullopt;
1333 }
1334 void addFirOperand(
1335 mlir::Type type, int entityPosition, Property p,
1336 llvm::ArrayRef<mlir::NamedAttribute> attributes = std::nullopt) {
1337 interface.inputs.emplace_back(
1338 FirPlaceHolder{type, entityPosition, p, attributes});
1339 }
1340 void
1341 addFirResult(mlir::Type type, int entityPosition, Property p,
1342 llvm::ArrayRef<mlir::NamedAttribute> attributes = std::nullopt) {
1343 interface.outputs.emplace_back(
1344 FirPlaceHolder{type, entityPosition, p, attributes});
1345 }
1346 void addPassedArg(PassEntityBy p, FortranEntity entity,
1347 const DummyCharacteristics *characteristics) {
1348 interface.passedArguments.emplace_back(
1349 PassedEntity{p, entity, emptyValue(), emptyValue(), characteristics});
1350 }
1351 void setPassedResult(PassEntityBy p, FortranEntity entity) {
1352 interface.passedResult =
1353 PassedEntity{p, entity, emptyValue(), emptyValue()};
1354 }
1355 void setSaveResult() { interface.saveResult = true; }
1356 int nextPassedArgPosition() { return interface.passedArguments.size(); }
1357
1358 static FirValue emptyValue() {
1359 if constexpr (std::is_same_v<Fortran::lower::CalleeInterface, T>) {
1360 return {};
1361 } else {
1362 return -1;
1363 }
1364 }
1365
1366 Fortran::lower::AbstractConverter &getConverter() {
1367 return interface.converter;
1368 }
1369 CallInterface &interface;
1370 mlir::MLIRContext &mlirContext;
1371 };
1372
1373 template <typename T>
1374 bool Fortran::lower::CallInterface<T>::PassedEntity::isOptional() const {
1375 if (!characteristics)
1376 return false;
1377 return characteristics->IsOptional();
1378 }
1379 template <typename T>
1380 bool Fortran::lower::CallInterface<T>::PassedEntity::mayBeModifiedByCall()
1381 const {
1382 if (!characteristics)
1383 return true;
1384 if (characteristics->GetIntent() == Fortran::common::Intent::In)
1385 return false;
1386 return !hasValueAttribute();
1387 }
1388 template <typename T>
1389 bool Fortran::lower::CallInterface<T>::PassedEntity::mayBeReadByCall() const {
1390 if (!characteristics)
1391 return true;
1392 return characteristics->GetIntent() != Fortran::common::Intent::Out;
1393 }
1394
1395 template <typename T>
1396 bool Fortran::lower::CallInterface<T>::PassedEntity::testTKR(
1397 Fortran::common::IgnoreTKR flag) const {
1398 if (!characteristics)
1399 return false;
1400 const auto *dummy =
1401 std::get_if<Fortran::evaluate::characteristics::DummyDataObject>(
1402 &characteristics->u);
1403 if (!dummy)
1404 return false;
1405 return dummy->ignoreTKR.test(flag);
1406 }
1407
1408 template <typename T>
1409 bool Fortran::lower::CallInterface<T>::PassedEntity::isIntentOut() const {
1410 if (!characteristics)
1411 return true;
1412 return characteristics->GetIntent() == Fortran::common::Intent::Out;
1413 }
1414 template <typename T>
1415 bool Fortran::lower::CallInterface<T>::PassedEntity::mustBeMadeContiguous()
1416 const {
1417 if (!characteristics)
1418 return true;
1419 const auto *dummy =
1420 std::get_if<Fortran::evaluate::characteristics::DummyDataObject>(
1421 &characteristics->u);
1422 if (!dummy)
1423 return false;
1424 const auto &shapeAttrs = dummy->type.attrs();
1425 using ShapeAttrs = Fortran::evaluate::characteristics::TypeAndShape::Attr;
1426 if (shapeAttrs.test(ShapeAttrs::AssumedRank) ||
1427 shapeAttrs.test(ShapeAttrs::AssumedShape))
1428 return dummy->attrs.test(
1429 Fortran::evaluate::characteristics::DummyDataObject::Attr::Contiguous);
1430 if (shapeAttrs.test(ShapeAttrs::DeferredShape))
1431 return false;
1432 // Explicit shape arrays are contiguous.
1433 return dummy->type.Rank() > 0;
1434 }
1435
1436 template <typename T>
1437 bool Fortran::lower::CallInterface<T>::PassedEntity::hasValueAttribute() const {
1438 if (!characteristics)
1439 return false;
1440 const auto *dummy =
1441 std::get_if<Fortran::evaluate::characteristics::DummyDataObject>(
1442 &characteristics->u);
1443 return dummy &&
1444 dummy->attrs.test(
1445 Fortran::evaluate::characteristics::DummyDataObject::Attr::Value);
1446 }
1447
1448 template <typename T>
1449 bool Fortran::lower::CallInterface<T>::PassedEntity::hasAllocatableAttribute()
1450 const {
1451 if (!characteristics)
1452 return false;
1453 const auto *dummy =
1454 std::get_if<Fortran::evaluate::characteristics::DummyDataObject>(
1455 &characteristics->u);
1456 using Attrs = Fortran::evaluate::characteristics::DummyDataObject::Attr;
1457 return dummy && dummy->attrs.test(Attrs::Allocatable);
1458 }
1459
1460 template <typename T>
1461 bool Fortran::lower::CallInterface<
1462 T>::PassedEntity::mayRequireIntentoutFinalization() const {
1463 // Conservatively assume that the finalization is needed.
1464 if (!characteristics)
1465 return true;
1466
1467 // No INTENT(OUT) dummy arguments do not require finalization on entry.
1468 if (!isIntentOut())
1469 return false;
1470
1471 const auto *dummy =
1472 std::get_if<Fortran::evaluate::characteristics::DummyDataObject>(
1473 &characteristics->u);
1474 if (!dummy)
1475 return true;
1476
1477 // POINTER/ALLOCATABLE dummy arguments do not require finalization.
1478 using Attrs = Fortran::evaluate::characteristics::DummyDataObject::Attr;
1479 if (dummy->attrs.test(Attrs::Allocatable) ||
1480 dummy->attrs.test(Attrs::Pointer))
1481 return false;
1482
1483 // Polymorphic and unlimited polymorphic INTENT(OUT) dummy arguments
1484 // may need finalization.
1485 const Fortran::evaluate::DynamicType &type = dummy->type.type();
1486 if (type.IsPolymorphic() || type.IsUnlimitedPolymorphic())
1487 return true;
1488
1489 // INTENT(OUT) dummy arguments of derived types require finalization,
1490 // if their type has finalization.
1491 const Fortran::semantics::DerivedTypeSpec *derived =
1492 Fortran::evaluate::GetDerivedTypeSpec(type);
1493 if (!derived)
1494 return false;
1495
1496 return Fortran::semantics::IsFinalizable(*derived);
1497 }
1498
1499 template <typename T>
1500 bool Fortran::lower::CallInterface<
1501 T>::PassedEntity::isSequenceAssociatedDescriptor() const {
1502 if (!characteristics || passBy != PassEntityBy::Box)
1503 return false;
1504 const auto *dummy =
1505 std::get_if<Fortran::evaluate::characteristics::DummyDataObject>(
1506 &characteristics->u);
1507 return dummy && dummy->type.CanBeSequenceAssociated();
1508 }
1509
1510 template <typename T>
1511 void Fortran::lower::CallInterface<T>::determineInterface(
1512 bool isImplicit,
1513 const Fortran::evaluate::characteristics::Procedure &procedure) {
1514 CallInterfaceImpl<T> impl(*this);
1515 if (isImplicit)
1516 impl.buildImplicitInterface(procedure);
1517 else
1518 impl.buildExplicitInterface(procedure);
1519 // We only expect the extra host asspciations argument from the callee side as
1520 // the definition of internal procedures will be present, and we'll always
1521 // have a FuncOp definition in the ModuleOp, when lowering.
1522 if constexpr (std::is_same_v<T, Fortran::lower::CalleeInterface>) {
1523 if (side().hasHostAssociated())
1524 impl.appendHostAssocTupleArg(side().getHostAssociatedTy());
1525 }
1526 }
1527
1528 template <typename T>
1529 mlir::FunctionType Fortran::lower::CallInterface<T>::genFunctionType() {
1530 llvm::SmallVector<mlir::Type> returnTys;
1531 llvm::SmallVector<mlir::Type> inputTys;
1532 for (const FirPlaceHolder &placeHolder : outputs)
1533 returnTys.emplace_back(placeHolder.type);
1534 for (const FirPlaceHolder &placeHolder : inputs)
1535 inputTys.emplace_back(placeHolder.type);
1536 return mlir::FunctionType::get(&converter.getMLIRContext(), inputTys,
1537 returnTys);
1538 }
1539
1540 template <typename T>
1541 llvm::SmallVector<mlir::Type>
1542 Fortran::lower::CallInterface<T>::getResultType() const {
1543 llvm::SmallVector<mlir::Type> types;
1544 for (const FirPlaceHolder &out : outputs)
1545 types.emplace_back(out.type);
1546 return types;
1547 }
1548
1549 template class Fortran::lower::CallInterface<Fortran::lower::CalleeInterface>;
1550 template class Fortran::lower::CallInterface<Fortran::lower::CallerInterface>;
1551
1552 //===----------------------------------------------------------------------===//
1553 // Function Type Translation
1554 //===----------------------------------------------------------------------===//
1555
1556 /// Build signature from characteristics when there is no Fortran entity to
1557 /// associate with the arguments (i.e, this is not a call site or a procedure
1558 /// declaration. This is needed when dealing with function pointers/dummy
1559 /// arguments.
1560
1561 class SignatureBuilder;
1562 template <>
1563 struct Fortran::lower::PassedEntityTypes<SignatureBuilder> {
1564 using FortranEntity = FakeEntity;
1565 using FirValue = int;
1566 };
1567
1568 /// SignatureBuilder is a CRTP implementation of CallInterface intended to
1569 /// help translating characteristics::Procedure to mlir::FunctionType using
1570 /// the CallInterface translation.
1571 class SignatureBuilder
1572 : public Fortran::lower::CallInterface<SignatureBuilder> {
1573 public:
1574 SignatureBuilder(const Fortran::evaluate::characteristics::Procedure &p,
1575 Fortran::lower::AbstractConverter &c, bool forceImplicit)
1576 : CallInterface{c}, proc{p} {
1577 bool isImplicit = forceImplicit || proc.CanBeCalledViaImplicitInterface();
1578 determineInterface(isImplicit, proc);
1579 }
1580 SignatureBuilder(const Fortran::evaluate::ProcedureDesignator &procDes,
1581 Fortran::lower::AbstractConverter &c)
1582 : CallInterface{c}, procDesignator{&procDes},
1583 proc{Fortran::evaluate::characteristics::Procedure::Characterize(
1584 procDes, converter.getFoldingContext(), /*emitError=*/false)
1585 .value()} {}
1586 /// Does the procedure characteristics being translated have alternate
1587 /// returns ?
1588 bool hasAlternateReturns() const {
1589 for (const Fortran::evaluate::characteristics::DummyArgument &dummy :
1590 proc.dummyArguments)
1591 if (std::holds_alternative<
1592 Fortran::evaluate::characteristics::AlternateReturn>(dummy.u))
1593 return true;
1594 return false;
1595 };
1596
1597 /// This is only here to fulfill CRTP dependencies and should not be called.
1598 std::string getMangledName() const {
1599 if (procDesignator)
1600 return getProcMangledName(*procDesignator, converter);
1601 fir::emitFatalError(
1602 converter.getCurrentLocation(),
1603 "should not query name when only building function type");
1604 }
1605
1606 /// This is only here to fulfill CRTP dependencies and should not be called.
1607 mlir::Location getCalleeLocation() const {
1608 if (procDesignator)
1609 return getProcedureDesignatorLoc(*procDesignator, converter);
1610 return converter.getCurrentLocation();
1611 }
1612
1613 const Fortran::semantics::Symbol *getProcedureSymbol() const {
1614 if (procDesignator)
1615 return procDesignator->GetSymbol();
1616 return nullptr;
1617 };
1618
1619 Fortran::evaluate::characteristics::Procedure characterize() const {
1620 return proc;
1621 }
1622 /// SignatureBuilder cannot be used on main program.
1623 static constexpr bool isMainProgram() { return false; }
1624
1625 /// Return the characteristics::Procedure that is being translated to
1626 /// mlir::FunctionType.
1627 const Fortran::evaluate::characteristics::Procedure &
1628 getCallDescription() const {
1629 return proc;
1630 }
1631
1632 /// This is not the description of an indirect call.
1633 static constexpr bool isIndirectCall() { return false; }
1634
1635 /// Return the translated signature.
1636 mlir::FunctionType getFunctionType() {
1637 if (interfaceDetermined)
1638 fir::emitFatalError(converter.getCurrentLocation(),
1639 "SignatureBuilder should only be used once");
1640 // Most unrestricted intrinsic characteristics have the Elemental attribute
1641 // which triggers CanBeCalledViaImplicitInterface to return false. However,
1642 // using implicit interface rules is just fine here.
1643 bool forceImplicit =
1644 procDesignator && procDesignator->GetSpecificIntrinsic();
1645 bool isImplicit = forceImplicit || proc.CanBeCalledViaImplicitInterface();
1646 determineInterface(isImplicit, proc);
1647 interfaceDetermined = true;
1648 return genFunctionType();
1649 }
1650
1651 mlir::func::FuncOp getOrCreateFuncOp() {
1652 if (interfaceDetermined)
1653 fir::emitFatalError(converter.getCurrentLocation(),
1654 "SignatureBuilder should only be used once");
1655 declare();
1656 interfaceDetermined = true;
1657 return getFuncOp();
1658 }
1659
1660 // Copy of base implementation.
1661 static constexpr bool hasHostAssociated() { return false; }
1662 mlir::Type getHostAssociatedTy() const {
1663 llvm_unreachable("getting host associated type in SignatureBuilder");
1664 }
1665
1666 private:
1667 const Fortran::evaluate::ProcedureDesignator *procDesignator = nullptr;
1668 Fortran::evaluate::characteristics::Procedure proc;
1669 bool interfaceDetermined = false;
1670 };
1671
1672 mlir::FunctionType Fortran::lower::translateSignature(
1673 const Fortran::evaluate::ProcedureDesignator &proc,
1674 Fortran::lower::AbstractConverter &converter) {
1675 return SignatureBuilder{proc, converter}.getFunctionType();
1676 }
1677
1678 mlir::func::FuncOp Fortran::lower::getOrDeclareFunction(
1679 const Fortran::evaluate::ProcedureDesignator &proc,
1680 Fortran::lower::AbstractConverter &converter) {
1681 mlir::ModuleOp module = converter.getModuleOp();
1682 std::string name = getProcMangledName(proc, converter);
1683 mlir::func::FuncOp func = fir::FirOpBuilder::getNamedFunction(
1684 module, converter.getMLIRSymbolTable(), name);
1685 if (func)
1686 return func;
1687
1688 // getOrDeclareFunction is only used for functions not defined in the current
1689 // program unit, so use the location of the procedure designator symbol, which
1690 // is the first occurrence of the procedure in the program unit.
1691 return SignatureBuilder{proc, converter}.getOrCreateFuncOp();
1692 }
1693
1694 // Is it required to pass a dummy procedure with \p characteristics as a tuple
1695 // containing the function address and the result length ?
1696 static bool mustPassLengthWithDummyProcedure(
1697 const std::optional<Fortran::evaluate::characteristics::Procedure>
1698 &characteristics) {
1699 return characteristics &&
1700 Fortran::lower::CallInterfaceImpl<SignatureBuilder>::
1701 mustPassLengthWithDummyProcedure(*characteristics);
1702 }
1703
1704 bool Fortran::lower::mustPassLengthWithDummyProcedure(
1705 const Fortran::evaluate::ProcedureDesignator &procedure,
1706 Fortran::lower::AbstractConverter &converter) {
1707 std::optional<Fortran::evaluate::characteristics::Procedure> characteristics =
1708 Fortran::evaluate::characteristics::Procedure::Characterize(
1709 procedure, converter.getFoldingContext(), /*emitError=*/false);
1710 return ::mustPassLengthWithDummyProcedure(characteristics);
1711 }
1712
1713 mlir::Type Fortran::lower::getDummyProcedureType(
1714 const Fortran::semantics::Symbol &dummyProc,
1715 Fortran::lower::AbstractConverter &converter) {
1716 std::optional<Fortran::evaluate::characteristics::Procedure> iface =
1717 Fortran::evaluate::characteristics::Procedure::Characterize(
1718 dummyProc, converter.getFoldingContext());
1719 mlir::Type procType = getProcedureDesignatorType(
1720 iface.has_value() ? &*iface : nullptr, converter);
1721 if (::mustPassLengthWithDummyProcedure(iface))
1722 return fir::factory::getCharacterProcedureTupleType(procType);
1723 return procType;
1724 }
1725
1726 bool Fortran::lower::isCPtrArgByValueType(mlir::Type ty) {
1727 return mlir::isa<fir::ReferenceType>(ty) &&
1728 fir::isa_integer(fir::unwrapRefType(ty));
1729 }
1730
1731 // Return the mlir::FunctionType of a procedure
1732 static mlir::FunctionType
1733 getProcedureType(const Fortran::evaluate::characteristics::Procedure &proc,
1734 Fortran::lower::AbstractConverter &converter) {
1735 return SignatureBuilder{proc, converter, false}.genFunctionType();
1736 }