forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConvertVariable.cpp
2569 lines (2436 loc) · 118 KB
/
ConvertVariable.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===-- ConvertVariable.cpp -- bridge to lower to MLIR --------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/
//
//===----------------------------------------------------------------------===//
#include "flang/Lower/ConvertVariable.h"
#include "flang/Lower/AbstractConverter.h"
#include "flang/Lower/Allocatable.h"
#include "flang/Lower/BoxAnalyzer.h"
#include "flang/Lower/CallInterface.h"
#include "flang/Lower/ConvertConstant.h"
#include "flang/Lower/ConvertExpr.h"
#include "flang/Lower/ConvertExprToHLFIR.h"
#include "flang/Lower/ConvertProcedureDesignator.h"
#include "flang/Lower/Cuda.h"
#include "flang/Lower/Mangler.h"
#include "flang/Lower/PFTBuilder.h"
#include "flang/Lower/StatementContext.h"
#include "flang/Lower/Support/Utils.h"
#include "flang/Lower/SymbolMap.h"
#include "flang/Optimizer/Builder/Character.h"
#include "flang/Optimizer/Builder/FIRBuilder.h"
#include "flang/Optimizer/Builder/HLFIRTools.h"
#include "flang/Optimizer/Builder/IntrinsicCall.h"
#include "flang/Optimizer/Builder/Runtime/Derived.h"
#include "flang/Optimizer/Builder/Todo.h"
#include "flang/Optimizer/Dialect/CUF/CUFOps.h"
#include "flang/Optimizer/Dialect/FIRAttr.h"
#include "flang/Optimizer/Dialect/FIRDialect.h"
#include "flang/Optimizer/Dialect/FIROps.h"
#include "flang/Optimizer/Dialect/Support/FIRContext.h"
#include "flang/Optimizer/HLFIR/HLFIROps.h"
#include "flang/Optimizer/Support/FatalError.h"
#include "flang/Optimizer/Support/InternalNames.h"
#include "flang/Optimizer/Support/Utils.h"
#include "flang/Runtime/allocator-registry-consts.h"
#include "flang/Semantics/runtime-type-info.h"
#include "flang/Semantics/tools.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include <optional>
static llvm::cl::opt<bool>
allowAssumedRank("allow-assumed-rank",
llvm::cl::desc("Enable assumed rank lowering"),
llvm::cl::init(true));
#define DEBUG_TYPE "flang-lower-variable"
/// Helper to lower a scalar expression using a specific symbol mapping.
static mlir::Value genScalarValue(Fortran::lower::AbstractConverter &converter,
mlir::Location loc,
const Fortran::lower::SomeExpr &expr,
Fortran::lower::SymMap &symMap,
Fortran::lower::StatementContext &context) {
// This does not use the AbstractConverter member function to override the
// symbol mapping to be used expression lowering.
if (converter.getLoweringOptions().getLowerToHighLevelFIR()) {
hlfir::EntityWithAttributes loweredExpr =
Fortran::lower::convertExprToHLFIR(loc, converter, expr, symMap,
context);
return hlfir::loadTrivialScalar(loc, converter.getFirOpBuilder(),
loweredExpr);
}
return fir::getBase(Fortran::lower::createSomeExtendedExpression(
loc, converter, expr, symMap, context));
}
/// Does this variable have a default initialization?
bool Fortran::lower::hasDefaultInitialization(
const Fortran::semantics::Symbol &sym) {
if (sym.has<Fortran::semantics::ObjectEntityDetails>() && sym.size())
if (!Fortran::semantics::IsAllocatableOrPointer(sym))
if (const Fortran::semantics::DeclTypeSpec *declTypeSpec = sym.GetType())
if (const Fortran::semantics::DerivedTypeSpec *derivedTypeSpec =
declTypeSpec->AsDerived()) {
// Pointer assignments in the runtime may hit undefined behaviors if
// the RHS contains garbage. Pointer objects are always established by
// lowering to NULL() (in Fortran::lower::createMutableBox). However,
// pointer components need special care here so that local and global
// derived type containing pointers are always initialized.
// Intent(out), however, do not need to be initialized since the
// related descriptor storage comes from a local or global that has
// been initialized (it may not be NULL() anymore, but the rank, type,
// and non deferred length parameters are still correct in a
// conformant program, and that is what matters).
const bool ignorePointer = Fortran::semantics::IsIntentOut(sym);
return derivedTypeSpec->HasDefaultInitialization(
/*ignoreAllocatable=*/false, ignorePointer);
}
return false;
}
// Does this variable have a finalization?
static bool hasFinalization(const Fortran::semantics::Symbol &sym) {
if (sym.has<Fortran::semantics::ObjectEntityDetails>())
if (const Fortran::semantics::DeclTypeSpec *declTypeSpec = sym.GetType())
if (const Fortran::semantics::DerivedTypeSpec *derivedTypeSpec =
declTypeSpec->AsDerived())
return Fortran::semantics::IsFinalizable(*derivedTypeSpec);
return false;
}
// Does this variable have an allocatable direct component?
static bool
hasAllocatableDirectComponent(const Fortran::semantics::Symbol &sym) {
if (sym.has<Fortran::semantics::ObjectEntityDetails>())
if (const Fortran::semantics::DeclTypeSpec *declTypeSpec = sym.GetType())
if (const Fortran::semantics::DerivedTypeSpec *derivedTypeSpec =
declTypeSpec->AsDerived())
return Fortran::semantics::HasAllocatableDirectComponent(
*derivedTypeSpec);
return false;
}
//===----------------------------------------------------------------===//
// Global variables instantiation (not for alias and common)
//===----------------------------------------------------------------===//
/// Helper to generate expression value inside global initializer.
static fir::ExtendedValue
genInitializerExprValue(Fortran::lower::AbstractConverter &converter,
mlir::Location loc,
const Fortran::lower::SomeExpr &expr,
Fortran::lower::StatementContext &stmtCtx) {
// Data initializer are constant value and should not depend on other symbols
// given the front-end fold parameter references. In any case, the "current"
// map of the converter should not be used since it holds mapping to
// mlir::Value from another mlir region. If these value are used by accident
// in the initializer, this will lead to segfaults in mlir code.
Fortran::lower::SymMap emptyMap;
return Fortran::lower::createSomeInitializerExpression(loc, converter, expr,
emptyMap, stmtCtx);
}
/// Can this symbol constant be placed in read-only memory?
static bool isConstant(const Fortran::semantics::Symbol &sym) {
return sym.attrs().test(Fortran::semantics::Attr::PARAMETER) ||
sym.test(Fortran::semantics::Symbol::Flag::ReadOnly);
}
static fir::GlobalOp defineGlobal(Fortran::lower::AbstractConverter &converter,
const Fortran::lower::pft::Variable &var,
llvm::StringRef globalName,
mlir::StringAttr linkage,
cuf::DataAttributeAttr dataAttr = {});
static mlir::Location genLocation(Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &sym) {
// Compiler generated name cannot be used as source location, their name
// is not pointing to the source files.
if (!sym.test(Fortran::semantics::Symbol::Flag::CompilerCreated))
return converter.genLocation(sym.name());
return converter.getCurrentLocation();
}
/// Create the global op declaration without any initializer
static fir::GlobalOp declareGlobal(Fortran::lower::AbstractConverter &converter,
const Fortran::lower::pft::Variable &var,
llvm::StringRef globalName,
mlir::StringAttr linkage) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
if (fir::GlobalOp global = builder.getNamedGlobal(globalName))
return global;
const Fortran::semantics::Symbol &sym = var.getSymbol();
cuf::DataAttributeAttr dataAttr =
Fortran::lower::translateSymbolCUFDataAttribute(
converter.getFirOpBuilder().getContext(), sym);
// Always define linkonce data since it may be optimized out from the module
// that actually owns the variable if it does not refers to it.
if (linkage == builder.createLinkOnceODRLinkage() ||
linkage == builder.createLinkOnceLinkage())
return defineGlobal(converter, var, globalName, linkage, dataAttr);
mlir::Location loc = genLocation(converter, sym);
// Resolve potential host and module association before checking that this
// symbol is an object of a function pointer.
const Fortran::semantics::Symbol &ultimate = sym.GetUltimate();
if (!ultimate.has<Fortran::semantics::ObjectEntityDetails>() &&
!Fortran::semantics::IsProcedurePointer(ultimate))
mlir::emitError(loc, "processing global declaration: symbol '")
<< toStringRef(sym.name()) << "' has unexpected details\n";
return builder.createGlobal(loc, converter.genType(var), globalName, linkage,
mlir::Attribute{}, isConstant(ultimate),
var.isTarget(), dataAttr);
}
/// Temporary helper to catch todos in initial data target lowering.
static bool
hasDerivedTypeWithLengthParameters(const Fortran::semantics::Symbol &sym) {
if (const Fortran::semantics::DeclTypeSpec *declTy = sym.GetType())
if (const Fortran::semantics::DerivedTypeSpec *derived =
declTy->AsDerived())
return Fortran::semantics::CountLenParameters(*derived) > 0;
return false;
}
fir::ExtendedValue Fortran::lower::genExtAddrInInitializer(
Fortran::lower::AbstractConverter &converter, mlir::Location loc,
const Fortran::lower::SomeExpr &addr) {
Fortran::lower::SymMap globalOpSymMap;
Fortran::lower::AggregateStoreMap storeMap;
Fortran::lower::StatementContext stmtCtx;
if (const Fortran::semantics::Symbol *sym =
Fortran::evaluate::GetFirstSymbol(addr)) {
// Length parameters processing will need care in global initializer
// context.
if (hasDerivedTypeWithLengthParameters(*sym))
TODO(loc, "initial-data-target with derived type length parameters");
auto var = Fortran::lower::pft::Variable(*sym, /*global=*/true);
Fortran::lower::instantiateVariable(converter, var, globalOpSymMap,
storeMap);
}
if (converter.getLoweringOptions().getLowerToHighLevelFIR())
return Fortran::lower::convertExprToAddress(loc, converter, addr,
globalOpSymMap, stmtCtx);
return Fortran::lower::createInitializerAddress(loc, converter, addr,
globalOpSymMap, stmtCtx);
}
/// create initial-data-target fir.box in a global initializer region.
mlir::Value Fortran::lower::genInitialDataTarget(
Fortran::lower::AbstractConverter &converter, mlir::Location loc,
mlir::Type boxType, const Fortran::lower::SomeExpr &initialTarget,
bool couldBeInEquivalence) {
Fortran::lower::SymMap globalOpSymMap;
Fortran::lower::AggregateStoreMap storeMap;
Fortran::lower::StatementContext stmtCtx;
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>(
initialTarget))
return fir::factory::createUnallocatedBox(
builder, loc, boxType,
/*nonDeferredParams=*/std::nullopt);
// Pointer initial data target, and NULL(mold).
for (const auto &sym : Fortran::evaluate::CollectSymbols(initialTarget)) {
// Derived type component symbols should not be instantiated as objects
// on their own.
if (sym->owner().IsDerivedType())
continue;
// Length parameters processing will need care in global initializer
// context.
if (hasDerivedTypeWithLengthParameters(sym))
TODO(loc, "initial-data-target with derived type length parameters");
auto var = Fortran::lower::pft::Variable(sym, /*global=*/true);
if (couldBeInEquivalence) {
auto dependentVariableList =
Fortran::lower::pft::getDependentVariableList(sym);
for (Fortran::lower::pft::Variable var : dependentVariableList) {
if (!var.isAggregateStore())
break;
instantiateVariable(converter, var, globalOpSymMap, storeMap);
}
var = dependentVariableList.back();
assert(var.getSymbol().name() == sym->name() &&
"missing symbol in dependence list");
}
Fortran::lower::instantiateVariable(converter, var, globalOpSymMap,
storeMap);
}
// Handle NULL(mold) as a special case. Return an unallocated box of MOLD
// type. The return box is correctly created as a fir.box<fir.ptr<T>> where
// T is extracted from the MOLD argument.
if (const Fortran::evaluate::ProcedureRef *procRef =
Fortran::evaluate::UnwrapProcedureRef(initialTarget)) {
const Fortran::evaluate::SpecificIntrinsic *intrinsic =
procRef->proc().GetSpecificIntrinsic();
if (intrinsic && intrinsic->name == "null") {
assert(procRef->arguments().size() == 1 &&
"Expecting mold argument for NULL intrinsic");
const auto *argExpr = procRef->arguments()[0].value().UnwrapExpr();
assert(argExpr);
const Fortran::semantics::Symbol *sym =
Fortran::evaluate::GetFirstSymbol(*argExpr);
assert(sym && "MOLD must be a pointer or allocatable symbol");
mlir::Type boxType = converter.genType(*sym);
mlir::Value box =
fir::factory::createUnallocatedBox(builder, loc, boxType, {});
return box;
}
}
mlir::Value targetBox;
mlir::Value targetShift;
if (converter.getLoweringOptions().getLowerToHighLevelFIR()) {
auto target = Fortran::lower::convertExprToBox(
loc, converter, initialTarget, globalOpSymMap, stmtCtx);
targetBox = fir::getBase(target);
targetShift = builder.createShape(loc, target);
} else {
if (initialTarget.Rank() > 0) {
auto target = Fortran::lower::createSomeArrayBox(converter, initialTarget,
globalOpSymMap, stmtCtx);
targetBox = fir::getBase(target);
targetShift = builder.createShape(loc, target);
} else {
fir::ExtendedValue addr = Fortran::lower::createInitializerAddress(
loc, converter, initialTarget, globalOpSymMap, stmtCtx);
targetBox = builder.createBox(loc, addr);
// Nothing to do for targetShift, the target is a scalar.
}
}
// The targetBox is a fir.box<T>, not a fir.box<fir.ptr<T>> as it should for
// pointers (this matters to get the POINTER attribute correctly inside the
// initial value of the descriptor).
// Create a fir.rebox to set the attribute correctly, and use targetShift
// to preserve the target lower bounds if any.
return builder.create<fir::ReboxOp>(loc, boxType, targetBox, targetShift,
/*slice=*/mlir::Value{});
}
/// Generate default initial value for a derived type object \p sym with mlir
/// type \p symTy.
static mlir::Value genDefaultInitializerValue(
Fortran::lower::AbstractConverter &converter, mlir::Location loc,
const Fortran::semantics::Symbol &sym, mlir::Type symTy,
Fortran::lower::StatementContext &stmtCtx);
/// Generate the initial value of a derived component \p component and insert
/// it into the derived type initial value \p insertInto of type \p recTy.
/// Return the new derived type initial value after the insertion.
static mlir::Value genComponentDefaultInit(
Fortran::lower::AbstractConverter &converter, mlir::Location loc,
const Fortran::semantics::Symbol &component, fir::RecordType recTy,
mlir::Value insertInto, Fortran::lower::StatementContext &stmtCtx) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
std::string name = converter.getRecordTypeFieldName(component);
mlir::Type componentTy = recTy.getType(name);
assert(componentTy && "component not found in type");
mlir::Value componentValue;
if (const auto *object{
component.detailsIf<Fortran::semantics::ObjectEntityDetails>()}) {
if (const auto &init = object->init()) {
// Component has explicit initialization.
if (Fortran::semantics::IsPointer(component))
// Initial data target.
componentValue =
genInitialDataTarget(converter, loc, componentTy, *init);
else
// Initial value.
componentValue = fir::getBase(
genInitializerExprValue(converter, loc, *init, stmtCtx));
} else if (Fortran::semantics::IsAllocatableOrPointer(component)) {
// Pointer or allocatable without initialization.
// Create deallocated/disassociated value.
// From a standard point of view, pointer without initialization do not
// need to be disassociated, but for sanity and simplicity, do it in
// global constructor since this has no runtime cost.
componentValue = fir::factory::createUnallocatedBox(
builder, loc, componentTy, std::nullopt);
} else if (Fortran::lower::hasDefaultInitialization(component)) {
// Component type has default initialization.
componentValue = genDefaultInitializerValue(converter, loc, component,
componentTy, stmtCtx);
} else {
// Component has no initial value. Set its bits to zero by extension
// to match what is expected because other compilers are doing it.
componentValue = builder.create<fir::ZeroOp>(loc, componentTy);
}
} else if (const auto *proc{
component
.detailsIf<Fortran::semantics::ProcEntityDetails>()}) {
if (proc->init().has_value()) {
auto sym{*proc->init()};
if (sym) // Has a procedure target.
componentValue =
Fortran::lower::convertProcedureDesignatorInitialTarget(converter,
loc, *sym);
else // Has NULL() target.
componentValue =
fir::factory::createNullBoxProc(builder, loc, componentTy);
} else
componentValue = builder.create<fir::ZeroOp>(loc, componentTy);
}
assert(componentValue && "must have been computed");
componentValue = builder.createConvert(loc, componentTy, componentValue);
auto fieldTy = fir::FieldType::get(recTy.getContext());
// FIXME: type parameters must come from the derived-type-spec
auto field = builder.create<fir::FieldIndexOp>(
loc, fieldTy, name, recTy,
/*typeParams=*/mlir::ValueRange{} /*TODO*/);
return builder.create<fir::InsertValueOp>(
loc, recTy, insertInto, componentValue,
builder.getArrayAttr(field.getAttributes()));
}
static mlir::Value genDefaultInitializerValue(
Fortran::lower::AbstractConverter &converter, mlir::Location loc,
const Fortran::semantics::Symbol &sym, mlir::Type symTy,
Fortran::lower::StatementContext &stmtCtx) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::Type scalarType = symTy;
fir::SequenceType sequenceType;
if (auto ty = mlir::dyn_cast<fir::SequenceType>(symTy)) {
sequenceType = ty;
scalarType = ty.getEleTy();
}
// Build a scalar default value of the symbol type, looping through the
// components to build each component initial value.
auto recTy = mlir::cast<fir::RecordType>(scalarType);
mlir::Value initialValue = builder.create<fir::UndefOp>(loc, scalarType);
const Fortran::semantics::DeclTypeSpec *declTy = sym.GetType();
assert(declTy && "var with default initialization must have a type");
if (converter.getLoweringOptions().getLowerToHighLevelFIR()) {
// In HLFIR, the parent type is the first component, while in FIR there is
// not parent component in the fir.type and the component of the parent are
// "inlined" at the beginning of the fir.type.
const Fortran::semantics::Symbol &typeSymbol =
declTy->derivedTypeSpec().typeSymbol();
const Fortran::semantics::Scope *derivedScope =
declTy->derivedTypeSpec().GetScope();
assert(derivedScope && "failed to retrieve derived type scope");
for (const auto &componentName :
typeSymbol.get<Fortran::semantics::DerivedTypeDetails>()
.componentNames()) {
auto scopeIter = derivedScope->find(componentName);
assert(scopeIter != derivedScope->cend() &&
"failed to find derived type component symbol");
const Fortran::semantics::Symbol &component = scopeIter->second.get();
initialValue = genComponentDefaultInit(converter, loc, component, recTy,
initialValue, stmtCtx);
}
} else {
Fortran::semantics::OrderedComponentIterator components(
declTy->derivedTypeSpec());
for (const auto &component : components) {
// Skip parent components, the sub-components of parent types are part of
// components and will be looped through right after.
if (component.test(Fortran::semantics::Symbol::Flag::ParentComp))
continue;
initialValue = genComponentDefaultInit(converter, loc, component, recTy,
initialValue, stmtCtx);
}
}
if (sequenceType) {
// For arrays, duplicate the scalar value to all elements with an
// fir.insert_range covering the whole array.
auto arrayInitialValue = builder.create<fir::UndefOp>(loc, sequenceType);
llvm::SmallVector<int64_t> rangeBounds;
for (int64_t extent : sequenceType.getShape()) {
if (extent == fir::SequenceType::getUnknownExtent())
TODO(loc,
"default initial value of array component with length parameters");
rangeBounds.push_back(0);
rangeBounds.push_back(extent - 1);
}
return builder.create<fir::InsertOnRangeOp>(
loc, sequenceType, arrayInitialValue, initialValue,
builder.getIndexVectorAttr(rangeBounds));
}
return initialValue;
}
/// Does this global already have an initializer ?
static bool globalIsInitialized(fir::GlobalOp global) {
return !global.getRegion().empty() || global.getInitVal();
}
/// Call \p genInit to generate code inside \p global initializer region.
void Fortran::lower::createGlobalInitialization(
fir::FirOpBuilder &builder, fir::GlobalOp global,
std::function<void(fir::FirOpBuilder &)> genInit) {
mlir::Region ®ion = global.getRegion();
region.push_back(new mlir::Block);
mlir::Block &block = region.back();
auto insertPt = builder.saveInsertionPoint();
builder.setInsertionPointToStart(&block);
genInit(builder);
builder.restoreInsertionPoint(insertPt);
}
static unsigned getAllocatorIdx(cuf::DataAttributeAttr dataAttr) {
if (dataAttr) {
if (dataAttr.getValue() == cuf::DataAttribute::Pinned)
return kPinnedAllocatorPos;
if (dataAttr.getValue() == cuf::DataAttribute::Device)
return kDeviceAllocatorPos;
if (dataAttr.getValue() == cuf::DataAttribute::Managed)
return kManagedAllocatorPos;
if (dataAttr.getValue() == cuf::DataAttribute::Unified)
return kUnifiedAllocatorPos;
}
return kDefaultAllocator;
}
/// Create the global op and its init if it has one
static fir::GlobalOp defineGlobal(Fortran::lower::AbstractConverter &converter,
const Fortran::lower::pft::Variable &var,
llvm::StringRef globalName,
mlir::StringAttr linkage,
cuf::DataAttributeAttr dataAttr) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
const Fortran::semantics::Symbol &sym = var.getSymbol();
mlir::Location loc = genLocation(converter, sym);
bool isConst = isConstant(sym);
fir::GlobalOp global = builder.getNamedGlobal(globalName);
mlir::Type symTy = converter.genType(var);
if (global && globalIsInitialized(global))
return global;
if (!converter.getLoweringOptions().getLowerToHighLevelFIR() &&
Fortran::semantics::IsProcedurePointer(sym))
TODO(loc, "procedure pointer globals");
// If this is an array, check to see if we can use a dense attribute
// with a tensor mlir type. This optimization currently only supports
// Fortran arrays of integer, real, complex, or logical. The tensor
// type does not support nested structures.
if (mlir::isa<fir::SequenceType>(symTy) &&
!Fortran::semantics::IsAllocatableOrPointer(sym)) {
mlir::Type eleTy = mlir::cast<fir::SequenceType>(symTy).getElementType();
if (mlir::isa<mlir::IntegerType, mlir::FloatType, mlir::ComplexType,
fir::LogicalType>(eleTy)) {
const auto *details =
sym.detailsIf<Fortran::semantics::ObjectEntityDetails>();
if (details->init()) {
global = Fortran::lower::tryCreatingDenseGlobal(
builder, loc, symTy, globalName, linkage, isConst,
details->init().value(), dataAttr);
if (global) {
global.setVisibility(mlir::SymbolTable::Visibility::Public);
return global;
}
}
}
}
if (!global)
global =
builder.createGlobal(loc, symTy, globalName, linkage, mlir::Attribute{},
isConst, var.isTarget(), dataAttr);
if (Fortran::semantics::IsAllocatableOrPointer(sym) &&
!Fortran::semantics::IsProcedure(sym)) {
const auto *details =
sym.detailsIf<Fortran::semantics::ObjectEntityDetails>();
if (details && details->init()) {
auto expr = *details->init();
Fortran::lower::createGlobalInitialization(
builder, global, [&](fir::FirOpBuilder &b) {
mlir::Value box = Fortran::lower::genInitialDataTarget(
converter, loc, symTy, expr);
b.create<fir::HasValueOp>(loc, box);
});
} else {
// Create unallocated/disassociated descriptor if no explicit init
Fortran::lower::createGlobalInitialization(
builder, global, [&](fir::FirOpBuilder &b) {
mlir::Value box = fir::factory::createUnallocatedBox(
b, loc, symTy,
/*nonDeferredParams=*/std::nullopt,
/*typeSourceBox=*/{}, getAllocatorIdx(dataAttr));
b.create<fir::HasValueOp>(loc, box);
});
}
} else if (const auto *details =
sym.detailsIf<Fortran::semantics::ObjectEntityDetails>()) {
if (details->init()) {
Fortran::lower::createGlobalInitialization(
builder, global, [&](fir::FirOpBuilder &builder) {
Fortran::lower::StatementContext stmtCtx(
/*cleanupProhibited=*/true);
fir::ExtendedValue initVal = genInitializerExprValue(
converter, loc, details->init().value(), stmtCtx);
mlir::Value castTo =
builder.createConvert(loc, symTy, fir::getBase(initVal));
builder.create<fir::HasValueOp>(loc, castTo);
});
} else if (Fortran::lower::hasDefaultInitialization(sym)) {
Fortran::lower::createGlobalInitialization(
builder, global, [&](fir::FirOpBuilder &builder) {
Fortran::lower::StatementContext stmtCtx(
/*cleanupProhibited=*/true);
mlir::Value initVal =
genDefaultInitializerValue(converter, loc, sym, symTy, stmtCtx);
mlir::Value castTo = builder.createConvert(loc, symTy, initVal);
builder.create<fir::HasValueOp>(loc, castTo);
});
}
} else if (Fortran::semantics::IsProcedurePointer(sym)) {
const auto *details{sym.detailsIf<Fortran::semantics::ProcEntityDetails>()};
if (details && details->init()) {
auto sym{*details->init()};
if (sym) // Has a procedure target.
Fortran::lower::createGlobalInitialization(
builder, global, [&](fir::FirOpBuilder &b) {
Fortran::lower::StatementContext stmtCtx(
/*cleanupProhibited=*/true);
auto box{Fortran::lower::convertProcedureDesignatorInitialTarget(
converter, loc, *sym)};
auto castTo{builder.createConvert(loc, symTy, box)};
b.create<fir::HasValueOp>(loc, castTo);
});
else { // Has NULL() target.
Fortran::lower::createGlobalInitialization(
builder, global, [&](fir::FirOpBuilder &b) {
auto box{fir::factory::createNullBoxProc(b, loc, symTy)};
b.create<fir::HasValueOp>(loc, box);
});
}
} else {
// No initialization.
Fortran::lower::createGlobalInitialization(
builder, global, [&](fir::FirOpBuilder &b) {
auto box{fir::factory::createNullBoxProc(b, loc, symTy)};
b.create<fir::HasValueOp>(loc, box);
});
}
} else if (sym.has<Fortran::semantics::CommonBlockDetails>()) {
mlir::emitError(loc, "COMMON symbol processed elsewhere");
} else {
TODO(loc, "global"); // Something else
}
// Creates zero initializer for globals without initializers, this is a common
// and expected behavior (although not required by the standard)
if (!globalIsInitialized(global)) {
// Fortran does not provide means to specify that a BIND(C) module
// uninitialized variables will be defined in C.
// Add the common linkage to those to allow some level of support
// for this use case. Note that this use case will not work if the Fortran
// module code is placed in a shared library since, at least for the ELF
// format, common symbols are assigned a section in shared libraries.
// The best is still to declare C defined variables in a Fortran module file
// with no other definitions, and to never link the resulting module object
// file.
if (sym.attrs().test(Fortran::semantics::Attr::BIND_C))
global.setLinkName(builder.createCommonLinkage());
Fortran::lower::createGlobalInitialization(
builder, global, [&](fir::FirOpBuilder &builder) {
mlir::Value initValue;
if (converter.getLoweringOptions().getInitGlobalZero())
initValue = builder.create<fir::ZeroOp>(loc, symTy);
else
initValue = builder.create<fir::UndefOp>(loc, symTy);
builder.create<fir::HasValueOp>(loc, initValue);
});
}
// Set public visibility to prevent global definition to be optimized out
// even if they have no initializer and are unused in this compilation unit.
global.setVisibility(mlir::SymbolTable::Visibility::Public);
return global;
}
/// Return linkage attribute for \p var.
static mlir::StringAttr
getLinkageAttribute(fir::FirOpBuilder &builder,
const Fortran::lower::pft::Variable &var) {
// Runtime type info for a same derived type is identical in each compilation
// unit. It desired to avoid having to link against module that only define a
// type. Therefore the runtime type info is generated everywhere it is needed
// with `linkonce_odr` LLVM linkage.
if (var.isRuntimeTypeInfoData())
return builder.createLinkOnceODRLinkage();
if (var.isModuleOrSubmoduleVariable())
return {}; // external linkage
// Otherwise, the variable is owned by a procedure and must not be visible in
// other compilation units.
return builder.createInternalLinkage();
}
/// Instantiate a global variable. If it hasn't already been processed, add
/// the global to the ModuleOp as a new uniqued symbol and initialize it with
/// the correct value. It will be referenced on demand using `fir.addr_of`.
static void instantiateGlobal(Fortran::lower::AbstractConverter &converter,
const Fortran::lower::pft::Variable &var,
Fortran::lower::SymMap &symMap) {
const Fortran::semantics::Symbol &sym = var.getSymbol();
assert(!var.isAlias() && "must be handled in instantiateAlias");
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
std::string globalName = converter.mangleName(sym);
mlir::Location loc = genLocation(converter, sym);
mlir::StringAttr linkage = getLinkageAttribute(builder, var);
fir::GlobalOp global;
if (var.isModuleOrSubmoduleVariable()) {
// A non-intrinsic module global is defined when lowering the module.
// Emit only a declaration if the global does not exist.
global = declareGlobal(converter, var, globalName, linkage);
} else {
cuf::DataAttributeAttr dataAttr =
Fortran::lower::translateSymbolCUFDataAttribute(builder.getContext(),
sym);
global = defineGlobal(converter, var, globalName, linkage, dataAttr);
}
auto addrOf = builder.create<fir::AddrOfOp>(loc, global.resultType(),
global.getSymbol());
Fortran::lower::StatementContext stmtCtx;
mapSymbolAttributes(converter, var, symMap, stmtCtx, addrOf);
}
//===----------------------------------------------------------------===//
// Local variables instantiation (not for alias)
//===----------------------------------------------------------------===//
/// Create a stack slot for a local variable. Precondition: the insertion
/// point of the builder must be in the entry block, which is currently being
/// constructed.
static mlir::Value createNewLocal(Fortran::lower::AbstractConverter &converter,
mlir::Location loc,
const Fortran::lower::pft::Variable &var,
mlir::Value preAlloc,
llvm::ArrayRef<mlir::Value> shape = {},
llvm::ArrayRef<mlir::Value> lenParams = {}) {
if (preAlloc)
return preAlloc;
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
std::string nm = converter.mangleName(var.getSymbol());
mlir::Type ty = converter.genType(var);
const Fortran::semantics::Symbol &ultimateSymbol =
var.getSymbol().GetUltimate();
llvm::StringRef symNm = toStringRef(ultimateSymbol.name());
bool isTarg = var.isTarget();
// Do not allocate storage for cray pointee. The address inside the cray
// pointer will be used instead when using the pointee. Allocating space
// would be a waste of space, and incorrect if the pointee is a non dummy
// assumed-size (possible with cray pointee).
if (ultimateSymbol.test(Fortran::semantics::Symbol::Flag::CrayPointee))
return builder.create<fir::ZeroOp>(loc, fir::ReferenceType::get(ty));
if (Fortran::semantics::NeedCUDAAlloc(ultimateSymbol)) {
cuf::DataAttributeAttr dataAttr =
Fortran::lower::translateSymbolCUFDataAttribute(builder.getContext(),
ultimateSymbol);
llvm::SmallVector<mlir::Value> indices;
llvm::SmallVector<mlir::Value> elidedShape =
fir::factory::elideExtentsAlreadyInType(ty, shape);
llvm::SmallVector<mlir::Value> elidedLenParams =
fir::factory::elideLengthsAlreadyInType(ty, lenParams);
auto idxTy = builder.getIndexType();
for (mlir::Value sh : elidedShape)
indices.push_back(builder.createConvert(loc, idxTy, sh));
mlir::Value alloc = builder.create<cuf::AllocOp>(
loc, ty, nm, symNm, dataAttr, lenParams, indices);
return alloc;
}
// Let the builder do all the heavy lifting.
if (!Fortran::semantics::IsProcedurePointer(ultimateSymbol))
return builder.allocateLocal(loc, ty, nm, symNm, shape, lenParams, isTarg);
// Local procedure pointer.
auto res{builder.allocateLocal(loc, ty, nm, symNm, shape, lenParams, isTarg)};
auto box{fir::factory::createNullBoxProc(builder, loc, ty)};
builder.create<fir::StoreOp>(loc, box, res);
return res;
}
/// Must \p var be default initialized at runtime when entering its scope.
static bool
mustBeDefaultInitializedAtRuntime(const Fortran::lower::pft::Variable &var) {
if (!var.hasSymbol())
return false;
const Fortran::semantics::Symbol &sym = var.getSymbol();
if (var.isGlobal())
// Global variables are statically initialized.
return false;
if (Fortran::semantics::IsDummy(sym) && !Fortran::semantics::IsIntentOut(sym))
return false;
// Polymorphic intent(out) dummy might need default initialization
// at runtime.
if (Fortran::semantics::IsPolymorphic(sym) &&
Fortran::semantics::IsDummy(sym) &&
Fortran::semantics::IsIntentOut(sym) &&
!Fortran::semantics::IsAllocatable(sym) &&
!Fortran::semantics::IsPointer(sym))
return true;
// Local variables (including function results), and intent(out) dummies must
// be default initialized at runtime if their type has default initialization.
return Fortran::lower::hasDefaultInitialization(sym);
}
/// Call default initialization runtime routine to initialize \p var.
void Fortran::lower::defaultInitializeAtRuntime(
Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &sym, Fortran::lower::SymMap &symMap) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::Location loc = converter.getCurrentLocation();
fir::ExtendedValue exv = converter.getSymbolExtendedValue(sym, &symMap);
if (Fortran::semantics::IsOptional(sym)) {
// 15.5.2.12 point 3, absent optional dummies are not initialized.
// Creating descriptor/passing null descriptor to the runtime would
// create runtime crashes.
auto isPresent = builder.create<fir::IsPresentOp>(loc, builder.getI1Type(),
fir::getBase(exv));
builder.genIfThen(loc, isPresent)
.genThen([&]() {
auto box = builder.createBox(loc, exv);
fir::runtime::genDerivedTypeInitialize(builder, loc, box);
})
.end();
} else {
/// For "simpler" types, relying on "_FortranAInitialize"
/// leads to poor runtime performance. Hence optimize
/// the same.
const Fortran::semantics::DeclTypeSpec *declTy = sym.GetType();
mlir::Type symTy = converter.genType(sym);
const auto *details =
sym.detailsIf<Fortran::semantics::ObjectEntityDetails>();
if (details && !Fortran::semantics::IsPolymorphic(sym) &&
declTy->category() ==
Fortran::semantics::DeclTypeSpec::Category::TypeDerived &&
!mlir::isa<fir::SequenceType>(symTy) &&
!sym.test(Fortran::semantics::Symbol::Flag::OmpPrivate) &&
!sym.test(Fortran::semantics::Symbol::Flag::OmpFirstPrivate)) {
std::string globalName = fir::NameUniquer::doGenerated(
(converter.mangleName(*declTy->AsDerived()) + fir::kNameSeparator +
fir::kDerivedTypeInitSuffix)
.str());
mlir::Location loc = genLocation(converter, sym);
mlir::StringAttr linkage = builder.createInternalLinkage();
fir::GlobalOp global = builder.getNamedGlobal(globalName);
if (!global && details->init()) {
global = builder.createGlobal(loc, symTy, globalName, linkage,
mlir::Attribute{},
/*isConst=*/true,
/*isTarget=*/false,
/*dataAttr=*/{});
Fortran::lower::createGlobalInitialization(
builder, global, [&](fir::FirOpBuilder &builder) {
Fortran::lower::StatementContext stmtCtx(
/*cleanupProhibited=*/true);
fir::ExtendedValue initVal = genInitializerExprValue(
converter, loc, details->init().value(), stmtCtx);
mlir::Value castTo =
builder.createConvert(loc, symTy, fir::getBase(initVal));
builder.create<fir::HasValueOp>(loc, castTo);
});
} else if (!global) {
global = builder.createGlobal(loc, symTy, globalName, linkage,
mlir::Attribute{},
/*isConst=*/true,
/*isTarget=*/false,
/*dataAttr=*/{});
Fortran::lower::createGlobalInitialization(
builder, global, [&](fir::FirOpBuilder &builder) {
Fortran::lower::StatementContext stmtCtx(
/*cleanupProhibited=*/true);
mlir::Value initVal = genDefaultInitializerValue(
converter, loc, sym, symTy, stmtCtx);
mlir::Value castTo = builder.createConvert(loc, symTy, initVal);
builder.create<fir::HasValueOp>(loc, castTo);
});
}
auto addrOf = builder.create<fir::AddrOfOp>(loc, global.resultType(),
global.getSymbol());
fir::LoadOp load = builder.create<fir::LoadOp>(loc, addrOf.getResult());
// FIXME: Use memcpy instead of store.
builder.create<fir::StoreOp>(loc, load, fir::getBase(exv));
} else {
mlir::Value box = builder.createBox(loc, exv);
fir::runtime::genDerivedTypeInitialize(builder, loc, box);
}
}
}
/// Call clone initialization runtime routine to initialize \p sym's value.
void Fortran::lower::initializeCloneAtRuntime(
Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &sym, Fortran::lower::SymMap &symMap) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::Location loc = converter.getCurrentLocation();
fir::ExtendedValue exv = converter.getSymbolExtendedValue(sym, &symMap);
mlir::Value newBox = builder.createBox(loc, exv);
lower::SymbolBox hsb = converter.lookupOneLevelUpSymbol(sym);
fir::ExtendedValue hexv = converter.symBoxToExtendedValue(hsb);
mlir::Value box = builder.createBox(loc, hexv);
fir::runtime::genDerivedTypeInitializeClone(builder, loc, newBox, box);
}
enum class VariableCleanUp { Finalize, Deallocate };
/// Check whether a local variable needs to be finalized according to clause
/// 7.5.6.3 point 3 or if it is an allocatable that must be deallocated. Note
/// that deallocation will trigger finalization if the type has any.
static std::optional<VariableCleanUp>
needDeallocationOrFinalization(const Fortran::lower::pft::Variable &var) {
if (!var.hasSymbol())
return std::nullopt;
const Fortran::semantics::Symbol &sym = var.getSymbol();
const Fortran::semantics::Scope &owner = sym.owner();
if (owner.kind() == Fortran::semantics::Scope::Kind::MainProgram) {
// The standard does not require finalizing main program variables.
return std::nullopt;
}
if (!Fortran::semantics::IsPointer(sym) &&
!Fortran::semantics::IsDummy(sym) &&
!Fortran::semantics::IsFunctionResult(sym) &&
!Fortran::semantics::IsSaved(sym)) {
if (Fortran::semantics::IsAllocatable(sym))
return VariableCleanUp::Deallocate;
if (hasFinalization(sym))
return VariableCleanUp::Finalize;
// hasFinalization() check above handled all cases that require
// finalization, but we also have to deallocate all allocatable
// components of local variables (since they are also local variables
// according to F18 5.4.3.2.2, p. 2, note 1).
// Here, the variable itself is not allocatable. If it has an allocatable
// component the Destroy runtime does the job. Use the Finalize clean-up,
// though there will be no finalization in runtime.
if (hasAllocatableDirectComponent(sym))
return VariableCleanUp::Finalize;
}
return std::nullopt;
}
/// Check whether a variable needs the be finalized according to clause 7.5.6.3
/// point 7.
/// Must be nonpointer, nonallocatable, INTENT (OUT) dummy argument.
static bool
needDummyIntentoutFinalization(const Fortran::lower::pft::Variable &var) {
if (!var.hasSymbol())
return false;
const Fortran::semantics::Symbol &sym = var.getSymbol();
if (!Fortran::semantics::IsDummy(sym) ||
!Fortran::semantics::IsIntentOut(sym) ||
Fortran::semantics::IsAllocatable(sym) ||
Fortran::semantics::IsPointer(sym))
return false;
// Polymorphic and unlimited polymorphic intent(out) dummy argument might need
// finalization at runtime.
if (Fortran::semantics::IsPolymorphic(sym) ||
Fortran::semantics::IsUnlimitedPolymorphic(sym))
return true;
// Intent(out) dummies must be finalized at runtime if their type has a
// finalization.
// Allocatable components of INTENT(OUT) dummies must be deallocated (9.7.3.2
// p6). Calling finalization runtime for this works even if the components
// have no final procedures.
return hasFinalization(sym) || hasAllocatableDirectComponent(sym);
}
/// Call default initialization runtime routine to initialize \p var.
static void finalizeAtRuntime(Fortran::lower::AbstractConverter &converter,
const Fortran::lower::pft::Variable &var,
Fortran::lower::SymMap &symMap) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::Location loc = converter.getCurrentLocation();
const Fortran::semantics::Symbol &sym = var.getSymbol();
fir::ExtendedValue exv = converter.getSymbolExtendedValue(sym, &symMap);
if (Fortran::semantics::IsOptional(sym)) {
// Only finalize if present.
auto isPresent = builder.create<fir::IsPresentOp>(loc, builder.getI1Type(),
fir::getBase(exv));
builder.genIfThen(loc, isPresent)
.genThen([&]() {
auto box = builder.createBox(loc, exv);
fir::runtime::genDerivedTypeDestroy(builder, loc, box);
})
.end();
} else {
mlir::Value box = builder.createBox(loc, exv);
fir::runtime::genDerivedTypeDestroy(builder, loc, box);
}
}
// Fortran 2018 - 9.7.3.2 point 6
// When a procedure is invoked, any allocated allocatable object that is an
// actual argument corresponding to an INTENT(OUT) allocatable dummy argument
// is deallocated; any allocated allocatable object that is a subobject of an
// actual argument corresponding to an INTENT(OUT) dummy argument is
// deallocated.
// Note that allocatable components of non-ALLOCATABLE INTENT(OUT) dummy
// arguments are dealt with needDummyIntentoutFinalization (finalization runtime
// is called to reach the intended component deallocation effect).
static void deallocateIntentOut(Fortran::lower::AbstractConverter &converter,
const Fortran::lower::pft::Variable &var,
Fortran::lower::SymMap &symMap) {
if (!var.hasSymbol())
return;
const Fortran::semantics::Symbol &sym = var.getSymbol();
if (Fortran::semantics::IsDummy(sym) &&
Fortran::semantics::IsIntentOut(sym) &&
Fortran::semantics::IsAllocatable(sym)) {
fir::ExtendedValue extVal = converter.getSymbolExtendedValue(sym, &symMap);
if (auto mutBox = extVal.getBoxOf<fir::MutableBoxValue>()) {
// The dummy argument is not passed in the ENTRY so it should not be
// deallocated.
if (mlir::Operation *op = mutBox->getAddr().getDefiningOp()) {
if (auto declOp = mlir::dyn_cast<hlfir::DeclareOp>(op))
op = declOp.getMemref().getDefiningOp();
if (op && mlir::isa<fir::AllocaOp>(op))
return;
}
mlir::Location loc = converter.getCurrentLocation();
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
if (Fortran::semantics::IsOptional(sym)) {
auto isPresent = builder.create<fir::IsPresentOp>(
loc, builder.getI1Type(), fir::getBase(extVal));
builder.genIfThen(loc, isPresent)
.genThen([&]() {