Debian Codegraph @

flang/lib/Lower/ConvertVariable.cpp

raw
1 //===-- ConvertVariable.cpp -- bridge to lower to MLIR --------------------===//
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 // Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "flang/Lower/ConvertVariable.h"
14 #include "flang/Lower/AbstractConverter.h"
15 #include "flang/Lower/Allocatable.h"
16 #include "flang/Lower/BoxAnalyzer.h"
17 #include "flang/Lower/CallInterface.h"
18 #include "flang/Lower/ConvertConstant.h"
19 #include "flang/Lower/ConvertExpr.h"
20 #include "flang/Lower/ConvertExprToHLFIR.h"
21 #include "flang/Lower/ConvertProcedureDesignator.h"
22 #include "flang/Lower/Mangler.h"
23 #include "flang/Lower/PFTBuilder.h"
24 #include "flang/Lower/StatementContext.h"
25 #include "flang/Lower/Support/Utils.h"
26 #include "flang/Lower/SymbolMap.h"
27 #include "flang/Optimizer/Builder/Character.h"
28 #include "flang/Optimizer/Builder/FIRBuilder.h"
29 #include "flang/Optimizer/Builder/HLFIRTools.h"
30 #include "flang/Optimizer/Builder/IntrinsicCall.h"
31 #include "flang/Optimizer/Builder/Runtime/Derived.h"
32 #include "flang/Optimizer/Builder/Todo.h"
33 #include "flang/Optimizer/Dialect/CUF/CUFOps.h"
34 #include "flang/Optimizer/Dialect/FIRAttr.h"
35 #include "flang/Optimizer/Dialect/FIRDialect.h"
36 #include "flang/Optimizer/Dialect/FIROps.h"
37 #include "flang/Optimizer/Dialect/Support/FIRContext.h"
38 #include "flang/Optimizer/HLFIR/HLFIROps.h"
39 #include "flang/Optimizer/Support/FatalError.h"
40 #include "flang/Optimizer/Support/InternalNames.h"
41 #include "flang/Optimizer/Support/Utils.h"
42 #include "flang/Semantics/runtime-type-info.h"
43 #include "flang/Semantics/tools.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include <optional>
47
48 static llvm::cl::opt<bool> allowAssumedRank(
49 "allow-assumed-rank",
50 llvm::cl::desc("Enable assumed rank lowering - experimental"),
51 llvm::cl::init(false));
52
53 #define DEBUG_TYPE "flang-lower-variable"
54
55 /// Helper to lower a scalar expression using a specific symbol mapping.
56 static mlir::Value genScalarValue(Fortran::lower::AbstractConverter &converter,
57 mlir::Location loc,
58 const Fortran::lower::SomeExpr &expr,
59 Fortran::lower::SymMap &symMap,
60 Fortran::lower::StatementContext &context) {
61 // This does not use the AbstractConverter member function to override the
62 // symbol mapping to be used expression lowering.
63 if (converter.getLoweringOptions().getLowerToHighLevelFIR()) {
64 hlfir::EntityWithAttributes loweredExpr =
65 Fortran::lower::convertExprToHLFIR(loc, converter, expr, symMap,
66 context);
67 return hlfir::loadTrivialScalar(loc, converter.getFirOpBuilder(),
68 loweredExpr);
69 }
70 return fir::getBase(Fortran::lower::createSomeExtendedExpression(
71 loc, converter, expr, symMap, context));
72 }
73
74 /// Does this variable have a default initialization?
75 bool Fortran::lower::hasDefaultInitialization(
76 const Fortran::semantics::Symbol &sym) {
77 if (sym.has<Fortran::semantics::ObjectEntityDetails>() && sym.size())
78 if (!Fortran::semantics::IsAllocatableOrPointer(sym))
79 if (const Fortran::semantics::DeclTypeSpec *declTypeSpec = sym.GetType())
80 if (const Fortran::semantics::DerivedTypeSpec *derivedTypeSpec =
81 declTypeSpec->AsDerived()) {
82 // Pointer assignments in the runtime may hit undefined behaviors if
83 // the RHS contains garbage. Pointer objects are always established by
84 // lowering to NULL() (in Fortran::lower::createMutableBox). However,
85 // pointer components need special care here so that local and global
86 // derived type containing pointers are always initialized.
87 // Intent(out), however, do not need to be initialized since the
88 // related descriptor storage comes from a local or global that has
89 // been initialized (it may not be NULL() anymore, but the rank, type,
90 // and non deferred length parameters are still correct in a
91 // conformant program, and that is what matters).
92 const bool ignorePointer = Fortran::semantics::IsIntentOut(sym);
93 return derivedTypeSpec->HasDefaultInitialization(
94 /*ignoreAllocatable=*/false, ignorePointer);
95 }
96 return false;
97 }
98
99 // Does this variable have a finalization?
100 static bool hasFinalization(const Fortran::semantics::Symbol &sym) {
101 if (sym.has<Fortran::semantics::ObjectEntityDetails>())
102 if (const Fortran::semantics::DeclTypeSpec *declTypeSpec = sym.GetType())
103 if (const Fortran::semantics::DerivedTypeSpec *derivedTypeSpec =
104 declTypeSpec->AsDerived())
105 return Fortran::semantics::IsFinalizable(*derivedTypeSpec);
106 return false;
107 }
108
109 // Does this variable have an allocatable direct component?
110 static bool
111 hasAllocatableDirectComponent(const Fortran::semantics::Symbol &sym) {
112 if (sym.has<Fortran::semantics::ObjectEntityDetails>())
113 if (const Fortran::semantics::DeclTypeSpec *declTypeSpec = sym.GetType())
114 if (const Fortran::semantics::DerivedTypeSpec *derivedTypeSpec =
115 declTypeSpec->AsDerived())
116 return Fortran::semantics::HasAllocatableDirectComponent(
117 *derivedTypeSpec);
118 return false;
119 }
120 //===----------------------------------------------------------------===//
121 // Global variables instantiation (not for alias and common)
122 //===----------------------------------------------------------------===//
123
124 /// Helper to generate expression value inside global initializer.
125 static fir::ExtendedValue
126 genInitializerExprValue(Fortran::lower::AbstractConverter &converter,
127 mlir::Location loc,
128 const Fortran::lower::SomeExpr &expr,
129 Fortran::lower::StatementContext &stmtCtx) {
130 // Data initializer are constant value and should not depend on other symbols
131 // given the front-end fold parameter references. In any case, the "current"
132 // map of the converter should not be used since it holds mapping to
133 // mlir::Value from another mlir region. If these value are used by accident
134 // in the initializer, this will lead to segfaults in mlir code.
135 Fortran::lower::SymMap emptyMap;
136 return Fortran::lower::createSomeInitializerExpression(loc, converter, expr,
137 emptyMap, stmtCtx);
138 }
139
140 /// Can this symbol constant be placed in read-only memory?
141 static bool isConstant(const Fortran::semantics::Symbol &sym) {
142 return sym.attrs().test(Fortran::semantics::Attr::PARAMETER) ||
143 sym.test(Fortran::semantics::Symbol::Flag::ReadOnly);
144 }
145
146 static fir::GlobalOp defineGlobal(Fortran::lower::AbstractConverter &converter,
147 const Fortran::lower::pft::Variable &var,
148 llvm::StringRef globalName,
149 mlir::StringAttr linkage,
150 cuf::DataAttributeAttr dataAttr = {});
151
152 static mlir::Location genLocation(Fortran::lower::AbstractConverter &converter,
153 const Fortran::semantics::Symbol &sym) {
154 // Compiler generated name cannot be used as source location, their name
155 // is not pointing to the source files.
156 if (!sym.test(Fortran::semantics::Symbol::Flag::CompilerCreated))
157 return converter.genLocation(sym.name());
158 return converter.getCurrentLocation();
159 }
160
161 /// Create the global op declaration without any initializer
162 static fir::GlobalOp declareGlobal(Fortran::lower::AbstractConverter &converter,
163 const Fortran::lower::pft::Variable &var,
164 llvm::StringRef globalName,
165 mlir::StringAttr linkage) {
166 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
167 if (fir::GlobalOp global = builder.getNamedGlobal(globalName))
168 return global;
169 const Fortran::semantics::Symbol &sym = var.getSymbol();
170 cuf::DataAttributeAttr dataAttr =
171 Fortran::lower::translateSymbolCUFDataAttribute(
172 converter.getFirOpBuilder().getContext(), sym);
173 // Always define linkonce data since it may be optimized out from the module
174 // that actually owns the variable if it does not refers to it.
175 if (linkage == builder.createLinkOnceODRLinkage() ||
176 linkage == builder.createLinkOnceLinkage())
177 return defineGlobal(converter, var, globalName, linkage, dataAttr);
178 mlir::Location loc = genLocation(converter, sym);
179 // Resolve potential host and module association before checking that this
180 // symbol is an object of a function pointer.
181 const Fortran::semantics::Symbol &ultimate = sym.GetUltimate();
182 if (!ultimate.has<Fortran::semantics::ObjectEntityDetails>() &&
183 !Fortran::semantics::IsProcedurePointer(ultimate))
184 mlir::emitError(loc, "processing global declaration: symbol '")
185 << toStringRef(sym.name()) << "' has unexpected details\n";
186 return builder.createGlobal(loc, converter.genType(var), globalName, linkage,
187 mlir::Attribute{}, isConstant(ultimate),
188 var.isTarget(), dataAttr);
189 }
190
191 /// Temporary helper to catch todos in initial data target lowering.
192 static bool
193 hasDerivedTypeWithLengthParameters(const Fortran::semantics::Symbol &sym) {
194 if (const Fortran::semantics::DeclTypeSpec *declTy = sym.GetType())
195 if (const Fortran::semantics::DerivedTypeSpec *derived =
196 declTy->AsDerived())
197 return Fortran::semantics::CountLenParameters(*derived) > 0;
198 return false;
199 }
200
201 fir::ExtendedValue Fortran::lower::genExtAddrInInitializer(
202 Fortran::lower::AbstractConverter &converter, mlir::Location loc,
203 const Fortran::lower::SomeExpr &addr) {
204 Fortran::lower::SymMap globalOpSymMap;
205 Fortran::lower::AggregateStoreMap storeMap;
206 Fortran::lower::StatementContext stmtCtx;
207 if (const Fortran::semantics::Symbol *sym =
208 Fortran::evaluate::GetFirstSymbol(addr)) {
209 // Length parameters processing will need care in global initializer
210 // context.
211 if (hasDerivedTypeWithLengthParameters(*sym))
212 TODO(loc, "initial-data-target with derived type length parameters");
213
214 auto var = Fortran::lower::pft::Variable(*sym, /*global=*/true);
215 Fortran::lower::instantiateVariable(converter, var, globalOpSymMap,
216 storeMap);
217 }
218
219 if (converter.getLoweringOptions().getLowerToHighLevelFIR())
220 return Fortran::lower::convertExprToAddress(loc, converter, addr,
221 globalOpSymMap, stmtCtx);
222 return Fortran::lower::createInitializerAddress(loc, converter, addr,
223 globalOpSymMap, stmtCtx);
224 }
225
226 /// create initial-data-target fir.box in a global initializer region.
227 mlir::Value Fortran::lower::genInitialDataTarget(
228 Fortran::lower::AbstractConverter &converter, mlir::Location loc,
229 mlir::Type boxType, const Fortran::lower::SomeExpr &initialTarget,
230 bool couldBeInEquivalence) {
231 Fortran::lower::SymMap globalOpSymMap;
232 Fortran::lower::AggregateStoreMap storeMap;
233 Fortran::lower::StatementContext stmtCtx;
234 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
235 if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>(
236 initialTarget))
237 return fir::factory::createUnallocatedBox(
238 builder, loc, boxType,
239 /*nonDeferredParams=*/std::nullopt);
240 // Pointer initial data target, and NULL(mold).
241 for (const auto &sym : Fortran::evaluate::CollectSymbols(initialTarget)) {
242 // Derived type component symbols should not be instantiated as objects
243 // on their own.
244 if (sym->owner().IsDerivedType())
245 continue;
246 // Length parameters processing will need care in global initializer
247 // context.
248 if (hasDerivedTypeWithLengthParameters(sym))
249 TODO(loc, "initial-data-target with derived type length parameters");
250 auto var = Fortran::lower::pft::Variable(sym, /*global=*/true);
251 if (couldBeInEquivalence) {
252 auto dependentVariableList =
253 Fortran::lower::pft::getDependentVariableList(sym);
254 for (Fortran::lower::pft::Variable var : dependentVariableList) {
255 if (!var.isAggregateStore())
256 break;
257 instantiateVariable(converter, var, globalOpSymMap, storeMap);
258 }
259 var = dependentVariableList.back();
260 assert(var.getSymbol().name() == sym->name() &&
261 "missing symbol in dependence list");
262 }
263 Fortran::lower::instantiateVariable(converter, var, globalOpSymMap,
264 storeMap);
265 }
266
267 // Handle NULL(mold) as a special case. Return an unallocated box of MOLD
268 // type. The return box is correctly created as a fir.box<fir.ptr<T>> where
269 // T is extracted from the MOLD argument.
270 if (const Fortran::evaluate::ProcedureRef *procRef =
271 Fortran::evaluate::UnwrapProcedureRef(initialTarget)) {
272 const Fortran::evaluate::SpecificIntrinsic *intrinsic =
273 procRef->proc().GetSpecificIntrinsic();
274 if (intrinsic && intrinsic->name == "null") {
275 assert(procRef->arguments().size() == 1 &&
276 "Expecting mold argument for NULL intrinsic");
277 const auto *argExpr = procRef->arguments()[0].value().UnwrapExpr();
278 assert(argExpr);
279 const Fortran::semantics::Symbol *sym =
280 Fortran::evaluate::GetFirstSymbol(*argExpr);
281 assert(sym && "MOLD must be a pointer or allocatable symbol");
282 mlir::Type boxType = converter.genType(*sym);
283 mlir::Value box =
284 fir::factory::createUnallocatedBox(builder, loc, boxType, {});
285 return box;
286 }
287 }
288
289 mlir::Value targetBox;
290 mlir::Value targetShift;
291 if (converter.getLoweringOptions().getLowerToHighLevelFIR()) {
292 auto target = Fortran::lower::convertExprToBox(
293 loc, converter, initialTarget, globalOpSymMap, stmtCtx);
294 targetBox = fir::getBase(target);
295 targetShift = builder.createShape(loc, target);
296 } else {
297 if (initialTarget.Rank() > 0) {
298 auto target = Fortran::lower::createSomeArrayBox(converter, initialTarget,
299 globalOpSymMap, stmtCtx);
300 targetBox = fir::getBase(target);
301 targetShift = builder.createShape(loc, target);
302 } else {
303 fir::ExtendedValue addr = Fortran::lower::createInitializerAddress(
304 loc, converter, initialTarget, globalOpSymMap, stmtCtx);
305 targetBox = builder.createBox(loc, addr);
306 // Nothing to do for targetShift, the target is a scalar.
307 }
308 }
309 // The targetBox is a fir.box<T>, not a fir.box<fir.ptr<T>> as it should for
310 // pointers (this matters to get the POINTER attribute correctly inside the
311 // initial value of the descriptor).
312 // Create a fir.rebox to set the attribute correctly, and use targetShift
313 // to preserve the target lower bounds if any.
314 return builder.create<fir::ReboxOp>(loc, boxType, targetBox, targetShift,
315 /*slice=*/mlir::Value{});
316 }
317
318 /// Generate default initial value for a derived type object \p sym with mlir
319 /// type \p symTy.
320 static mlir::Value genDefaultInitializerValue(
321 Fortran::lower::AbstractConverter &converter, mlir::Location loc,
322 const Fortran::semantics::Symbol &sym, mlir::Type symTy,
323 Fortran::lower::StatementContext &stmtCtx);
324
325 /// Generate the initial value of a derived component \p component and insert
326 /// it into the derived type initial value \p insertInto of type \p recTy.
327 /// Return the new derived type initial value after the insertion.
328 static mlir::Value genComponentDefaultInit(
329 Fortran::lower::AbstractConverter &converter, mlir::Location loc,
330 const Fortran::semantics::Symbol &component, fir::RecordType recTy,
331 mlir::Value insertInto, Fortran::lower::StatementContext &stmtCtx) {
332 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
333 std::string name = converter.getRecordTypeFieldName(component);
334 mlir::Type componentTy = recTy.getType(name);
335 assert(componentTy && "component not found in type");
336 mlir::Value componentValue;
337 if (const auto *object{
338 component.detailsIf<Fortran::semantics::ObjectEntityDetails>()}) {
339 if (const auto &init = object->init()) {
340 // Component has explicit initialization.
341 if (Fortran::semantics::IsPointer(component))
342 // Initial data target.
343 componentValue =
344 genInitialDataTarget(converter, loc, componentTy, *init);
345 else
346 // Initial value.
347 componentValue = fir::getBase(
348 genInitializerExprValue(converter, loc, *init, stmtCtx));
349 } else if (Fortran::semantics::IsAllocatableOrPointer(component)) {
350 // Pointer or allocatable without initialization.
351 // Create deallocated/disassociated value.
352 // From a standard point of view, pointer without initialization do not
353 // need to be disassociated, but for sanity and simplicity, do it in
354 // global constructor since this has no runtime cost.
355 componentValue = fir::factory::createUnallocatedBox(
356 builder, loc, componentTy, std::nullopt);
357 } else if (Fortran::lower::hasDefaultInitialization(component)) {
358 // Component type has default initialization.
359 componentValue = genDefaultInitializerValue(converter, loc, component,
360 componentTy, stmtCtx);
361 } else {
362 // Component has no initial value. Set its bits to zero by extension
363 // to match what is expected because other compilers are doing it.
364 componentValue = builder.create<fir::ZeroOp>(loc, componentTy);
365 }
366 } else if (const auto *proc{
367 component
368 .detailsIf<Fortran::semantics::ProcEntityDetails>()}) {
369 if (proc->init().has_value()) {
370 auto sym{*proc->init()};
371 if (sym) // Has a procedure target.
372 componentValue =
373 Fortran::lower::convertProcedureDesignatorInitialTarget(converter,
374 loc, *sym);
375 else // Has NULL() target.
376 componentValue =
377 fir::factory::createNullBoxProc(builder, loc, componentTy);
378 } else
379 componentValue = builder.create<fir::ZeroOp>(loc, componentTy);
380 }
381 assert(componentValue && "must have been computed");
382 componentValue = builder.createConvert(loc, componentTy, componentValue);
383 auto fieldTy = fir::FieldType::get(recTy.getContext());
384 // FIXME: type parameters must come from the derived-type-spec
385 auto field = builder.create<fir::FieldIndexOp>(
386 loc, fieldTy, name, recTy,
387 /*typeParams=*/mlir::ValueRange{} /*TODO*/);
388 return builder.create<fir::InsertValueOp>(
389 loc, recTy, insertInto, componentValue,
390 builder.getArrayAttr(field.getAttributes()));
391 }
392
393 static mlir::Value genDefaultInitializerValue(
394 Fortran::lower::AbstractConverter &converter, mlir::Location loc,
395 const Fortran::semantics::Symbol &sym, mlir::Type symTy,
396 Fortran::lower::StatementContext &stmtCtx) {
397 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
398 mlir::Type scalarType = symTy;
399 fir::SequenceType sequenceType;
400 if (auto ty = mlir::dyn_cast<fir::SequenceType>(symTy)) {
401 sequenceType = ty;
402 scalarType = ty.getEleTy();
403 }
404 // Build a scalar default value of the symbol type, looping through the
405 // components to build each component initial value.
406 auto recTy = mlir::cast<fir::RecordType>(scalarType);
407 mlir::Value initialValue = builder.create<fir::UndefOp>(loc, scalarType);
408 const Fortran::semantics::DeclTypeSpec *declTy = sym.GetType();
409 assert(declTy && "var with default initialization must have a type");
410
411 if (converter.getLoweringOptions().getLowerToHighLevelFIR()) {
412 // In HLFIR, the parent type is the first component, while in FIR there is
413 // not parent component in the fir.type and the component of the parent are
414 // "inlined" at the beginning of the fir.type.
415 const Fortran::semantics::Symbol &typeSymbol =
416 declTy->derivedTypeSpec().typeSymbol();
417 const Fortran::semantics::Scope *derivedScope =
418 declTy->derivedTypeSpec().GetScope();
419 assert(derivedScope && "failed to retrieve derived type scope");
420 for (const auto &componentName :
421 typeSymbol.get<Fortran::semantics::DerivedTypeDetails>()
422 .componentNames()) {
423 auto scopeIter = derivedScope->find(componentName);
424 assert(scopeIter != derivedScope->cend() &&
425 "failed to find derived type component symbol");
426 const Fortran::semantics::Symbol &component = scopeIter->second.get();
427 initialValue = genComponentDefaultInit(converter, loc, component, recTy,
428 initialValue, stmtCtx);
429 }
430 } else {
431 Fortran::semantics::OrderedComponentIterator components(
432 declTy->derivedTypeSpec());
433 for (const auto &component : components) {
434 // Skip parent components, the sub-components of parent types are part of
435 // components and will be looped through right after.
436 if (component.test(Fortran::semantics::Symbol::Flag::ParentComp))
437 continue;
438 initialValue = genComponentDefaultInit(converter, loc, component, recTy,
439 initialValue, stmtCtx);
440 }
441 }
442
443 if (sequenceType) {
444 // For arrays, duplicate the scalar value to all elements with an
445 // fir.insert_range covering the whole array.
446 auto arrayInitialValue = builder.create<fir::UndefOp>(loc, sequenceType);
447 llvm::SmallVector<int64_t> rangeBounds;
448 for (int64_t extent : sequenceType.getShape()) {
449 if (extent == fir::SequenceType::getUnknownExtent())
450 TODO(loc,
451 "default initial value of array component with length parameters");
452 rangeBounds.push_back(0);
453 rangeBounds.push_back(extent - 1);
454 }
455 return builder.create<fir::InsertOnRangeOp>(
456 loc, sequenceType, arrayInitialValue, initialValue,
457 builder.getIndexVectorAttr(rangeBounds));
458 }
459 return initialValue;
460 }
461
462 /// Does this global already have an initializer ?
463 static bool globalIsInitialized(fir::GlobalOp global) {
464 return !global.getRegion().empty() || global.getInitVal();
465 }
466
467 /// Call \p genInit to generate code inside \p global initializer region.
468 void Fortran::lower::createGlobalInitialization(
469 fir::FirOpBuilder &builder, fir::GlobalOp global,
470 std::function<void(fir::FirOpBuilder &)> genInit) {
471 mlir::Region &region = global.getRegion();
472 region.push_back(new mlir::Block);
473 mlir::Block &block = region.back();
474 auto insertPt = builder.saveInsertionPoint();
475 builder.setInsertionPointToStart(&block);
476 genInit(builder);
477 builder.restoreInsertionPoint(insertPt);
478 }
479
480 /// Create the global op and its init if it has one
481 static fir::GlobalOp defineGlobal(Fortran::lower::AbstractConverter &converter,
482 const Fortran::lower::pft::Variable &var,
483 llvm::StringRef globalName,
484 mlir::StringAttr linkage,
485 cuf::DataAttributeAttr dataAttr) {
486 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
487 const Fortran::semantics::Symbol &sym = var.getSymbol();
488 mlir::Location loc = genLocation(converter, sym);
489 bool isConst = isConstant(sym);
490 fir::GlobalOp global = builder.getNamedGlobal(globalName);
491 mlir::Type symTy = converter.genType(var);
492
493 if (global && globalIsInitialized(global))
494 return global;
495
496 if (!converter.getLoweringOptions().getLowerToHighLevelFIR() &&
497 Fortran::semantics::IsProcedurePointer(sym))
498 TODO(loc, "procedure pointer globals");
499
500 // If this is an array, check to see if we can use a dense attribute
501 // with a tensor mlir type. This optimization currently only supports
502 // Fortran arrays of integer, real, complex, or logical. The tensor
503 // type does not support nested structures.
504 if (mlir::isa<fir::SequenceType>(symTy) &&
505 !Fortran::semantics::IsAllocatableOrPointer(sym)) {
506 mlir::Type eleTy = mlir::cast<fir::SequenceType>(symTy).getEleTy();
507 if (mlir::isa<mlir::IntegerType, mlir::FloatType, fir::ComplexType,
508 fir::LogicalType>(eleTy)) {
509 const auto *details =
510 sym.detailsIf<Fortran::semantics::ObjectEntityDetails>();
511 if (details->init()) {
512 global = Fortran::lower::tryCreatingDenseGlobal(
513 builder, loc, symTy, globalName, linkage, isConst,
514 details->init().value(), dataAttr);
515 if (global) {
516 global.setVisibility(mlir::SymbolTable::Visibility::Public);
517 return global;
518 }
519 }
520 }
521 }
522 if (!global)
523 global =
524 builder.createGlobal(loc, symTy, globalName, linkage, mlir::Attribute{},
525 isConst, var.isTarget(), dataAttr);
526 if (Fortran::semantics::IsAllocatableOrPointer(sym) &&
527 !Fortran::semantics::IsProcedure(sym)) {
528 const auto *details =
529 sym.detailsIf<Fortran::semantics::ObjectEntityDetails>();
530 if (details && details->init()) {
531 auto expr = *details->init();
532 Fortran::lower::createGlobalInitialization(
533 builder, global, [&](fir::FirOpBuilder &b) {
534 mlir::Value box = Fortran::lower::genInitialDataTarget(
535 converter, loc, symTy, expr);
536 b.create<fir::HasValueOp>(loc, box);
537 });
538 } else {
539 // Create unallocated/disassociated descriptor if no explicit init
540 Fortran::lower::createGlobalInitialization(
541 builder, global, [&](fir::FirOpBuilder &b) {
542 mlir::Value box =
543 fir::factory::createUnallocatedBox(b, loc, symTy, std::nullopt);
544 b.create<fir::HasValueOp>(loc, box);
545 });
546 }
547 } else if (const auto *details =
548 sym.detailsIf<Fortran::semantics::ObjectEntityDetails>()) {
549 if (details->init()) {
550 Fortran::lower::createGlobalInitialization(
551 builder, global, [&](fir::FirOpBuilder &builder) {
552 Fortran::lower::StatementContext stmtCtx(
553 /*cleanupProhibited=*/true);
554 fir::ExtendedValue initVal = genInitializerExprValue(
555 converter, loc, details->init().value(), stmtCtx);
556 mlir::Value castTo =
557 builder.createConvert(loc, symTy, fir::getBase(initVal));
558 builder.create<fir::HasValueOp>(loc, castTo);
559 });
560 } else if (Fortran::lower::hasDefaultInitialization(sym)) {
561 Fortran::lower::createGlobalInitialization(
562 builder, global, [&](fir::FirOpBuilder &builder) {
563 Fortran::lower::StatementContext stmtCtx(
564 /*cleanupProhibited=*/true);
565 mlir::Value initVal =
566 genDefaultInitializerValue(converter, loc, sym, symTy, stmtCtx);
567 mlir::Value castTo = builder.createConvert(loc, symTy, initVal);
568 builder.create<fir::HasValueOp>(loc, castTo);
569 });
570 }
571 } else if (Fortran::semantics::IsProcedurePointer(sym)) {
572 const auto *details{sym.detailsIf<Fortran::semantics::ProcEntityDetails>()};
573 if (details && details->init()) {
574 auto sym{*details->init()};
575 if (sym) // Has a procedure target.
576 Fortran::lower::createGlobalInitialization(
577 builder, global, [&](fir::FirOpBuilder &b) {
578 Fortran::lower::StatementContext stmtCtx(
579 /*cleanupProhibited=*/true);
580 auto box{Fortran::lower::convertProcedureDesignatorInitialTarget(
581 converter, loc, *sym)};
582 auto castTo{builder.createConvert(loc, symTy, box)};
583 b.create<fir::HasValueOp>(loc, castTo);
584 });
585 else { // Has NULL() target.
586 Fortran::lower::createGlobalInitialization(
587 builder, global, [&](fir::FirOpBuilder &b) {
588 auto box{fir::factory::createNullBoxProc(b, loc, symTy)};
589 b.create<fir::HasValueOp>(loc, box);
590 });
591 }
592 } else {
593 // No initialization.
594 Fortran::lower::createGlobalInitialization(
595 builder, global, [&](fir::FirOpBuilder &b) {
596 auto box{fir::factory::createNullBoxProc(b, loc, symTy)};
597 b.create<fir::HasValueOp>(loc, box);
598 });
599 }
600 } else if (sym.has<Fortran::semantics::CommonBlockDetails>()) {
601 mlir::emitError(loc, "COMMON symbol processed elsewhere");
602 } else {
603 TODO(loc, "global"); // Something else
604 }
605 // Creates zero initializer for globals without initializers, this is a common
606 // and expected behavior (although not required by the standard)
607 if (!globalIsInitialized(global)) {
608 // Fortran does not provide means to specify that a BIND(C) module
609 // uninitialized variables will be defined in C.
610 // Add the common linkage to those to allow some level of support
611 // for this use case. Note that this use case will not work if the Fortran
612 // module code is placed in a shared library since, at least for the ELF
613 // format, common symbols are assigned a section in shared libraries.
614 // The best is still to declare C defined variables in a Fortran module file
615 // with no other definitions, and to never link the resulting module object
616 // file.
617 if (sym.attrs().test(Fortran::semantics::Attr::BIND_C))
618 global.setLinkName(builder.createCommonLinkage());
619 Fortran::lower::createGlobalInitialization(
620 builder, global, [&](fir::FirOpBuilder &builder) {
621 mlir::Value initValue = builder.create<fir::ZeroOp>(loc, symTy);
622 builder.create<fir::HasValueOp>(loc, initValue);
623 });
624 }
625 // Set public visibility to prevent global definition to be optimized out
626 // even if they have no initializer and are unused in this compilation unit.
627 global.setVisibility(mlir::SymbolTable::Visibility::Public);
628 return global;
629 }
630
631 /// Return linkage attribute for \p var.
632 static mlir::StringAttr
633 getLinkageAttribute(fir::FirOpBuilder &builder,
634 const Fortran::lower::pft::Variable &var) {
635 // Runtime type info for a same derived type is identical in each compilation
636 // unit. It desired to avoid having to link against module that only define a
637 // type. Therefore the runtime type info is generated everywhere it is needed
638 // with `linkonce_odr` LLVM linkage.
639 if (var.isRuntimeTypeInfoData())
640 return builder.createLinkOnceODRLinkage();
641 if (var.isModuleOrSubmoduleVariable())
642 return {}; // external linkage
643 // Otherwise, the variable is owned by a procedure and must not be visible in
644 // other compilation units.
645 return builder.createInternalLinkage();
646 }
647
648 /// Instantiate a global variable. If it hasn't already been processed, add
649 /// the global to the ModuleOp as a new uniqued symbol and initialize it with
650 /// the correct value. It will be referenced on demand using `fir.addr_of`.
651 static void instantiateGlobal(Fortran::lower::AbstractConverter &converter,
652 const Fortran::lower::pft::Variable &var,
653 Fortran::lower::SymMap &symMap) {
654 const Fortran::semantics::Symbol &sym = var.getSymbol();
655 assert(!var.isAlias() && "must be handled in instantiateAlias");
656 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
657 std::string globalName = converter.mangleName(sym);
658 mlir::Location loc = genLocation(converter, sym);
659 mlir::StringAttr linkage = getLinkageAttribute(builder, var);
660 fir::GlobalOp global;
661 if (var.isModuleOrSubmoduleVariable()) {
662 // A non-intrinsic module global is defined when lowering the module.
663 // Emit only a declaration if the global does not exist.
664 global = declareGlobal(converter, var, globalName, linkage);
665 } else {
666 cuf::DataAttributeAttr dataAttr =
667 Fortran::lower::translateSymbolCUFDataAttribute(builder.getContext(),
668 sym);
669 global = defineGlobal(converter, var, globalName, linkage, dataAttr);
670 }
671 auto addrOf = builder.create<fir::AddrOfOp>(loc, global.resultType(),
672 global.getSymbol());
673 Fortran::lower::StatementContext stmtCtx;
674 mapSymbolAttributes(converter, var, symMap, stmtCtx, addrOf);
675 }
676
677 //===----------------------------------------------------------------===//
678 // Local variables instantiation (not for alias)
679 //===----------------------------------------------------------------===//
680
681 /// Create a stack slot for a local variable. Precondition: the insertion
682 /// point of the builder must be in the entry block, which is currently being
683 /// constructed.
684 static mlir::Value createNewLocal(Fortran::lower::AbstractConverter &converter,
685 mlir::Location loc,
686 const Fortran::lower::pft::Variable &var,
687 mlir::Value preAlloc,
688 llvm::ArrayRef<mlir::Value> shape = {},
689 llvm::ArrayRef<mlir::Value> lenParams = {}) {
690 if (preAlloc)
691 return preAlloc;
692 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
693 std::string nm = converter.mangleName(var.getSymbol());
694 mlir::Type ty = converter.genType(var);
695 const Fortran::semantics::Symbol &ultimateSymbol =
696 var.getSymbol().GetUltimate();
697 llvm::StringRef symNm = toStringRef(ultimateSymbol.name());
698 bool isTarg = var.isTarget();
699
700 // Do not allocate storage for cray pointee. The address inside the cray
701 // pointer will be used instead when using the pointee. Allocating space
702 // would be a waste of space, and incorrect if the pointee is a non dummy
703 // assumed-size (possible with cray pointee).
704 if (ultimateSymbol.test(Fortran::semantics::Symbol::Flag::CrayPointee))
705 return builder.create<fir::ZeroOp>(loc, fir::ReferenceType::get(ty));
706
707 if (Fortran::semantics::NeedCUDAAlloc(ultimateSymbol)) {
708 cuf::DataAttributeAttr dataAttr =
709 Fortran::lower::translateSymbolCUFDataAttribute(builder.getContext(),
710 ultimateSymbol);
711 llvm::SmallVector<mlir::Value> indices;
712 llvm::SmallVector<mlir::Value> elidedShape =
713 fir::factory::elideExtentsAlreadyInType(ty, shape);
714 llvm::SmallVector<mlir::Value> elidedLenParams =
715 fir::factory::elideLengthsAlreadyInType(ty, lenParams);
716 auto idxTy = builder.getIndexType();
717 for (mlir::Value sh : elidedShape)
718 indices.push_back(builder.createConvert(loc, idxTy, sh));
719 mlir::Value alloc = builder.create<cuf::AllocOp>(
720 loc, ty, nm, symNm, dataAttr, lenParams, indices);
721 return alloc;
722 }
723
724 // Let the builder do all the heavy lifting.
725 if (!Fortran::semantics::IsProcedurePointer(ultimateSymbol))
726 return builder.allocateLocal(loc, ty, nm, symNm, shape, lenParams, isTarg);
727
728 // Local procedure pointer.
729 auto res{builder.allocateLocal(loc, ty, nm, symNm, shape, lenParams, isTarg)};
730 auto box{fir::factory::createNullBoxProc(builder, loc, ty)};
731 builder.create<fir::StoreOp>(loc, box, res);
732 return res;
733 }
734
735 /// Must \p var be default initialized at runtime when entering its scope.
736 static bool
737 mustBeDefaultInitializedAtRuntime(const Fortran::lower::pft::Variable &var) {
738 if (!var.hasSymbol())
739 return false;
740 const Fortran::semantics::Symbol &sym = var.getSymbol();
741 if (var.isGlobal())
742 // Global variables are statically initialized.
743 return false;
744 if (Fortran::semantics::IsDummy(sym) && !Fortran::semantics::IsIntentOut(sym))
745 return false;
746 // Polymorphic intent(out) dummy might need default initialization
747 // at runtime.
748 if (Fortran::semantics::IsPolymorphic(sym) &&
749 Fortran::semantics::IsDummy(sym) &&
750 Fortran::semantics::IsIntentOut(sym) &&
751 !Fortran::semantics::IsAllocatable(sym) &&
752 !Fortran::semantics::IsPointer(sym))
753 return true;
754 // Local variables (including function results), and intent(out) dummies must
755 // be default initialized at runtime if their type has default initialization.
756 return Fortran::lower::hasDefaultInitialization(sym);
757 }
758
759 /// Call default initialization runtime routine to initialize \p var.
760 void Fortran::lower::defaultInitializeAtRuntime(
761 Fortran::lower::AbstractConverter &converter,
762 const Fortran::semantics::Symbol &sym, Fortran::lower::SymMap &symMap) {
763 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
764 mlir::Location loc = converter.getCurrentLocation();
765 fir::ExtendedValue exv = converter.getSymbolExtendedValue(sym, &symMap);
766 if (Fortran::semantics::IsOptional(sym)) {
767 // 15.5.2.12 point 3, absent optional dummies are not initialized.
768 // Creating descriptor/passing null descriptor to the runtime would
769 // create runtime crashes.
770 auto isPresent = builder.create<fir::IsPresentOp>(loc, builder.getI1Type(),
771 fir::getBase(exv));
772 builder.genIfThen(loc, isPresent)
773 .genThen([&]() {
774 auto box = builder.createBox(loc, exv);
775 fir::runtime::genDerivedTypeInitialize(builder, loc, box);
776 })
777 .end();
778 } else {
779 mlir::Value box = builder.createBox(loc, exv);
780 fir::runtime::genDerivedTypeInitialize(builder, loc, box);
781 }
782 }
783
784 enum class VariableCleanUp { Finalize, Deallocate };
785 /// Check whether a local variable needs to be finalized according to clause
786 /// 7.5.6.3 point 3 or if it is an allocatable that must be deallocated. Note
787 /// that deallocation will trigger finalization if the type has any.
788 static std::optional<VariableCleanUp>
789 needDeallocationOrFinalization(const Fortran::lower::pft::Variable &var) {
790 if (!var.hasSymbol())
791 return std::nullopt;
792 const Fortran::semantics::Symbol &sym = var.getSymbol();
793 const Fortran::semantics::Scope &owner = sym.owner();
794 if (owner.kind() == Fortran::semantics::Scope::Kind::MainProgram) {
795 // The standard does not require finalizing main program variables.
796 return std::nullopt;
797 }
798 if (!Fortran::semantics::IsPointer(sym) &&
799 !Fortran::semantics::IsDummy(sym) &&
800 !Fortran::semantics::IsFunctionResult(sym) &&
801 !Fortran::semantics::IsSaved(sym)) {
802 if (Fortran::semantics::IsAllocatable(sym))
803 return VariableCleanUp::Deallocate;
804 if (hasFinalization(sym))
805 return VariableCleanUp::Finalize;
806 // hasFinalization() check above handled all cases that require
807 // finalization, but we also have to deallocate all allocatable
808 // components of local variables (since they are also local variables
809 // according to F18 5.4.3.2.2, p. 2, note 1).
810 // Here, the variable itself is not allocatable. If it has an allocatable
811 // component the Destroy runtime does the job. Use the Finalize clean-up,
812 // though there will be no finalization in runtime.
813 if (hasAllocatableDirectComponent(sym))
814 return VariableCleanUp::Finalize;
815 }
816 return std::nullopt;
817 }
818
819 /// Check whether a variable needs the be finalized according to clause 7.5.6.3
820 /// point 7.
821 /// Must be nonpointer, nonallocatable, INTENT (OUT) dummy argument.
822 static bool
823 needDummyIntentoutFinalization(const Fortran::lower::pft::Variable &var) {
824 if (!var.hasSymbol())
825 return false;
826 const Fortran::semantics::Symbol &sym = var.getSymbol();
827 if (!Fortran::semantics::IsDummy(sym) ||
828 !Fortran::semantics::IsIntentOut(sym) ||
829 Fortran::semantics::IsAllocatable(sym) ||
830 Fortran::semantics::IsPointer(sym))
831 return false;
832 // Polymorphic and unlimited polymorphic intent(out) dummy argument might need
833 // finalization at runtime.
834 if (Fortran::semantics::IsPolymorphic(sym) ||
835 Fortran::semantics::IsUnlimitedPolymorphic(sym))
836 return true;
837 // Intent(out) dummies must be finalized at runtime if their type has a
838 // finalization.
839 // Allocatable components of INTENT(OUT) dummies must be deallocated (9.7.3.2
840 // p6). Calling finalization runtime for this works even if the components
841 // have no final procedures.
842 return hasFinalization(sym) || hasAllocatableDirectComponent(sym);
843 }
844
845 /// Call default initialization runtime routine to initialize \p var.
846 static void finalizeAtRuntime(Fortran::lower::AbstractConverter &converter,
847 const Fortran::lower::pft::Variable &var,
848 Fortran::lower::SymMap &symMap) {
849 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
850 mlir::Location loc = converter.getCurrentLocation();
851 const Fortran::semantics::Symbol &sym = var.getSymbol();
852 fir::ExtendedValue exv = converter.getSymbolExtendedValue(sym, &symMap);
853 if (Fortran::semantics::IsOptional(sym)) {
854 // Only finalize if present.
855 auto isPresent = builder.create<fir::IsPresentOp>(loc, builder.getI1Type(),
856 fir::getBase(exv));
857 builder.genIfThen(loc, isPresent)
858 .genThen([&]() {
859 auto box = builder.createBox(loc, exv);
860 fir::runtime::genDerivedTypeDestroy(builder, loc, box);
861 })
862 .end();
863 } else {
864 mlir::Value box = builder.createBox(loc, exv);
865 fir::runtime::genDerivedTypeDestroy(builder, loc, box);
866 }
867 }
868
869 // Fortran 2018 - 9.7.3.2 point 6
870 // When a procedure is invoked, any allocated allocatable object that is an
871 // actual argument corresponding to an INTENT(OUT) allocatable dummy argument
872 // is deallocated; any allocated allocatable object that is a subobject of an
873 // actual argument corresponding to an INTENT(OUT) dummy argument is
874 // deallocated.
875 // Note that allocatable components of non-ALLOCATABLE INTENT(OUT) dummy
876 // arguments are dealt with needDummyIntentoutFinalization (finalization runtime
877 // is called to reach the intended component deallocation effect).
878 static void deallocateIntentOut(Fortran::lower::AbstractConverter &converter,
879 const Fortran::lower::pft::Variable &var,
880 Fortran::lower::SymMap &symMap) {
881 if (!var.hasSymbol())
882 return;
883
884 const Fortran::semantics::Symbol &sym = var.getSymbol();
885 if (Fortran::semantics::IsDummy(sym) &&
886 Fortran::semantics::IsIntentOut(sym) &&
887 Fortran::semantics::IsAllocatable(sym)) {
888 fir::ExtendedValue extVal = converter.getSymbolExtendedValue(sym, &symMap);
889 if (auto mutBox = extVal.getBoxOf<fir::MutableBoxValue>()) {
890 // The dummy argument is not passed in the ENTRY so it should not be
891 // deallocated.
892 if (mlir::Operation *op = mutBox->getAddr().getDefiningOp()) {
893 if (auto declOp = mlir::dyn_cast<hlfir::DeclareOp>(op))
894 op = declOp.getMemref().getDefiningOp();
895 if (op && mlir::isa<fir::AllocaOp>(op))
896 return;
897 }
898 mlir::Location loc = converter.getCurrentLocation();
899 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
900
901 if (Fortran::semantics::IsOptional(sym)) {
902 auto isPresent = builder.create<fir::IsPresentOp>(
903 loc, builder.getI1Type(), fir::getBase(extVal));
904 builder.genIfThen(loc, isPresent)
905 .genThen([&]() {
906 Fortran::lower::genDeallocateIfAllocated(converter, *mutBox, loc);
907 })
908 .end();
909 } else {
910 Fortran::lower::genDeallocateIfAllocated(converter, *mutBox, loc);
911 }
912 }
913 }
914 }
915
916 /// Instantiate a local variable. Precondition: Each variable will be visited
917 /// such that if its properties depend on other variables, the variables upon
918 /// which its properties depend will already have been visited.
919 static void instantiateLocal(Fortran::lower::AbstractConverter &converter,
920 const Fortran::lower::pft::Variable &var,
921 Fortran::lower::SymMap &symMap) {
922 assert(!var.isAlias());
923 Fortran::lower::StatementContext stmtCtx;
924 mapSymbolAttributes(converter, var, symMap, stmtCtx);
925 deallocateIntentOut(converter, var, symMap);
926 if (needDummyIntentoutFinalization(var))
927 finalizeAtRuntime(converter, var, symMap);
928 if (mustBeDefaultInitializedAtRuntime(var))
929 Fortran::lower::defaultInitializeAtRuntime(converter, var.getSymbol(),
930 symMap);
931 if (Fortran::semantics::NeedCUDAAlloc(var.getSymbol())) {
932 auto *builder = &converter.getFirOpBuilder();
933 mlir::Location loc = converter.getCurrentLocation();
934 fir::ExtendedValue exv =
935 converter.getSymbolExtendedValue(var.getSymbol(), &symMap);
936 auto *sym = &var.getSymbol();
937 converter.getFctCtx().attachCleanup([builder, loc, exv, sym]() {
938 cuf::DataAttributeAttr dataAttr =
939 Fortran::lower::translateSymbolCUFDataAttribute(builder->getContext(),
940 *sym);
941 builder->create<cuf::FreeOp>(loc, fir::getBase(exv), dataAttr);
942 });
943 }
944 if (std::optional<VariableCleanUp> cleanup =
945 needDeallocationOrFinalization(var)) {
946 auto *builder = &converter.getFirOpBuilder();
947 mlir::Location loc = converter.getCurrentLocation();
948 fir::ExtendedValue exv =
949 converter.getSymbolExtendedValue(var.getSymbol(), &symMap);
950 switch (*cleanup) {
951 case VariableCleanUp::Finalize:
952 converter.getFctCtx().attachCleanup([builder, loc, exv]() {
953 mlir::Value box = builder->createBox(loc, exv);
954 fir::runtime::genDerivedTypeDestroy(*builder, loc, box);
955 });
956 break;
957 case VariableCleanUp::Deallocate:
958 auto *converterPtr = &converter;
959 auto *sym = &var.getSymbol();
960 converter.getFctCtx().attachCleanup([converterPtr, loc, exv, sym]() {
961 const fir::MutableBoxValue *mutableBox =
962 exv.getBoxOf<fir::MutableBoxValue>();
963 assert(mutableBox &&
964 "trying to deallocate entity not lowered as allocatable");
965 Fortran::lower::genDeallocateIfAllocated(*converterPtr, *mutableBox,
966 loc, sym);
967
968 });
969 }
970 }
971 }
972
973 //===----------------------------------------------------------------===//
974 // Aliased (EQUIVALENCE) variables instantiation
975 //===----------------------------------------------------------------===//
976
977 /// Insert \p aggregateStore instance into an AggregateStoreMap.
978 static void insertAggregateStore(Fortran::lower::AggregateStoreMap &storeMap,
979 const Fortran::lower::pft::Variable &var,
980 mlir::Value aggregateStore) {
981 std::size_t off = var.getAggregateStore().getOffset();
982 Fortran::lower::AggregateStoreKey key = {var.getOwningScope(), off};
983 storeMap[key] = aggregateStore;
984 }
985
986 /// Retrieve the aggregate store instance of \p alias from an
987 /// AggregateStoreMap.
988 static mlir::Value
989 getAggregateStore(Fortran::lower::AggregateStoreMap &storeMap,
990 const Fortran::lower::pft::Variable &alias) {
991 Fortran::lower::AggregateStoreKey key = {alias.getOwningScope(),
992 alias.getAliasOffset()};
993 auto iter = storeMap.find(key);
994 assert(iter != storeMap.end());
995 return iter->second;
996 }
997
998 /// Build the name for the storage of a global equivalence.
999 static std::string mangleGlobalAggregateStore(
1000 Fortran::lower::AbstractConverter &converter,
1001 const Fortran::lower::pft::Variable::AggregateStore &st) {
1002 return converter.mangleName(st.getNamingSymbol());
1003 }
1004
1005 /// Build the type for the storage of an equivalence.
1006 static mlir::Type
1007 getAggregateType(Fortran::lower::AbstractConverter &converter,
1008 const Fortran::lower::pft::Variable::AggregateStore &st) {
1009 if (const Fortran::semantics::Symbol *initSym = st.getInitialValueSymbol())
1010 return converter.genType(*initSym);
1011 mlir::IntegerType byteTy = converter.getFirOpBuilder().getIntegerType(8);
1012 return fir::SequenceType::get(std::get<1>(st.interval), byteTy);
1013 }
1014
1015 /// Define a GlobalOp for the storage of a global equivalence described
1016 /// by \p aggregate. The global is named \p aggName and is created with
1017 /// the provided \p linkage.
1018 /// If any of the equivalence members are initialized, an initializer is
1019 /// created for the equivalence.
1020 /// This is to be used when lowering the scope that owns the equivalence
1021 /// (as opposed to simply using it through host or use association).
1022 /// This is not to be used for equivalence of common block members (they
1023 /// already have the common block GlobalOp for them, see defineCommonBlock).
1024 static fir::GlobalOp defineGlobalAggregateStore(
1025 Fortran::lower::AbstractConverter &converter,
1026 const Fortran::lower::pft::Variable::AggregateStore &aggregate,
1027 llvm::StringRef aggName, mlir::StringAttr linkage) {
1028 assert(aggregate.isGlobal() && "not a global interval");
1029 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1030 fir::GlobalOp global = builder.getNamedGlobal(aggName);
1031 if (global && globalIsInitialized(global))
1032 return global;
1033 mlir::Location loc = converter.getCurrentLocation();
1034 mlir::Type aggTy = getAggregateType(converter, aggregate);
1035 if (!global)
1036 global = builder.createGlobal(loc, aggTy, aggName, linkage);
1037
1038 if (const Fortran::semantics::Symbol *initSym =
1039 aggregate.getInitialValueSymbol())
1040 if (const auto *objectDetails =
1041 initSym->detailsIf<Fortran::semantics::ObjectEntityDetails>())
1042 if (objectDetails->init()) {
1043 Fortran::lower::createGlobalInitialization(
1044 builder, global, [&](fir::FirOpBuilder &builder) {
1045 Fortran::lower::StatementContext stmtCtx;
1046 mlir::Value initVal = fir::getBase(genInitializerExprValue(
1047 converter, loc, objectDetails->init().value(), stmtCtx));
1048 builder.create<fir::HasValueOp>(loc, initVal);
1049 });
1050 return global;
1051 }
1052 // Equivalence has no Fortran initial value. Create an undefined FIR initial
1053 // value to ensure this is consider an object definition in the IR regardless
1054 // of the linkage.
1055 Fortran::lower::createGlobalInitialization(
1056 builder, global, [&](fir::FirOpBuilder &builder) {
1057 Fortran::lower::StatementContext stmtCtx;
1058 mlir::Value initVal = builder.create<fir::ZeroOp>(loc, aggTy);
1059 builder.create<fir::HasValueOp>(loc, initVal);
1060 });
1061 return global;
1062 }
1063
1064 /// Declare a GlobalOp for the storage of a global equivalence described
1065 /// by \p aggregate. The global is named \p aggName and is created with
1066 /// the provided \p linkage.
1067 /// No initializer is built for the created GlobalOp.
1068 /// This is to be used when lowering the scope that uses members of an
1069 /// equivalence it through host or use association.
1070 /// This is not to be used for equivalence of common block members (they
1071 /// already have the common block GlobalOp for them, see defineCommonBlock).
1072 static fir::GlobalOp declareGlobalAggregateStore(
1073 Fortran::lower::AbstractConverter &converter, mlir::Location loc,
1074 const Fortran::lower::pft::Variable::AggregateStore &aggregate,
1075 llvm::StringRef aggName, mlir::StringAttr linkage) {
1076 assert(aggregate.isGlobal() && "not a global interval");
1077 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1078 if (fir::GlobalOp global = builder.getNamedGlobal(aggName))
1079 return global;
1080 mlir::Type aggTy = getAggregateType(converter, aggregate);
1081 return builder.createGlobal(loc, aggTy, aggName, linkage);
1082 }
1083
1084 /// This is an aggregate store for a set of EQUIVALENCED variables. Create the
1085 /// storage on the stack or global memory and add it to the map.
1086 static void
1087 instantiateAggregateStore(Fortran::lower::AbstractConverter &converter,
1088 const Fortran::lower::pft::Variable &var,
1089 Fortran::lower::AggregateStoreMap &storeMap) {
1090 assert(var.isAggregateStore() && "not an interval");
1091 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1092 mlir::IntegerType i8Ty = builder.getIntegerType(8);
1093 mlir::Location loc = converter.getCurrentLocation();
1094 std::string aggName =
1095 mangleGlobalAggregateStore(converter, var.getAggregateStore());
1096 if (var.isGlobal()) {
1097 fir::GlobalOp global;
1098 auto &aggregate = var.getAggregateStore();
1099 mlir::StringAttr linkage = getLinkageAttribute(builder, var);
1100 if (var.isModuleOrSubmoduleVariable()) {
1101 // A module global was or will be defined when lowering the module. Emit
1102 // only a declaration if the global does not exist at that point.
1103 global = declareGlobalAggregateStore(converter, loc, aggregate, aggName,
1104 linkage);
1105 } else {
1106 global =
1107 defineGlobalAggregateStore(converter, aggregate, aggName, linkage);
1108 }
1109 auto addr = builder.create<fir::AddrOfOp>(loc, global.resultType(),
1110 global.getSymbol());
1111 auto size = std::get<1>(var.getInterval());
1112 fir::SequenceType::Shape shape(1, size);
1113 auto seqTy = fir::SequenceType::get(shape, i8Ty);
1114 mlir::Type refTy = builder.getRefType(seqTy);
1115 mlir::Value aggregateStore = builder.createConvert(loc, refTy, addr);
1116 insertAggregateStore(storeMap, var, aggregateStore);
1117 return;
1118 }
1119 // This is a local aggregate, allocate an anonymous block of memory.
1120 auto size = std::get<1>(var.getInterval());
1121 fir::SequenceType::Shape shape(1, size);
1122 auto seqTy = fir::SequenceType::get(shape, i8Ty);
1123 mlir::Value local =
1124 builder.allocateLocal(loc, seqTy, aggName, "", std::nullopt, std::nullopt,
1125 /*target=*/false);
1126 insertAggregateStore(storeMap, var, local);
1127 }
1128
1129 /// Cast an alias address (variable part of an equivalence) to fir.ptr so that
1130 /// the optimizer is conservative and avoids doing copy elision in assignment
1131 /// involving equivalenced variables.
1132 /// TODO: Represent the equivalence aliasing constraint in another way to avoid
1133 /// pessimizing array assignments involving equivalenced variables.
1134 static mlir::Value castAliasToPointer(fir::FirOpBuilder &builder,
1135 mlir::Location loc, mlir::Type aliasType,
1136 mlir::Value aliasAddr) {
1137 return builder.createConvert(loc, fir::PointerType::get(aliasType),
1138 aliasAddr);
1139 }
1140
1141 /// Instantiate a member of an equivalence. Compute its address in its
1142 /// aggregate storage and lower its attributes.
1143 static void instantiateAlias(Fortran::lower::AbstractConverter &converter,
1144 const Fortran::lower::pft::Variable &var,
1145 Fortran::lower::SymMap &symMap,
1146 Fortran::lower::AggregateStoreMap &storeMap) {
1147 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1148 assert(var.isAlias());
1149 const Fortran::semantics::Symbol &sym = var.getSymbol();
1150 const mlir::Location loc = genLocation(converter, sym);
1151 mlir::IndexType idxTy = builder.getIndexType();
1152 mlir::IntegerType i8Ty = builder.getIntegerType(8);
1153 mlir::Type i8Ptr = builder.getRefType(i8Ty);
1154 mlir::Type symType = converter.genType(sym);
1155 std::size_t off = sym.GetUltimate().offset() - var.getAliasOffset();
1156 mlir::Value storeAddr = getAggregateStore(storeMap, var);
1157 mlir::Value offset = builder.createIntegerConstant(loc, idxTy, off);
1158 mlir::Value bytePtr = builder.create<fir::CoordinateOp>(
1159 loc, i8Ptr, storeAddr, mlir::ValueRange{offset});
1160 mlir::Value typedPtr = castAliasToPointer(builder, loc, symType, bytePtr);
1161 Fortran::lower::StatementContext stmtCtx;
1162 mapSymbolAttributes(converter, var, symMap, stmtCtx, typedPtr);
1163 // Default initialization is possible for equivalence members: see
1164 // F2018 19.5.3.4. Note that if several equivalenced entities have
1165 // default initialization, they must have the same type, and the standard
1166 // allows the storage to be default initialized several times (this has
1167 // no consequences other than wasting some execution time). For now,
1168 // do not try optimizing this to single default initializations of
1169 // the equivalenced storages. Keep lowering simple.
1170 if (mustBeDefaultInitializedAtRuntime(var))
1171 Fortran::lower::defaultInitializeAtRuntime(converter, var.getSymbol(),
1172 symMap);
1173 }
1174
1175 //===--------------------------------------------------------------===//
1176 // COMMON blocks instantiation
1177 //===--------------------------------------------------------------===//
1178
1179 /// Does any member of the common block has an initializer ?
1180 static bool
1181 commonBlockHasInit(const Fortran::semantics::MutableSymbolVector &cmnBlkMems) {
1182 for (const Fortran::semantics::MutableSymbolRef &mem : cmnBlkMems) {
1183 if (const auto *memDet =
1184 mem->detailsIf<Fortran::semantics::ObjectEntityDetails>())
1185 if (memDet->init())
1186 return true;
1187 }
1188 return false;
1189 }
1190
1191 /// Build a tuple type for a common block based on the common block
1192 /// members and the common block size.
1193 /// This type is only needed to build common block initializers where
1194 /// the initial value is the collection of the member initial values.
1195 static mlir::TupleType getTypeOfCommonWithInit(
1196 Fortran::lower::AbstractConverter &converter,
1197 const Fortran::semantics::MutableSymbolVector &cmnBlkMems,
1198 std::size_t commonSize) {
1199 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1200 llvm::SmallVector<mlir::Type> members;
1201 std::size_t counter = 0;
1202 for (const Fortran::semantics::MutableSymbolRef &mem : cmnBlkMems) {
1203 if (const auto *memDet =
1204 mem->detailsIf<Fortran::semantics::ObjectEntityDetails>()) {
1205 if (mem->offset() > counter) {
1206 fir::SequenceType::Shape len = {
1207 static_cast<fir::SequenceType::Extent>(mem->offset() - counter)};
1208 mlir::IntegerType byteTy = builder.getIntegerType(8);
1209 auto memTy = fir::SequenceType::get(len, byteTy);
1210 members.push_back(memTy);
1211 counter = mem->offset();
1212 }
1213 if (memDet->init()) {
1214 mlir::Type memTy = converter.genType(*mem);
1215 members.push_back(memTy);
1216 counter = mem->offset() + mem->size();
1217 }
1218 }
1219 }
1220 if (counter < commonSize) {
1221 fir::SequenceType::Shape len = {
1222 static_cast<fir::SequenceType::Extent>(commonSize - counter)};
1223 mlir::IntegerType byteTy = builder.getIntegerType(8);
1224 auto memTy = fir::SequenceType::get(len, byteTy);
1225 members.push_back(memTy);
1226 }
1227 return mlir::TupleType::get(builder.getContext(), members);
1228 }
1229
1230 /// Common block members may have aliases. They are not in the common block
1231 /// member list from the symbol. We need to know about these aliases if they
1232 /// have initializer to generate the common initializer.
1233 /// This function takes care of adding aliases with initializer to the member
1234 /// list.
1235 static Fortran::semantics::MutableSymbolVector
1236 getCommonMembersWithInitAliases(const Fortran::semantics::Symbol &common) {
1237 const auto &commonDetails =
1238 common.get<Fortran::semantics::CommonBlockDetails>();
1239 auto members = commonDetails.objects();
1240
1241 // The number and size of equivalence and common is expected to be small, so
1242 // no effort is given to optimize this loop of complexity equivalenced
1243 // common members * common members
1244 for (const Fortran::semantics::EquivalenceSet &set :
1245 common.owner().equivalenceSets())
1246 for (const Fortran::semantics::EquivalenceObject &obj : set) {
1247 if (!obj.symbol.test(Fortran::semantics::Symbol::Flag::CompilerCreated)) {
1248 if (const auto &details =
1249 obj.symbol
1250 .detailsIf<Fortran::semantics::ObjectEntityDetails>()) {
1251 const Fortran::semantics::Symbol *com =
1252 FindCommonBlockContaining(obj.symbol);
1253 if (!details->init() || com != &common)
1254 continue;
1255 // This is an alias with an init that belongs to the list
1256 if (!llvm::is_contained(members, obj.symbol))
1257 members.emplace_back(obj.symbol);
1258 }
1259 }
1260 }
1261 return members;
1262 }
1263
1264 /// Return the fir::GlobalOp that was created of COMMON block \p common.
1265 /// It is an error if the fir::GlobalOp was not created before this is
1266 /// called (it cannot be created on the flight because it is not known here
1267 /// what mlir type the GlobalOp should have to satisfy all the
1268 /// appearances in the program).
1269 static fir::GlobalOp
1270 getCommonBlockGlobal(Fortran::lower::AbstractConverter &converter,
1271 const Fortran::semantics::Symbol &common) {
1272 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1273 std::string commonName = converter.mangleName(common);
1274 fir::GlobalOp global = builder.getNamedGlobal(commonName);
1275 // Common blocks are lowered before any subprograms to deal with common
1276 // whose size may not be the same in every subprograms.
1277 if (!global)
1278 fir::emitFatalError(converter.genLocation(common.name()),
1279 "COMMON block was not lowered before its usage");
1280 return global;
1281 }
1282
1283 /// Create the fir::GlobalOp for COMMON block \p common. If \p common has an
1284 /// initial value, it is not created yet. Instead, the common block list
1285 /// members is returned to later create the initial value in
1286 /// finalizeCommonBlockDefinition.
1287 static std::optional<std::tuple<
1288 fir::GlobalOp, Fortran::semantics::MutableSymbolVector, mlir::Location>>
1289 declareCommonBlock(Fortran::lower::AbstractConverter &converter,
1290 const Fortran::semantics::Symbol &common,
1291 std::size_t commonSize) {
1292 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1293 std::string commonName = converter.mangleName(common);
1294 fir::GlobalOp global = builder.getNamedGlobal(commonName);
1295 if (global)
1296 return std::nullopt;
1297 Fortran::semantics::MutableSymbolVector cmnBlkMems =
1298 getCommonMembersWithInitAliases(common);
1299 mlir::Location loc = converter.genLocation(common.name());
1300 mlir::StringAttr linkage = builder.createCommonLinkage();
1301 const auto *details =
1302 common.detailsIf<Fortran::semantics::CommonBlockDetails>();
1303 assert(details && "Expect CommonBlockDetails on the common symbol");
1304 if (!commonBlockHasInit(cmnBlkMems)) {
1305 // A COMMON block sans initializers is initialized to zero.
1306 // mlir::Vector types must have a strictly positive size, so at least
1307 // temporarily, force a zero size COMMON block to have one byte.
1308 const auto sz =
1309 static_cast<fir::SequenceType::Extent>(commonSize > 0 ? commonSize : 1);
1310 fir::SequenceType::Shape shape = {sz};
1311 mlir::IntegerType i8Ty = builder.getIntegerType(8);
1312 auto commonTy = fir::SequenceType::get(shape, i8Ty);
1313 auto vecTy = mlir::VectorType::get(sz, i8Ty);
1314 mlir::Attribute zero = builder.getIntegerAttr(i8Ty, 0);
1315 auto init = mlir::DenseElementsAttr::get(vecTy, llvm::ArrayRef(zero));
1316 global = builder.createGlobal(loc, commonTy, commonName, linkage, init);
1317 global.setAlignment(details->alignment());
1318 // No need to add any initial value later.
1319 return std::nullopt;
1320 }
1321 // COMMON block with initializer (note that initialized blank common are
1322 // accepted as an extension by semantics). Sort members by offset before
1323 // generating the type and initializer.
1324 std::sort(cmnBlkMems.begin(), cmnBlkMems.end(),
1325 [](auto &s1, auto &s2) { return s1->offset() < s2->offset(); });
1326 mlir::TupleType commonTy =
1327 getTypeOfCommonWithInit(converter, cmnBlkMems, commonSize);
1328 // Create the global object, the initial value will be added later.
1329 global = builder.createGlobal(loc, commonTy, commonName);
1330 global.setAlignment(details->alignment());
1331 return std::make_tuple(global, std::move(cmnBlkMems), loc);
1332 }
1333
1334 /// Add initial value to a COMMON block fir::GlobalOp \p global given the list
1335 /// \p cmnBlkMems of the common block member symbols that contains symbols with
1336 /// an initial value.
1337 static void finalizeCommonBlockDefinition(
1338 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
1339 fir::GlobalOp global,
1340 const Fortran::semantics::MutableSymbolVector &cmnBlkMems) {
1341 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1342 mlir::TupleType commonTy = mlir::cast<mlir::TupleType>(global.getType());
1343 auto initFunc = [&](fir::FirOpBuilder &builder) {
1344 mlir::IndexType idxTy = builder.getIndexType();
1345 mlir::Value cb = builder.create<fir::ZeroOp>(loc, commonTy);
1346 unsigned tupIdx = 0;
1347 std::size_t offset = 0;
1348 LLVM_DEBUG(llvm::dbgs() << "block {\n");
1349 for (const Fortran::semantics::MutableSymbolRef &mem : cmnBlkMems) {
1350 if (const auto *memDet =
1351 mem->detailsIf<Fortran::semantics::ObjectEntityDetails>()) {
1352 if (mem->offset() > offset) {
1353 ++tupIdx;
1354 offset = mem->offset();
1355 }
1356 if (memDet->init()) {
1357 LLVM_DEBUG(llvm::dbgs()
1358 << "offset: " << mem->offset() << " is " << *mem << '\n');
1359 Fortran::lower::StatementContext stmtCtx;
1360 auto initExpr = memDet->init().value();
1361 fir::ExtendedValue initVal =
1362 Fortran::semantics::IsPointer(*mem)
1363 ? Fortran::lower::genInitialDataTarget(
1364 converter, loc, converter.genType(*mem), initExpr)
1365 : genInitializerExprValue(converter, loc, initExpr, stmtCtx);
1366 mlir::IntegerAttr offVal = builder.getIntegerAttr(idxTy, tupIdx);
1367 mlir::Value castVal = builder.createConvert(
1368 loc, commonTy.getType(tupIdx), fir::getBase(initVal));
1369 cb = builder.create<fir::InsertValueOp>(loc, commonTy, cb, castVal,
1370 builder.getArrayAttr(offVal));
1371 ++tupIdx;
1372 offset = mem->offset() + mem->size();
1373 }
1374 }
1375 }
1376 LLVM_DEBUG(llvm::dbgs() << "}\n");
1377 builder.create<fir::HasValueOp>(loc, cb);
1378 };
1379 Fortran::lower::createGlobalInitialization(builder, global, initFunc);
1380 }
1381
1382 void Fortran::lower::defineCommonBlocks(
1383 Fortran::lower::AbstractConverter &converter,
1384 const Fortran::semantics::CommonBlockList &commonBlocks) {
1385 // Common blocks may depend on another common block address (if they contain
1386 // pointers with initial targets). To cover this case, create all common block
1387 // fir::Global before creating the initial values (if any).
1388 std::vector<std::tuple<fir::GlobalOp, Fortran::semantics::MutableSymbolVector,
1389 mlir::Location>>
1390 delayedInitializations;
1391 for (const auto &[common, size] : commonBlocks)
1392 if (auto delayedInit = declareCommonBlock(converter, common, size))
1393 delayedInitializations.emplace_back(std::move(*delayedInit));
1394 for (auto &[global, cmnBlkMems, loc] : delayedInitializations)
1395 finalizeCommonBlockDefinition(loc, converter, global, cmnBlkMems);
1396 }
1397
1398 mlir::Value Fortran::lower::genCommonBlockMember(
1399 Fortran::lower::AbstractConverter &converter, mlir::Location loc,
1400 const Fortran::semantics::Symbol &sym, mlir::Value commonValue) {
1401 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1402
1403 std::size_t byteOffset = sym.GetUltimate().offset();
1404 mlir::IntegerType i8Ty = builder.getIntegerType(8);
1405 mlir::Type i8Ptr = builder.getRefType(i8Ty);
1406 mlir::Type seqTy = builder.getRefType(builder.getVarLenSeqTy(i8Ty));
1407 mlir::Value base = builder.createConvert(loc, seqTy, commonValue);
1408
1409 mlir::Value offs =
1410 builder.createIntegerConstant(loc, builder.getIndexType(), byteOffset);
1411 mlir::Value varAddr = builder.create<fir::CoordinateOp>(
1412 loc, i8Ptr, base, mlir::ValueRange{offs});
1413 mlir::Type symType = converter.genType(sym);
1414
1415 return Fortran::semantics::FindEquivalenceSet(sym) != nullptr
1416 ? castAliasToPointer(builder, loc, symType, varAddr)
1417 : builder.createConvert(loc, builder.getRefType(symType), varAddr);
1418 }
1419
1420 /// The COMMON block is a global structure. `var` will be at some offset
1421 /// within the COMMON block. Adds the address of `var` (COMMON + offset) to
1422 /// the symbol map.
1423 static void instantiateCommon(Fortran::lower::AbstractConverter &converter,
1424 const Fortran::semantics::Symbol &common,
1425 const Fortran::lower::pft::Variable &var,
1426 Fortran::lower::SymMap &symMap) {
1427 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1428 const Fortran::semantics::Symbol &varSym = var.getSymbol();
1429 mlir::Location loc = converter.genLocation(varSym.name());
1430
1431 mlir::Value commonAddr;
1432 if (Fortran::lower::SymbolBox symBox = symMap.lookupSymbol(common))
1433 commonAddr = symBox.getAddr();
1434 if (!commonAddr) {
1435 // introduce a local AddrOf and add it to the map
1436 fir::GlobalOp global = getCommonBlockGlobal(converter, common);
1437 commonAddr = builder.create<fir::AddrOfOp>(loc, global.resultType(),
1438 global.getSymbol());
1439
1440 symMap.addSymbol(common, commonAddr);
1441 }
1442
1443 mlir::Value local = genCommonBlockMember(converter, loc, varSym, commonAddr);
1444 Fortran::lower::StatementContext stmtCtx;
1445 mapSymbolAttributes(converter, var, symMap, stmtCtx, local);
1446 }
1447
1448 //===--------------------------------------------------------------===//
1449 // Lower Variables specification expressions and attributes
1450 //===--------------------------------------------------------------===//
1451
1452 /// Helper to decide if a dummy argument must be tracked in an BoxValue.
1453 static bool lowerToBoxValue(const Fortran::semantics::Symbol &sym,
1454 mlir::Value dummyArg,
1455 Fortran::lower::AbstractConverter &converter) {
1456 // Only dummy arguments coming as fir.box can be tracked in an BoxValue.
1457 if (!dummyArg || !mlir::isa<fir::BaseBoxType>(dummyArg.getType()))
1458 return false;
1459 // Non contiguous arrays must be tracked in an BoxValue.
1460 if (sym.Rank() > 0 && !Fortran::evaluate::IsSimplyContiguous(
1461 sym, converter.getFoldingContext()))
1462 return true;
1463 // Assumed rank and optional fir.box cannot yet be read while lowering the
1464 // specifications.
1465 if (Fortran::evaluate::IsAssumedRank(sym) ||
1466 Fortran::semantics::IsOptional(sym))
1467 return true;
1468 // Polymorphic entity should be tracked through a fir.box that has the
1469 // dynamic type info.
1470 if (const Fortran::semantics::DeclTypeSpec *type = sym.GetType())
1471 if (type->IsPolymorphic())
1472 return true;
1473 return false;
1474 }
1475
1476 /// Compute extent from lower and upper bound.
1477 static mlir::Value computeExtent(fir::FirOpBuilder &builder, mlir::Location loc,
1478 mlir::Value lb, mlir::Value ub) {
1479 mlir::IndexType idxTy = builder.getIndexType();
1480 // Let the folder deal with the common `ub - <const> + 1` case.
1481 auto diff = builder.create<mlir::arith::SubIOp>(loc, idxTy, ub, lb);
1482 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
1483 auto rawExtent = builder.create<mlir::arith::AddIOp>(loc, idxTy, diff, one);
1484 return fir::factory::genMaxWithZero(builder, loc, rawExtent);
1485 }
1486
1487 /// Lower explicit lower bounds into \p result. Does nothing if this is not an
1488 /// array, or if the lower bounds are deferred, or all implicit or one.
1489 static void lowerExplicitLowerBounds(
1490 Fortran::lower::AbstractConverter &converter, mlir::Location loc,
1491 const Fortran::lower::BoxAnalyzer &box,
1492 llvm::SmallVectorImpl<mlir::Value> &result, Fortran::lower::SymMap &symMap,
1493 Fortran::lower::StatementContext &stmtCtx) {
1494 if (!box.isArray() || box.lboundIsAllOnes())
1495 return;
1496 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1497 mlir::IndexType idxTy = builder.getIndexType();
1498 if (box.isStaticArray()) {
1499 for (int64_t lb : box.staticLBound())
1500 result.emplace_back(builder.createIntegerConstant(loc, idxTy, lb));
1501 return;
1502 }
1503 for (const Fortran::semantics::ShapeSpec *spec : box.dynamicBound()) {
1504 if (auto low = spec->lbound().GetExplicit()) {
1505 auto expr = Fortran::lower::SomeExpr{*low};
1506 mlir::Value lb = builder.createConvert(
1507 loc, idxTy, genScalarValue(converter, loc, expr, symMap, stmtCtx));
1508 result.emplace_back(lb);
1509 }
1510 }
1511 assert(result.empty() || result.size() == box.dynamicBound().size());
1512 }
1513
1514 /// Return -1 for the last dimension extent/upper bound of assumed-size arrays.
1515 /// This value is required to fulfill the requirements for assumed-rank
1516 /// associated with assumed-size (see for instance UBOUND in 16.9.196, and
1517 /// CFI_desc_t requirements in 18.5.3 point 5.).
1518 static mlir::Value getAssumedSizeExtent(mlir::Location loc,
1519 fir::FirOpBuilder &builder) {
1520 return builder.createMinusOneInteger(loc, builder.getIndexType());
1521 }
1522
1523 /// Lower explicit extents into \p result if this is an explicit-shape or
1524 /// assumed-size array. Does nothing if this is not an explicit-shape or
1525 /// assumed-size array.
1526 static void
1527 lowerExplicitExtents(Fortran::lower::AbstractConverter &converter,
1528 mlir::Location loc, const Fortran::lower::BoxAnalyzer &box,
1529 llvm::SmallVectorImpl<mlir::Value> &lowerBounds,
1530 llvm::SmallVectorImpl<mlir::Value> &result,
1531 Fortran::lower::SymMap &symMap,
1532 Fortran::lower::StatementContext &stmtCtx) {
1533 if (!box.isArray())
1534 return;
1535 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1536 mlir::IndexType idxTy = builder.getIndexType();
1537 if (box.isStaticArray()) {
1538 for (int64_t extent : box.staticShape())
1539 result.emplace_back(builder.createIntegerConstant(loc, idxTy, extent));
1540 return;
1541 }
1542 for (const auto &spec : llvm::enumerate(box.dynamicBound())) {
1543 if (auto up = spec.value()->ubound().GetExplicit()) {
1544 auto expr = Fortran::lower::SomeExpr{*up};
1545 mlir::Value ub = builder.createConvert(
1546 loc, idxTy, genScalarValue(converter, loc, expr, symMap, stmtCtx));
1547 if (lowerBounds.empty())
1548 result.emplace_back(fir::factory::genMaxWithZero(builder, loc, ub));
1549 else
1550 result.emplace_back(
1551 computeExtent(builder, loc, lowerBounds[spec.index()], ub));
1552 } else if (spec.value()->ubound().isStar()) {
1553 result.emplace_back(getAssumedSizeExtent(loc, builder));
1554 }
1555 }
1556 assert(result.empty() || result.size() == box.dynamicBound().size());
1557 }
1558
1559 /// Lower explicit character length if any. Return empty mlir::Value if no
1560 /// explicit length.
1561 static mlir::Value
1562 lowerExplicitCharLen(Fortran::lower::AbstractConverter &converter,
1563 mlir::Location loc, const Fortran::lower::BoxAnalyzer &box,
1564 Fortran::lower::SymMap &symMap,
1565 Fortran::lower::StatementContext &stmtCtx) {
1566 if (!box.isChar())
1567 return mlir::Value{};
1568 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1569 mlir::Type lenTy = builder.getCharacterLengthType();
1570 if (std::optional<int64_t> len = box.getCharLenConst())
1571 return builder.createIntegerConstant(loc, lenTy, *len);
1572 if (std::optional<Fortran::lower::SomeExpr> lenExpr = box.getCharLenExpr())
1573 // If the length expression is negative, the length is zero. See F2018
1574 // 7.4.4.2 point 5.
1575 return fir::factory::genMaxWithZero(
1576 builder, loc,
1577 genScalarValue(converter, loc, *lenExpr, symMap, stmtCtx));
1578 return mlir::Value{};
1579 }
1580
1581 /// Assumed size arrays last extent is -1 in the front end.
1582 static mlir::Value genExtentValue(fir::FirOpBuilder &builder,
1583 mlir::Location loc, mlir::Type idxTy,
1584 long frontEndExtent) {
1585 if (frontEndExtent >= 0)
1586 return builder.createIntegerConstant(loc, idxTy, frontEndExtent);
1587 return getAssumedSizeExtent(loc, builder);
1588 }
1589
1590 /// If a symbol is an array, it may have been declared with unknown extent
1591 /// parameters (e.g., `*`), but if it has an initial value then the actual size
1592 /// may be available from the initial array value's type.
1593 inline static llvm::SmallVector<std::int64_t>
1594 recoverShapeVector(llvm::ArrayRef<std::int64_t> shapeVec, mlir::Value initVal) {
1595 llvm::SmallVector<std::int64_t> result;
1596 if (initVal) {
1597 if (auto seqTy = fir::unwrapUntilSeqType(initVal.getType())) {
1598 for (auto [fst, snd] : llvm::zip(shapeVec, seqTy.getShape()))
1599 result.push_back(fst == fir::SequenceType::getUnknownExtent() ? snd
1600 : fst);
1601 return result;
1602 }
1603 }
1604 result.assign(shapeVec.begin(), shapeVec.end());
1605 return result;
1606 }
1607
1608 fir::FortranVariableFlagsAttr Fortran::lower::translateSymbolAttributes(
1609 mlir::MLIRContext *mlirContext, const Fortran::semantics::Symbol &sym,
1610 fir::FortranVariableFlagsEnum extraFlags) {
1611 fir::FortranVariableFlagsEnum flags = extraFlags;
1612 if (sym.test(Fortran::semantics::Symbol::Flag::CrayPointee)) {
1613 // CrayPointee are represented as pointers.
1614 flags = flags | fir::FortranVariableFlagsEnum::pointer;
1615 return fir::FortranVariableFlagsAttr::get(mlirContext, flags);
1616 }
1617 const auto &attrs = sym.attrs();
1618 if (attrs.test(Fortran::semantics::Attr::ALLOCATABLE))
1619 flags = flags | fir::FortranVariableFlagsEnum::allocatable;
1620 if (attrs.test(Fortran::semantics::Attr::ASYNCHRONOUS))
1621 flags = flags | fir::FortranVariableFlagsEnum::asynchronous;
1622 if (attrs.test(Fortran::semantics::Attr::BIND_C))
1623 flags = flags | fir::FortranVariableFlagsEnum::bind_c;
1624 if (attrs.test(Fortran::semantics::Attr::CONTIGUOUS))
1625 flags = flags | fir::FortranVariableFlagsEnum::contiguous;
1626 if (attrs.test(Fortran::semantics::Attr::INTENT_IN))
1627 flags = flags | fir::FortranVariableFlagsEnum::intent_in;
1628 if (attrs.test(Fortran::semantics::Attr::INTENT_INOUT))
1629 flags = flags | fir::FortranVariableFlagsEnum::intent_inout;
1630 if (attrs.test(Fortran::semantics::Attr::INTENT_OUT))
1631 flags = flags | fir::FortranVariableFlagsEnum::intent_out;
1632 if (attrs.test(Fortran::semantics::Attr::OPTIONAL))
1633 flags = flags | fir::FortranVariableFlagsEnum::optional;
1634 if (attrs.test(Fortran::semantics::Attr::PARAMETER))
1635 flags = flags | fir::FortranVariableFlagsEnum::parameter;
1636 if (attrs.test(Fortran::semantics::Attr::POINTER))
1637 flags = flags | fir::FortranVariableFlagsEnum::pointer;
1638 if (attrs.test(Fortran::semantics::Attr::TARGET))
1639 flags = flags | fir::FortranVariableFlagsEnum::target;
1640 if (attrs.test(Fortran::semantics::Attr::VALUE))
1641 flags = flags | fir::FortranVariableFlagsEnum::value;
1642 if (attrs.test(Fortran::semantics::Attr::VOLATILE))
1643 flags = flags | fir::FortranVariableFlagsEnum::fortran_volatile;
1644 if (flags == fir::FortranVariableFlagsEnum::None)
1645 return {};
1646 return fir::FortranVariableFlagsAttr::get(mlirContext, flags);
1647 }
1648
1649 cuf::DataAttributeAttr Fortran::lower::translateSymbolCUFDataAttribute(
1650 mlir::MLIRContext *mlirContext, const Fortran::semantics::Symbol &sym) {
1651 std::optional<Fortran::common::CUDADataAttr> cudaAttr =
1652 Fortran::semantics::GetCUDADataAttr(&sym.GetUltimate());
1653 return cuf::getDataAttribute(mlirContext, cudaAttr);
1654 }
1655
1656 /// Map a symbol to its FIR address and evaluated specification expressions.
1657 /// Not for symbols lowered to fir.box.
1658 /// Will optionally create fir.declare.
1659 static void genDeclareSymbol(Fortran::lower::AbstractConverter &converter,
1660 Fortran::lower::SymMap &symMap,
1661 const Fortran::semantics::Symbol &sym,
1662 mlir::Value base, mlir::Value len = {},
1663 llvm::ArrayRef<mlir::Value> shape = std::nullopt,
1664 llvm::ArrayRef<mlir::Value> lbounds = std::nullopt,
1665 bool force = false) {
1666 // In HLFIR, procedure dummy symbols are not added with an hlfir.declare
1667 // because they are "values", and hlfir.declare is intended for variables. It
1668 // would add too much complexity to hlfir.declare to support this case, and
1669 // this would bring very little (the only point being debug info, that are not
1670 // yet emitted) since alias analysis is meaningless for those.
1671 // Commonblock names are not variables, but in some lowerings (like OpenMP) it
1672 // is useful to maintain the address of the commonblock in an MLIR value and
1673 // query it. hlfir.declare need not be created for these.
1674 if (converter.getLoweringOptions().getLowerToHighLevelFIR() &&
1675 (!Fortran::semantics::IsProcedure(sym) ||
1676 Fortran::semantics::IsPointer(sym)) &&
1677 !sym.detailsIf<Fortran::semantics::CommonBlockDetails>()) {
1678 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1679 const mlir::Location loc = genLocation(converter, sym);
1680 mlir::Value shapeOrShift;
1681 if (!shape.empty() && !lbounds.empty())
1682 shapeOrShift = builder.genShape(loc, lbounds, shape);
1683 else if (!shape.empty())
1684 shapeOrShift = builder.genShape(loc, shape);
1685 else if (!lbounds.empty())
1686 shapeOrShift = builder.genShift(loc, lbounds);
1687 llvm::SmallVector<mlir::Value> lenParams;
1688 if (len)
1689 lenParams.emplace_back(len);
1690 auto name = converter.mangleName(sym);
1691 fir::FortranVariableFlagsAttr attributes =
1692 Fortran::lower::translateSymbolAttributes(builder.getContext(), sym);
1693 cuf::DataAttributeAttr dataAttr =
1694 Fortran::lower::translateSymbolCUFDataAttribute(builder.getContext(),
1695 sym);
1696
1697 if (sym.test(Fortran::semantics::Symbol::Flag::CrayPointee)) {
1698 mlir::Type ptrBoxType =
1699 Fortran::lower::getCrayPointeeBoxType(base.getType());
1700 mlir::Value boxAlloc = builder.createTemporary(loc, ptrBoxType);
1701
1702 // Declare a local pointer variable.
1703 auto newBase = builder.create<hlfir::DeclareOp>(
1704 loc, boxAlloc, name, /*shape=*/nullptr, lenParams,
1705 /*dummy_scope=*/nullptr, attributes);
1706 mlir::Value nullAddr = builder.createNullConstant(
1707 loc, llvm::cast<fir::BaseBoxType>(ptrBoxType).getEleTy());
1708
1709 // If the element type is known-length character, then
1710 // EmboxOp does not need the length parameters.
1711 if (auto charType = mlir::dyn_cast<fir::CharacterType>(
1712 hlfir::getFortranElementType(base.getType())))
1713 if (!charType.hasDynamicLen())
1714 lenParams.clear();
1715
1716 // Inherit the shape (and maybe length parameters) from the pointee
1717 // declaration.
1718 mlir::Value initVal =
1719 builder.create<fir::EmboxOp>(loc, ptrBoxType, nullAddr, shapeOrShift,
1720 /*slice=*/nullptr, lenParams);
1721 builder.create<fir::StoreOp>(loc, initVal, newBase.getBase());
1722
1723 // Any reference to the pointee is going to be using the pointer
1724 // box from now on. The base_addr of the descriptor must be updated
1725 // to hold the value of the Cray pointer at the point of the pointee
1726 // access.
1727 // Note that the same Cray pointer may be associated with
1728 // multiple pointees and each of them has its own descriptor.
1729 symMap.addVariableDefinition(sym, newBase, force);
1730 return;
1731 }
1732 mlir::Value dummyScope;
1733 if (converter.isRegisteredDummySymbol(sym))
1734 dummyScope = converter.dummyArgsScopeValue();
1735 auto newBase = builder.create<hlfir::DeclareOp>(
1736 loc, base, name, shapeOrShift, lenParams, dummyScope, attributes,
1737 dataAttr);
1738 symMap.addVariableDefinition(sym, newBase, force);
1739 return;
1740 }
1741
1742 if (len) {
1743 if (!shape.empty()) {
1744 if (!lbounds.empty())
1745 symMap.addCharSymbolWithBounds(sym, base, len, shape, lbounds, force);
1746 else
1747 symMap.addCharSymbolWithShape(sym, base, len, shape, force);
1748 } else {
1749 symMap.addCharSymbol(sym, base, len, force);
1750 }
1751 } else {
1752 if (!shape.empty()) {
1753 if (!lbounds.empty())
1754 symMap.addSymbolWithBounds(sym, base, shape, lbounds, force);
1755 else
1756 symMap.addSymbolWithShape(sym, base, shape, force);
1757 } else {
1758 symMap.addSymbol(sym, base, force);
1759 }
1760 }
1761 }
1762
1763 /// Map a symbol to its FIR address and evaluated specification expressions
1764 /// provided as a fir::ExtendedValue. Will optionally create fir.declare.
1765 void Fortran::lower::genDeclareSymbol(
1766 Fortran::lower::AbstractConverter &converter,
1767 Fortran::lower::SymMap &symMap, const Fortran::semantics::Symbol &sym,
1768 const fir::ExtendedValue &exv, fir::FortranVariableFlagsEnum extraFlags,
1769 bool force) {
1770 if (converter.getLoweringOptions().getLowerToHighLevelFIR() &&
1771 (!Fortran::semantics::IsProcedure(sym) ||
1772 Fortran::semantics::IsPointer(sym)) &&
1773 !sym.detailsIf<Fortran::semantics::CommonBlockDetails>()) {
1774 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1775 const mlir::Location loc = genLocation(converter, sym);
1776 // FIXME: Using the ultimate symbol for translating symbol attributes will
1777 // lead to situations where the VOLATILE/ASYNCHRONOUS attributes are not
1778 // propagated to the hlfir.declare (these attributes can be added when
1779 // using module variables).
1780 fir::FortranVariableFlagsAttr attributes =
1781 Fortran::lower::translateSymbolAttributes(
1782 builder.getContext(), sym.GetUltimate(), extraFlags);
1783 cuf::DataAttributeAttr dataAttr =
1784 Fortran::lower::translateSymbolCUFDataAttribute(builder.getContext(),
1785 sym.GetUltimate());
1786 auto name = converter.mangleName(sym);
1787 mlir::Value dummyScope;
1788 if (converter.isRegisteredDummySymbol(sym))
1789 dummyScope = converter.dummyArgsScopeValue();
1790 hlfir::EntityWithAttributes declare = hlfir::genDeclare(
1791 loc, builder, exv, name, attributes, dummyScope, dataAttr);
1792 symMap.addVariableDefinition(sym, declare.getIfVariableInterface(), force);
1793 return;
1794 }
1795 symMap.addSymbol(sym, exv, force);
1796 }
1797
1798 /// Map an allocatable or pointer symbol to its FIR address and evaluated
1799 /// specification expressions. Will optionally create fir.declare.
1800 static void
1801 genAllocatableOrPointerDeclare(Fortran::lower::AbstractConverter &converter,
1802 Fortran::lower::SymMap &symMap,
1803 const Fortran::semantics::Symbol &sym,
1804 fir::MutableBoxValue box, bool force = false) {
1805 if (!converter.getLoweringOptions().getLowerToHighLevelFIR()) {
1806 symMap.addAllocatableOrPointer(sym, box, force);
1807 return;
1808 }
1809 assert(!box.isDescribedByVariables() &&
1810 "HLFIR alloctables/pointers must be fir.ref<fir.box>");
1811 mlir::Value base = box.getAddr();
1812 mlir::Value explictLength;
1813 if (box.hasNonDeferredLenParams()) {
1814 if (!box.isCharacter())
1815 TODO(genLocation(converter, sym),
1816 "Pointer or Allocatable parametrized derived type");
1817 explictLength = box.nonDeferredLenParams()[0];
1818 }
1819 genDeclareSymbol(converter, symMap, sym, base, explictLength,
1820 /*shape=*/std::nullopt,
1821 /*lbounds=*/std::nullopt, force);
1822 }
1823
1824 /// Map a procedure pointer
1825 static void genProcPointer(Fortran::lower::AbstractConverter &converter,
1826 Fortran::lower::SymMap &symMap,
1827 const Fortran::semantics::Symbol &sym,
1828 mlir::Value addr, bool force = false) {
1829 genDeclareSymbol(converter, symMap, sym, addr, mlir::Value{},
1830 /*shape=*/std::nullopt,
1831 /*lbounds=*/std::nullopt, force);
1832 }
1833
1834 /// Map a symbol represented with a runtime descriptor to its FIR fir.box and
1835 /// evaluated specification expressions. Will optionally create fir.declare.
1836 static void genBoxDeclare(Fortran::lower::AbstractConverter &converter,
1837 Fortran::lower::SymMap &symMap,
1838 const Fortran::semantics::Symbol &sym,
1839 mlir::Value box, llvm::ArrayRef<mlir::Value> lbounds,
1840 llvm::ArrayRef<mlir::Value> explicitParams,
1841 llvm::ArrayRef<mlir::Value> explicitExtents,
1842 bool replace = false) {
1843 if (converter.getLoweringOptions().getLowerToHighLevelFIR()) {
1844 fir::BoxValue boxValue{box, lbounds, explicitParams, explicitExtents};
1845 Fortran::lower::genDeclareSymbol(
1846 converter, symMap, sym, std::move(boxValue),
1847 fir::FortranVariableFlagsEnum::None, replace);
1848 return;
1849 }
1850 symMap.addBoxSymbol(sym, box, lbounds, explicitParams, explicitExtents,
1851 replace);
1852 }
1853
1854 /// Lower specification expressions and attributes of variable \p var and
1855 /// add it to the symbol map. For a global or an alias, the address must be
1856 /// pre-computed and provided in \p preAlloc. A dummy argument for the current
1857 /// entry point has already been mapped to an mlir block argument in
1858 /// mapDummiesAndResults. Its mapping may be updated here.
1859 void Fortran::lower::mapSymbolAttributes(
1860 AbstractConverter &converter, const Fortran::lower::pft::Variable &var,
1861 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx,
1862 mlir::Value preAlloc) {
1863 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1864 const Fortran::semantics::Symbol &sym = var.getSymbol();
1865 const mlir::Location loc = genLocation(converter, sym);
1866 mlir::IndexType idxTy = builder.getIndexType();
1867 const bool isDeclaredDummy = Fortran::semantics::IsDummy(sym);
1868 // An active dummy from the current entry point.
1869 const bool isDummy = isDeclaredDummy && symMap.lookupSymbol(sym).getAddr();
1870 // An unused dummy from another entry point.
1871 const bool isUnusedEntryDummy = isDeclaredDummy && !isDummy;
1872 const bool isResult = Fortran::semantics::IsFunctionResult(sym);
1873 const bool replace = isDummy || isResult;
1874 fir::factory::CharacterExprHelper charHelp{builder, loc};
1875
1876 if (Fortran::semantics::IsProcedure(sym)) {
1877 if (isUnusedEntryDummy) {
1878 // Additional discussion below.
1879 mlir::Type dummyProcType =
1880 Fortran::lower::getDummyProcedureType(sym, converter);
1881 mlir::Value undefOp = builder.create<fir::UndefOp>(loc, dummyProcType);
1882
1883 Fortran::lower::genDeclareSymbol(converter, symMap, sym, undefOp);
1884 }
1885
1886 // Procedure pointer.
1887 if (Fortran::semantics::IsPointer(sym)) {
1888 // global
1889 mlir::Value boxAlloc = preAlloc;
1890 // dummy or passed result
1891 if (!boxAlloc)
1892 if (Fortran::lower::SymbolBox symbox = symMap.lookupSymbol(sym))
1893 boxAlloc = symbox.getAddr();
1894 // local
1895 if (!boxAlloc)
1896 boxAlloc = createNewLocal(converter, loc, var, preAlloc);
1897 genProcPointer(converter, symMap, sym, boxAlloc, replace);
1898 }
1899 return;
1900 }
1901
1902 const bool isAssumedRank = Fortran::evaluate::IsAssumedRank(sym);
1903 if (isAssumedRank && !allowAssumedRank)
1904 TODO(loc, "assumed-rank variable in procedure implemented in Fortran");
1905
1906 Fortran::lower::BoxAnalyzer ba;
1907 ba.analyze(sym);
1908
1909 // First deal with pointers and allocatables, because their handling here
1910 // is the same regardless of their rank.
1911 if (Fortran::semantics::IsAllocatableOrPointer(sym)) {
1912 // Get address of fir.box describing the entity.
1913 // global
1914 mlir::Value boxAlloc = preAlloc;
1915 // dummy or passed result
1916 if (!boxAlloc)
1917 if (Fortran::lower::SymbolBox symbox = symMap.lookupSymbol(sym))
1918 boxAlloc = symbox.getAddr();
1919 assert((boxAlloc || !isAssumedRank) && "assumed-ranks cannot be local");
1920 // local
1921 if (!boxAlloc)
1922 boxAlloc = createNewLocal(converter, loc, var, preAlloc);
1923 // Lower non deferred parameters.
1924 llvm::SmallVector<mlir::Value> nonDeferredLenParams;
1925 if (ba.isChar()) {
1926 if (mlir::Value len =
1927 lowerExplicitCharLen(converter, loc, ba, symMap, stmtCtx))
1928 nonDeferredLenParams.push_back(len);
1929 else if (Fortran::semantics::IsAssumedLengthCharacter(sym))
1930 nonDeferredLenParams.push_back(
1931 Fortran::lower::getAssumedCharAllocatableOrPointerLen(
1932 builder, loc, sym, boxAlloc));
1933 } else if (const Fortran::semantics::DeclTypeSpec *declTy = sym.GetType()) {
1934 if (const Fortran::semantics::DerivedTypeSpec *derived =
1935 declTy->AsDerived())
1936 if (Fortran::semantics::CountLenParameters(*derived) != 0)
1937 TODO(loc,
1938 "derived type allocatable or pointer with length parameters");
1939 }
1940 fir::MutableBoxValue box = Fortran::lower::createMutableBox(
1941 converter, loc, var, boxAlloc, nonDeferredLenParams,
1942 /*alwaysUseBox=*/
1943 converter.getLoweringOptions().getLowerToHighLevelFIR());
1944 genAllocatableOrPointerDeclare(converter, symMap, var.getSymbol(), box,
1945 replace);
1946 return;
1947 }
1948
1949 if (isDummy) {
1950 mlir::Value dummyArg = symMap.lookupSymbol(sym).getAddr();
1951 if (lowerToBoxValue(sym, dummyArg, converter)) {
1952 llvm::SmallVector<mlir::Value> lbounds;
1953 llvm::SmallVector<mlir::Value> explicitExtents;
1954 llvm::SmallVector<mlir::Value> explicitParams;
1955 // Lower lower bounds, explicit type parameters and explicit
1956 // extents if any.
1957 if (ba.isChar()) {
1958 if (mlir::Value len =
1959 lowerExplicitCharLen(converter, loc, ba, symMap, stmtCtx))
1960 explicitParams.push_back(len);
1961 if (!isAssumedRank && sym.Rank() == 0) {
1962 // Do not keep scalar characters as fir.box (even when optional).
1963 // Lowering and FIR is not meant to deal with scalar characters as
1964 // fir.box outside of calls.
1965 auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(dummyArg.getType());
1966 mlir::Type refTy = builder.getRefType(boxTy.getEleTy());
1967 mlir::Type lenType = builder.getCharacterLengthType();
1968 mlir::Value addr, len;
1969 if (Fortran::semantics::IsOptional(sym)) {
1970 auto isPresent = builder.create<fir::IsPresentOp>(
1971 loc, builder.getI1Type(), dummyArg);
1972 auto addrAndLen =
1973 builder
1974 .genIfOp(loc, {refTy, lenType}, isPresent,
1975 /*withElseRegion=*/true)
1976 .genThen([&]() {
1977 mlir::Value readAddr =
1978 builder.create<fir::BoxAddrOp>(loc, refTy, dummyArg);
1979 mlir::Value readLength =
1980 charHelp.readLengthFromBox(dummyArg);
1981 builder.create<fir::ResultOp>(
1982 loc, mlir::ValueRange{readAddr, readLength});
1983 })
1984 .genElse([&] {
1985 mlir::Value readAddr = builder.genAbsentOp(loc, refTy);
1986 mlir::Value readLength =
1987 fir::factory::createZeroValue(builder, loc, lenType);
1988 builder.create<fir::ResultOp>(
1989 loc, mlir::ValueRange{readAddr, readLength});
1990 })
1991 .getResults();
1992 addr = addrAndLen[0];
1993 len = addrAndLen[1];
1994 } else {
1995 addr = builder.create<fir::BoxAddrOp>(loc, refTy, dummyArg);
1996 len = charHelp.readLengthFromBox(dummyArg);
1997 }
1998 if (!explicitParams.empty())
1999 len = explicitParams[0];
2000 ::genDeclareSymbol(converter, symMap, sym, addr, len, /*extents=*/{},
2001 /*lbounds=*/{}, replace);
2002 return;
2003 }
2004 }
2005 // TODO: derived type length parameters.
2006 if (!isAssumedRank) {
2007 lowerExplicitLowerBounds(converter, loc, ba, lbounds, symMap, stmtCtx);
2008 lowerExplicitExtents(converter, loc, ba, lbounds, explicitExtents,
2009 symMap, stmtCtx);
2010 }
2011 genBoxDeclare(converter, symMap, sym, dummyArg, lbounds, explicitParams,
2012 explicitExtents, replace);
2013 return;
2014 }
2015 }
2016
2017 // A dummy from another entry point that is not declared in the current
2018 // entry point requires a skeleton definition. Most such "unused" dummies
2019 // will not survive into final generated code, but some will. It is illegal
2020 // to reference one at run time if it does. Such a dummy is mapped to a
2021 // value in one of three ways:
2022 //
2023 // - Generate a fir::UndefOp value. This is lightweight, easy to clean up,
2024 // and often valid, but it may fail for a dummy with dynamic bounds,
2025 // or a dummy used to define another dummy. Information to distinguish
2026 // valid cases is not generally available here, with the exception of
2027 // dummy procedures. See the first function exit above.
2028 //
2029 // - Allocate an uninitialized stack slot. This is an intermediate-weight
2030 // solution that is harder to clean up. It is often valid, but may fail
2031 // for an object with dynamic bounds. This option is "automatically"
2032 // used by default for cases that do not use one of the other options.
2033 //
2034 // - Allocate a heap box/descriptor, initialized to zero. This always
2035 // works, but is more heavyweight and harder to clean up. It is used
2036 // for dynamic objects via calls to genUnusedEntryPointBox.
2037
2038 auto genUnusedEntryPointBox = [&]() {
2039 if (isUnusedEntryDummy) {
2040 assert(!Fortran::semantics::IsAllocatableOrPointer(sym) &&
2041 "handled above");
2042 // The box is read right away because lowering code does not expect
2043 // a non pointer/allocatable symbol to be mapped to a MutableBox.
2044 mlir::Type ty = converter.genType(var);
2045 bool isPolymorphic = false;
2046 if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(ty)) {
2047 isPolymorphic = mlir::isa<fir::ClassType>(ty);
2048 ty = boxTy.getEleTy();
2049 }
2050 Fortran::lower::genDeclareSymbol(
2051 converter, symMap, sym,
2052 fir::factory::genMutableBoxRead(
2053 builder, loc,
2054 fir::factory::createTempMutableBox(builder, loc, ty, {}, {},
2055 isPolymorphic)),
2056 fir::FortranVariableFlagsEnum::None,
2057 converter.isRegisteredDummySymbol(sym));
2058 return true;
2059 }
2060 return false;
2061 };
2062
2063 if (isAssumedRank) {
2064 assert(isUnusedEntryDummy && "assumed rank must be pointers/allocatables "
2065 "or descriptor dummy arguments");
2066 genUnusedEntryPointBox();
2067 return;
2068 }
2069
2070 // Helper to generate scalars for the symbol properties.
2071 auto genValue = [&](const Fortran::lower::SomeExpr &expr) {
2072 return genScalarValue(converter, loc, expr, symMap, stmtCtx);
2073 };
2074
2075 // For symbols reaching this point, all properties are constant and can be
2076 // read/computed already into ssa values.
2077
2078 // The origin must be \vec{1}.
2079 auto populateShape = [&](auto &shapes, const auto &bounds, mlir::Value box) {
2080 for (auto iter : llvm::enumerate(bounds)) {
2081 auto *spec = iter.value();
2082 assert(spec->lbound().GetExplicit() &&
2083 "lbound must be explicit with constant value 1");
2084 if (auto high = spec->ubound().GetExplicit()) {
2085 Fortran::lower::SomeExpr highEx{*high};
2086 mlir::Value ub = genValue(highEx);
2087 ub = builder.createConvert(loc, idxTy, ub);
2088 shapes.emplace_back(fir::factory::genMaxWithZero(builder, loc, ub));
2089 } else if (spec->ubound().isColon()) {
2090 assert(box && "assumed bounds require a descriptor");
2091 mlir::Value dim =
2092 builder.createIntegerConstant(loc, idxTy, iter.index());
2093 auto dimInfo =
2094 builder.create<fir::BoxDimsOp>(loc, idxTy, idxTy, idxTy, box, dim);
2095 shapes.emplace_back(dimInfo.getResult(1));
2096 } else if (spec->ubound().isStar()) {
2097 shapes.emplace_back(getAssumedSizeExtent(loc, builder));
2098 } else {
2099 llvm::report_fatal_error("unknown bound category");
2100 }
2101 }
2102 };
2103
2104 // The origin is not \vec{1}.
2105 auto populateLBoundsExtents = [&](auto &lbounds, auto &extents,
2106 const auto &bounds, mlir::Value box) {
2107 for (auto iter : llvm::enumerate(bounds)) {
2108 auto *spec = iter.value();
2109 fir::BoxDimsOp dimInfo;
2110 mlir::Value ub, lb;
2111 if (spec->lbound().isColon() || spec->ubound().isColon()) {
2112 // This is an assumed shape because allocatables and pointers extents
2113 // are not constant in the scope and are not read here.
2114 assert(box && "deferred bounds require a descriptor");
2115 mlir::Value dim =
2116 builder.createIntegerConstant(loc, idxTy, iter.index());
2117 dimInfo =
2118 builder.create<fir::BoxDimsOp>(loc, idxTy, idxTy, idxTy, box, dim);
2119 extents.emplace_back(dimInfo.getResult(1));
2120 if (auto low = spec->lbound().GetExplicit()) {
2121 auto expr = Fortran::lower::SomeExpr{*low};
2122 mlir::Value lb = builder.createConvert(loc, idxTy, genValue(expr));
2123 lbounds.emplace_back(lb);
2124 } else {
2125 // Implicit lower bound is 1 (Fortran 2018 section 8.5.8.3 point 3.)
2126 lbounds.emplace_back(builder.createIntegerConstant(loc, idxTy, 1));
2127 }
2128 } else {
2129 if (auto low = spec->lbound().GetExplicit()) {
2130 auto expr = Fortran::lower::SomeExpr{*low};
2131 lb = builder.createConvert(loc, idxTy, genValue(expr));
2132 } else {
2133 TODO(loc, "support for assumed rank entities");
2134 }
2135 lbounds.emplace_back(lb);
2136
2137 if (auto high = spec->ubound().GetExplicit()) {
2138 auto expr = Fortran::lower::SomeExpr{*high};
2139 ub = builder.createConvert(loc, idxTy, genValue(expr));
2140 extents.emplace_back(computeExtent(builder, loc, lb, ub));
2141 } else {
2142 // An assumed size array. The extent is not computed.
2143 assert(spec->ubound().isStar() && "expected assumed size");
2144 extents.emplace_back(getAssumedSizeExtent(loc, builder));
2145 }
2146 }
2147 }
2148 };
2149
2150 //===--------------------------------------------------------------===//
2151 // Non Pointer non allocatable scalar, explicit shape, and assumed
2152 // size arrays.
2153 // Lower the specification expressions.
2154 //===--------------------------------------------------------------===//
2155
2156 mlir::Value len;
2157 llvm::SmallVector<mlir::Value> extents;
2158 llvm::SmallVector<mlir::Value> lbounds;
2159 auto arg = symMap.lookupSymbol(sym).getAddr();
2160 mlir::Value addr = preAlloc;
2161
2162 if (arg)
2163 if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(arg.getType())) {
2164 // Contiguous assumed shape that can be tracked without a fir.box.
2165 mlir::Type refTy = builder.getRefType(boxTy.getEleTy());
2166 addr = builder.create<fir::BoxAddrOp>(loc, refTy, arg);
2167 }
2168
2169 // Compute/Extract character length.
2170 if (ba.isChar()) {
2171 if (arg) {
2172 assert(!preAlloc && "dummy cannot be pre-allocated");
2173 if (mlir::isa<fir::BoxCharType>(arg.getType())) {
2174 std::tie(addr, len) = charHelp.createUnboxChar(arg);
2175 } else if (mlir::isa<fir::CharacterType>(arg.getType())) {
2176 // fir.char<1> passed by value (BIND(C) with VALUE attribute).
2177 addr = builder.create<fir::AllocaOp>(loc, arg.getType());
2178 builder.create<fir::StoreOp>(loc, arg, addr);
2179 } else if (!addr) {
2180 addr = arg;
2181 }
2182 // Ensure proper type is given to array/scalar that was transmitted as a
2183 // fir.boxchar arg or is a statement function actual argument with
2184 // a different length than the dummy.
2185 mlir::Type castTy = builder.getRefType(converter.genType(var));
2186 addr = builder.createConvert(loc, castTy, addr);
2187 }
2188 if (std::optional<int64_t> cstLen = ba.getCharLenConst()) {
2189 // Static length
2190 len = builder.createIntegerConstant(loc, idxTy, *cstLen);
2191 } else {
2192 // Dynamic length
2193 if (genUnusedEntryPointBox())
2194 return;
2195 if (std::optional<Fortran::lower::SomeExpr> charLenExpr =
2196 ba.getCharLenExpr()) {
2197 // Explicit length
2198 mlir::Value rawLen = genValue(*charLenExpr);
2199 // If the length expression is negative, the length is zero. See
2200 // F2018 7.4.4.2 point 5.
2201 len = fir::factory::genMaxWithZero(builder, loc, rawLen);
2202 } else if (!len) {
2203 // Assumed length fir.box (possible for contiguous assumed shapes).
2204 // Read length from box.
2205 assert(arg && mlir::isa<fir::BoxType>(arg.getType()) &&
2206 "must be character dummy fir.box");
2207 len = charHelp.readLengthFromBox(arg);
2208 }
2209 }
2210 }
2211
2212 // Compute array extents and lower bounds.
2213 if (ba.isArray()) {
2214 if (ba.isStaticArray()) {
2215 if (ba.lboundIsAllOnes()) {
2216 for (std::int64_t extent :
2217 recoverShapeVector(ba.staticShape(), preAlloc))
2218 extents.push_back(genExtentValue(builder, loc, idxTy, extent));
2219 } else {
2220 for (auto [lb, extent] :
2221 llvm::zip(ba.staticLBound(),
2222 recoverShapeVector(ba.staticShape(), preAlloc))) {
2223 lbounds.emplace_back(builder.createIntegerConstant(loc, idxTy, lb));
2224 extents.emplace_back(genExtentValue(builder, loc, idxTy, extent));
2225 }
2226 }
2227 } else {
2228 // Non compile time constant shape.
2229 if (genUnusedEntryPointBox())
2230 return;
2231 if (ba.lboundIsAllOnes())
2232 populateShape(extents, ba.dynamicBound(), arg);
2233 else
2234 populateLBoundsExtents(lbounds, extents, ba.dynamicBound(), arg);
2235 }
2236 }
2237
2238 // Allocate or extract raw address for the entity
2239 if (!addr) {
2240 if (arg) {
2241 mlir::Type argType = arg.getType();
2242 const bool isCptrByVal = Fortran::semantics::IsBuiltinCPtr(sym) &&
2243 Fortran::lower::isCPtrArgByValueType(argType);
2244 if (isCptrByVal || !fir::conformsWithPassByRef(argType)) {
2245 // Dummy argument passed in register. Place the value in memory at that
2246 // point since lowering expect symbols to be mapped to memory addresses.
2247 mlir::Type symType = converter.genType(sym);
2248 addr = builder.create<fir::AllocaOp>(loc, symType);
2249 if (isCptrByVal) {
2250 // Place the void* address into the CPTR address component.
2251 mlir::Value addrComponent =
2252 fir::factory::genCPtrOrCFunptrAddr(builder, loc, addr, symType);
2253 builder.createStoreWithConvert(loc, arg, addrComponent);
2254 } else {
2255 builder.createStoreWithConvert(loc, arg, addr);
2256 }
2257 } else {
2258 // Dummy address, or address of result whose storage is passed by the
2259 // caller.
2260 assert(fir::isa_ref_type(argType) && "must be a memory address");
2261 addr = arg;
2262 }
2263 } else {
2264 // Local variables
2265 llvm::SmallVector<mlir::Value> typeParams;
2266 if (len)
2267 typeParams.emplace_back(len);
2268 addr = createNewLocal(converter, loc, var, preAlloc, extents, typeParams);
2269 }
2270 }
2271
2272 ::genDeclareSymbol(converter, symMap, sym, addr, len, extents, lbounds,
2273 replace);
2274 return;
2275 }
2276
2277 void Fortran::lower::defineModuleVariable(
2278 AbstractConverter &converter, const Fortran::lower::pft::Variable &var) {
2279 // Use empty linkage for module variables, which makes them available
2280 // for use in another unit.
2281 mlir::StringAttr linkage =
2282 getLinkageAttribute(converter.getFirOpBuilder(), var);
2283 if (!var.isGlobal())
2284 fir::emitFatalError(converter.getCurrentLocation(),
2285 "attempting to lower module variable as local");
2286 // Define aggregate storages for equivalenced objects.
2287 if (var.isAggregateStore()) {
2288 const Fortran::lower::pft::Variable::AggregateStore &aggregate =
2289 var.getAggregateStore();
2290 std::string aggName = mangleGlobalAggregateStore(converter, aggregate);
2291 defineGlobalAggregateStore(converter, aggregate, aggName, linkage);
2292 return;
2293 }
2294 const Fortran::semantics::Symbol &sym = var.getSymbol();
2295 if (const Fortran::semantics::Symbol *common =
2296 Fortran::semantics::FindCommonBlockContaining(var.getSymbol())) {
2297 // Nothing to do, common block are generated before everything. Ensure
2298 // this was done by calling getCommonBlockGlobal.
2299 getCommonBlockGlobal(converter, *common);
2300 } else if (var.isAlias()) {
2301 // Do nothing. Mapping will be done on user side.
2302 } else {
2303 std::string globalName = converter.mangleName(sym);
2304 cuf::DataAttributeAttr dataAttr =
2305 Fortran::lower::translateSymbolCUFDataAttribute(
2306 converter.getFirOpBuilder().getContext(), sym);
2307 defineGlobal(converter, var, globalName, linkage, dataAttr);
2308 }
2309 }
2310
2311 void Fortran::lower::instantiateVariable(AbstractConverter &converter,
2312 const pft::Variable &var,
2313 Fortran::lower::SymMap &symMap,
2314 AggregateStoreMap &storeMap) {
2315 if (var.hasSymbol()) {
2316 // Do not try to instantiate symbols twice, except for dummies and results,
2317 // that may have been mapped to the MLIR entry block arguments, and for
2318 // which the explicit specifications, if any, has not yet been lowered.
2319 const auto &sym = var.getSymbol();
2320 if (!IsDummy(sym) && !IsFunctionResult(sym) && symMap.lookupSymbol(sym))
2321 return;
2322 }
2323 LLVM_DEBUG(llvm::dbgs() << "instantiateVariable: "; var.dump());
2324 if (var.isAggregateStore())
2325 instantiateAggregateStore(converter, var, storeMap);
2326 else if (const Fortran::semantics::Symbol *common =
2327 Fortran::semantics::FindCommonBlockContaining(
2328 var.getSymbol().GetUltimate()))
2329 instantiateCommon(converter, *common, var, symMap);
2330 else if (var.isAlias())
2331 instantiateAlias(converter, var, symMap, storeMap);
2332 else if (var.isGlobal())
2333 instantiateGlobal(converter, var, symMap);
2334 else
2335 instantiateLocal(converter, var, symMap);
2336 }
2337
2338 static void
2339 mapCallInterfaceSymbol(const Fortran::semantics::Symbol &interfaceSymbol,
2340 Fortran::lower::AbstractConverter &converter,
2341 const Fortran::lower::CallerInterface &caller,
2342 Fortran::lower::SymMap &symMap) {
2343 Fortran::lower::AggregateStoreMap storeMap;
2344 for (Fortran::lower::pft::Variable var :
2345 Fortran::lower::pft::getDependentVariableList(interfaceSymbol)) {
2346 if (var.isAggregateStore()) {
2347 instantiateVariable(converter, var, symMap, storeMap);
2348 continue;
2349 }
2350 const Fortran::semantics::Symbol &sym = var.getSymbol();
2351 if (&sym == &interfaceSymbol)
2352 continue;
2353 const auto *hostDetails =
2354 sym.detailsIf<Fortran::semantics::HostAssocDetails>();
2355 if (hostDetails && !var.isModuleOrSubmoduleVariable()) {
2356 // The callee is an internal procedure `A` whose result properties
2357 // depend on host variables. The caller may be the host, or another
2358 // internal procedure `B` contained in the same host. In the first
2359 // case, the host symbol is obviously mapped, in the second case, it
2360 // must also be mapped because
2361 // HostAssociations::internalProcedureBindings that was called when
2362 // lowering `B` will have mapped all host symbols of captured variables
2363 // to the tuple argument containing the composite of all host associated
2364 // variables, whether or not the host symbol is actually referred to in
2365 // `B`. Hence it is possible to simply lookup the variable associated to
2366 // the host symbol without having to go back to the tuple argument.
2367 symMap.copySymbolBinding(hostDetails->symbol(), sym);
2368 // The SymbolBox associated to the host symbols is complete, skip
2369 // instantiateVariable that would try to allocate a new storage.
2370 continue;
2371 }
2372 if (Fortran::semantics::IsDummy(sym) &&
2373 sym.owner() == interfaceSymbol.owner()) {
2374 // Get the argument for the dummy argument symbols of the current call.
2375 symMap.addSymbol(sym, caller.getArgumentValue(sym));
2376 // All the properties of the dummy variable may not come from the actual
2377 // argument, let instantiateVariable handle this.
2378 }
2379 // If this is neither a host associated or dummy symbol, it must be a
2380 // module or common block variable to satisfy specification expression
2381 // requirements in 10.1.11, instantiateVariable will get its address and
2382 // properties.
2383 instantiateVariable(converter, var, symMap, storeMap);
2384 }
2385 }
2386
2387 void Fortran::lower::mapCallInterfaceSymbolsForResult(
2388 AbstractConverter &converter, const Fortran::lower::CallerInterface &caller,
2389 SymMap &symMap) {
2390 const Fortran::semantics::Symbol &result = caller.getResultSymbol();
2391 mapCallInterfaceSymbol(result, converter, caller, symMap);
2392 }
2393
2394 void Fortran::lower::mapCallInterfaceSymbolsForDummyArgument(
2395 AbstractConverter &converter, const Fortran::lower::CallerInterface &caller,
2396 SymMap &symMap, const Fortran::semantics::Symbol &dummySymbol) {
2397 mapCallInterfaceSymbol(dummySymbol, converter, caller, symMap);
2398 }
2399
2400 void Fortran::lower::mapSymbolAttributes(
2401 AbstractConverter &converter, const Fortran::semantics::SymbolRef &symbol,
2402 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx,
2403 mlir::Value preAlloc) {
2404 mapSymbolAttributes(converter, pft::Variable{symbol}, symMap, stmtCtx,
2405 preAlloc);
2406 }
2407
2408 void Fortran::lower::createIntrinsicModuleGlobal(
2409 Fortran::lower::AbstractConverter &converter, const pft::Variable &var) {
2410 defineGlobal(converter, var, converter.mangleName(var.getSymbol()),
2411 converter.getFirOpBuilder().createLinkOnceODRLinkage());
2412 }
2413
2414 void Fortran::lower::createRuntimeTypeInfoGlobal(
2415 Fortran::lower::AbstractConverter &converter,
2416 const Fortran::semantics::Symbol &typeInfoSym) {
2417 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
2418 std::string globalName = converter.mangleName(typeInfoSym);
2419 auto var = Fortran::lower::pft::Variable(typeInfoSym, /*global=*/true);
2420 mlir::StringAttr linkage = getLinkageAttribute(builder, var);
2421 defineGlobal(converter, var, globalName, linkage);
2422 }
2423
2424 mlir::Type Fortran::lower::getCrayPointeeBoxType(mlir::Type fortranType) {
2425 mlir::Type baseType = hlfir::getFortranElementOrSequenceType(fortranType);
2426 if (auto seqType = mlir::dyn_cast<fir::SequenceType>(baseType)) {
2427 // The pointer box's sequence type must be with unknown shape.
2428 llvm::SmallVector<int64_t> shape(seqType.getDimension(),
2429 fir::SequenceType::getUnknownExtent());
2430 baseType = fir::SequenceType::get(shape, seqType.getEleTy());
2431 }
2432 return fir::BoxType::get(fir::PointerType::get(baseType));
2433 }