1 //===-- Bridge.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/Bridge.h" 14 #include "flang/Lower/Allocatable.h" 15 #include "flang/Lower/CallInterface.h" 16 #include "flang/Lower/Coarray.h" 17 #include "flang/Lower/ConvertExpr.h" 18 #include "flang/Lower/ConvertType.h" 19 #include "flang/Lower/ConvertVariable.h" 20 #include "flang/Lower/HostAssociations.h" 21 #include "flang/Lower/IO.h" 22 #include "flang/Lower/IterationSpace.h" 23 #include "flang/Lower/Mangler.h" 24 #include "flang/Lower/OpenACC.h" 25 #include "flang/Lower/OpenMP.h" 26 #include "flang/Lower/PFTBuilder.h" 27 #include "flang/Lower/Runtime.h" 28 #include "flang/Lower/StatementContext.h" 29 #include "flang/Lower/Support/Utils.h" 30 #include "flang/Lower/Todo.h" 31 #include "flang/Optimizer/Builder/BoxValue.h" 32 #include "flang/Optimizer/Builder/Character.h" 33 #include "flang/Optimizer/Builder/FIRBuilder.h" 34 #include "flang/Optimizer/Builder/Runtime/Character.h" 35 #include "flang/Optimizer/Builder/Runtime/Ragged.h" 36 #include "flang/Optimizer/Dialect/FIRAttr.h" 37 #include "flang/Optimizer/Dialect/FIRDialect.h" 38 #include "flang/Optimizer/Dialect/FIROps.h" 39 #include "flang/Optimizer/Support/FIRContext.h" 40 #include "flang/Optimizer/Support/FatalError.h" 41 #include "flang/Optimizer/Support/InternalNames.h" 42 #include "flang/Optimizer/Transforms/Passes.h" 43 #include "flang/Parser/parse-tree.h" 44 #include "flang/Runtime/iostat.h" 45 #include "flang/Semantics/tools.h" 46 #include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h" 47 #include "mlir/IR/PatternMatch.h" 48 #include "mlir/Parser/Parser.h" 49 #include "mlir/Transforms/RegionUtils.h" 50 #include "llvm/Support/CommandLine.h" 51 #include "llvm/Support/Debug.h" 52 #include "llvm/Support/ErrorHandling.h" 53 54 #define DEBUG_TYPE "flang-lower-bridge" 55 56 static llvm::cl::opt<bool> dumpBeforeFir( 57 "fdebug-dump-pre-fir", llvm::cl::init(false), 58 llvm::cl::desc("dump the Pre-FIR tree prior to FIR generation")); 59 60 static llvm::cl::opt<bool> forceLoopToExecuteOnce( 61 "always-execute-loop-body", llvm::cl::init(false), 62 llvm::cl::desc("force the body of a loop to execute at least once")); 63 64 namespace { 65 /// Information for generating a structured or unstructured increment loop. 66 struct IncrementLoopInfo { 67 template <typename T> 68 explicit IncrementLoopInfo(Fortran::semantics::Symbol &sym, const T &lower, 69 const T &upper, const std::optional<T> &step, 70 bool isUnordered = false) 71 : loopVariableSym{sym}, lowerExpr{Fortran::semantics::GetExpr(lower)}, 72 upperExpr{Fortran::semantics::GetExpr(upper)}, 73 stepExpr{Fortran::semantics::GetExpr(step)}, isUnordered{isUnordered} {} 74 75 IncrementLoopInfo(IncrementLoopInfo &&) = default; 76 IncrementLoopInfo &operator=(IncrementLoopInfo &&x) { return x; } 77 78 bool isStructured() const { return !headerBlock; } 79 80 mlir::Type getLoopVariableType() const { 81 assert(loopVariable && "must be set"); 82 return fir::unwrapRefType(loopVariable.getType()); 83 } 84 85 // Data members common to both structured and unstructured loops. 86 const Fortran::semantics::Symbol &loopVariableSym; 87 const Fortran::lower::SomeExpr *lowerExpr; 88 const Fortran::lower::SomeExpr *upperExpr; 89 const Fortran::lower::SomeExpr *stepExpr; 90 bool isUnordered; // do concurrent, forall 91 mlir::Value loopVariable = nullptr; 92 mlir::Value stepValue = nullptr; // possible uses in multiple blocks 93 94 // Data members for structured loops. 95 fir::DoLoopOp doLoop = nullptr; 96 97 // Data members for unstructured loops. 98 bool hasRealControl = false; 99 mlir::Value tripVariable = nullptr; 100 mlir::Block *headerBlock = nullptr; // loop entry and test block 101 mlir::Block *bodyBlock = nullptr; // first loop body block 102 mlir::Block *exitBlock = nullptr; // loop exit target block 103 }; 104 105 /// Helper class to generate the runtime type info global data. This data 106 /// is required to describe the derived type to the runtime so that it can 107 /// operate over it. It must be ensured this data will be generated for every 108 /// derived type lowered in the current translated unit. However, this data 109 /// cannot be generated before FuncOp have been created for functions since the 110 /// initializers may take their address (e.g for type bound procedures). This 111 /// class allows registering all the required runtime type info while it is not 112 /// possible to create globals, and to generate this data after function 113 /// lowering. 114 class RuntimeTypeInfoConverter { 115 /// Store the location and symbols of derived type info to be generated. 116 /// The location of the derived type instantiation is also stored because 117 /// runtime type descriptor symbol are compiler generated and cannot be mapped 118 /// to user code on their own. 119 struct TypeInfoSymbol { 120 Fortran::semantics::SymbolRef symbol; 121 mlir::Location loc; 122 }; 123 124 public: 125 void registerTypeInfoSymbol(Fortran::lower::AbstractConverter &converter, 126 mlir::Location loc, 127 Fortran::semantics::SymbolRef typeInfoSym) { 128 if (seen.contains(typeInfoSym)) 129 return; 130 seen.insert(typeInfoSym); 131 if (!skipRegistration) { 132 registeredTypeInfoSymbols.emplace_back(TypeInfoSymbol{typeInfoSym, loc}); 133 return; 134 } 135 // Once the registration is closed, symbols cannot be added to the 136 // registeredTypeInfoSymbols list because it may be iterated over. 137 // However, after registration is closed, it is safe to directly generate 138 // the globals because all FuncOps whose addresses may be required by the 139 // initializers have been generated. 140 Fortran::lower::createRuntimeTypeInfoGlobal(converter, loc, 141 typeInfoSym.get()); 142 } 143 144 void createTypeInfoGlobals(Fortran::lower::AbstractConverter &converter) { 145 skipRegistration = true; 146 for (const TypeInfoSymbol &info : registeredTypeInfoSymbols) 147 Fortran::lower::createRuntimeTypeInfoGlobal(converter, info.loc, 148 info.symbol.get()); 149 registeredTypeInfoSymbols.clear(); 150 } 151 152 private: 153 /// Store the runtime type descriptors that will be required for the 154 /// derived type that have been converted to FIR derived types. 155 llvm::SmallVector<TypeInfoSymbol> registeredTypeInfoSymbols; 156 /// Create derived type runtime info global immediately without storing the 157 /// symbol in registeredTypeInfoSymbols. 158 bool skipRegistration = false; 159 /// Track symbols symbols processed during and after the registration 160 /// to avoid infinite loops between type conversions and global variable 161 /// creation. 162 llvm::SmallSetVector<Fortran::semantics::SymbolRef, 64> seen; 163 }; 164 165 using IncrementLoopNestInfo = llvm::SmallVector<IncrementLoopInfo>; 166 } // namespace 167 168 //===----------------------------------------------------------------------===// 169 // FirConverter 170 //===----------------------------------------------------------------------===// 171 172 namespace { 173 174 /// Traverse the pre-FIR tree (PFT) to generate the FIR dialect of MLIR. 175 class FirConverter : public Fortran::lower::AbstractConverter { 176 public: 177 explicit FirConverter(Fortran::lower::LoweringBridge &bridge) 178 : bridge{bridge}, foldingContext{bridge.createFoldingContext()} {} 179 virtual ~FirConverter() = default; 180 181 /// Convert the PFT to FIR. 182 void run(Fortran::lower::pft::Program &pft) { 183 // Preliminary translation pass. 184 185 // - Lower common blocks from the PFT common block list that contains a 186 // consolidated list of the common blocks (with the initialization if any in 187 // the Program, and with the common block biggest size in all its 188 // appearance). This is done before lowering any scope declarations because 189 // it is not know at the local scope level what MLIR type common blocks 190 // should have to suit all its usage in the compilation unit. 191 lowerCommonBlocks(pft.getCommonBlocks()); 192 193 // - Declare all functions that have definitions so that definition 194 // signatures prevail over call site signatures. 195 // - Define module variables and OpenMP/OpenACC declarative construct so 196 // that they are available before lowering any function that may use 197 // them. 198 for (Fortran::lower::pft::Program::Units &u : pft.getUnits()) { 199 std::visit(Fortran::common::visitors{ 200 [&](Fortran::lower::pft::FunctionLikeUnit &f) { 201 declareFunction(f); 202 }, 203 [&](Fortran::lower::pft::ModuleLikeUnit &m) { 204 lowerModuleDeclScope(m); 205 for (Fortran::lower::pft::FunctionLikeUnit &f : 206 m.nestedFunctions) 207 declareFunction(f); 208 }, 209 [&](Fortran::lower::pft::BlockDataUnit &b) {}, 210 [&](Fortran::lower::pft::CompilerDirectiveUnit &d) {}, 211 }, 212 u); 213 } 214 215 // Primary translation pass. 216 for (Fortran::lower::pft::Program::Units &u : pft.getUnits()) { 217 std::visit( 218 Fortran::common::visitors{ 219 [&](Fortran::lower::pft::FunctionLikeUnit &f) { lowerFunc(f); }, 220 [&](Fortran::lower::pft::ModuleLikeUnit &m) { lowerMod(m); }, 221 [&](Fortran::lower::pft::BlockDataUnit &b) {}, 222 [&](Fortran::lower::pft::CompilerDirectiveUnit &d) { 223 setCurrentPosition( 224 d.get<Fortran::parser::CompilerDirective>().source); 225 mlir::emitWarning(toLocation(), 226 "ignoring all compiler directives"); 227 }, 228 }, 229 u); 230 } 231 232 /// Once all the code has been translated, create runtime type info 233 /// global data structure for the derived types that have been 234 /// processed. 235 createGlobalOutsideOfFunctionLowering( 236 [&]() { runtimeTypeInfoConverter.createTypeInfoGlobals(*this); }); 237 } 238 239 /// Declare a function. 240 void declareFunction(Fortran::lower::pft::FunctionLikeUnit &funit) { 241 setCurrentPosition(funit.getStartingSourceLoc()); 242 for (int entryIndex = 0, last = funit.entryPointList.size(); 243 entryIndex < last; ++entryIndex) { 244 funit.setActiveEntry(entryIndex); 245 // Calling CalleeInterface ctor will build a declaration 246 // mlir::func::FuncOp with no other side effects. 247 // TODO: when doing some compiler profiling on real apps, it may be worth 248 // to check it's better to save the CalleeInterface instead of recomputing 249 // it later when lowering the body. CalleeInterface ctor should be linear 250 // with the number of arguments, so it is not awful to do it that way for 251 // now, but the linear coefficient might be non negligible. Until 252 // measured, stick to the solution that impacts the code less. 253 Fortran::lower::CalleeInterface{funit, *this}; 254 } 255 funit.setActiveEntry(0); 256 257 // Compute the set of host associated entities from the nested functions. 258 llvm::SetVector<const Fortran::semantics::Symbol *> escapeHost; 259 for (Fortran::lower::pft::FunctionLikeUnit &f : funit.nestedFunctions) 260 collectHostAssociatedVariables(f, escapeHost); 261 funit.setHostAssociatedSymbols(escapeHost); 262 263 // Declare internal procedures 264 for (Fortran::lower::pft::FunctionLikeUnit &f : funit.nestedFunctions) 265 declareFunction(f); 266 } 267 268 /// Collects the canonical list of all host associated symbols. These bindings 269 /// must be aggregated into a tuple which can then be added to each of the 270 /// internal procedure declarations and passed at each call site. 271 void collectHostAssociatedVariables( 272 Fortran::lower::pft::FunctionLikeUnit &funit, 273 llvm::SetVector<const Fortran::semantics::Symbol *> &escapees) { 274 const Fortran::semantics::Scope *internalScope = 275 funit.getSubprogramSymbol().scope(); 276 assert(internalScope && "internal procedures symbol must create a scope"); 277 auto addToListIfEscapee = [&](const Fortran::semantics::Symbol &sym) { 278 const Fortran::semantics::Symbol &ultimate = sym.GetUltimate(); 279 const auto *namelistDetails = 280 ultimate.detailsIf<Fortran::semantics::NamelistDetails>(); 281 if (ultimate.has<Fortran::semantics::ObjectEntityDetails>() || 282 Fortran::semantics::IsProcedurePointer(ultimate) || 283 Fortran::semantics::IsDummy(sym) || namelistDetails) { 284 const Fortran::semantics::Scope &ultimateScope = ultimate.owner(); 285 if (ultimateScope.kind() == 286 Fortran::semantics::Scope::Kind::MainProgram || 287 ultimateScope.kind() == Fortran::semantics::Scope::Kind::Subprogram) 288 if (ultimateScope != *internalScope && 289 ultimateScope.Contains(*internalScope)) { 290 if (namelistDetails) { 291 // So far, namelist symbols are processed on the fly in IO and 292 // the related namelist data structure is not added to the symbol 293 // map, so it cannot be passed to the internal procedures. 294 // Instead, all the symbols of the host namelist used in the 295 // internal procedure must be considered as host associated so 296 // that IO lowering can find them when needed. 297 for (const auto &namelistObject : namelistDetails->objects()) 298 escapees.insert(&*namelistObject); 299 } else { 300 escapees.insert(&ultimate); 301 } 302 } 303 } 304 }; 305 Fortran::lower::pft::visitAllSymbols(funit, addToListIfEscapee); 306 } 307 308 //===--------------------------------------------------------------------===// 309 // AbstractConverter overrides 310 //===--------------------------------------------------------------------===// 311 312 mlir::Value getSymbolAddress(Fortran::lower::SymbolRef sym) override final { 313 return lookupSymbol(sym).getAddr(); 314 } 315 316 mlir::Value impliedDoBinding(llvm::StringRef name) override final { 317 mlir::Value val = localSymbols.lookupImpliedDo(name); 318 if (!val) 319 fir::emitFatalError(toLocation(), "ac-do-variable has no binding"); 320 return val; 321 } 322 323 void copySymbolBinding(Fortran::lower::SymbolRef src, 324 Fortran::lower::SymbolRef target) override final { 325 localSymbols.addSymbol(target, lookupSymbol(src).toExtendedValue()); 326 } 327 328 /// Add the symbol binding to the inner-most level of the symbol map and 329 /// return true if it is not already present. Otherwise, return false. 330 bool bindIfNewSymbol(Fortran::lower::SymbolRef sym, 331 const fir::ExtendedValue &exval) { 332 if (shallowLookupSymbol(sym)) 333 return false; 334 bindSymbol(sym, exval); 335 return true; 336 } 337 338 void bindSymbol(Fortran::lower::SymbolRef sym, 339 const fir::ExtendedValue &exval) override final { 340 localSymbols.addSymbol(sym, exval, /*forced=*/true); 341 } 342 343 bool lookupLabelSet(Fortran::lower::SymbolRef sym, 344 Fortran::lower::pft::LabelSet &labelSet) override final { 345 Fortran::lower::pft::FunctionLikeUnit &owningProc = 346 *getEval().getOwningProcedure(); 347 auto iter = owningProc.assignSymbolLabelMap.find(sym); 348 if (iter == owningProc.assignSymbolLabelMap.end()) 349 return false; 350 labelSet = iter->second; 351 return true; 352 } 353 354 Fortran::lower::pft::Evaluation * 355 lookupLabel(Fortran::lower::pft::Label label) override final { 356 Fortran::lower::pft::FunctionLikeUnit &owningProc = 357 *getEval().getOwningProcedure(); 358 auto iter = owningProc.labelEvaluationMap.find(label); 359 if (iter == owningProc.labelEvaluationMap.end()) 360 return nullptr; 361 return iter->second; 362 } 363 364 fir::ExtendedValue genExprAddr(const Fortran::lower::SomeExpr &expr, 365 Fortran::lower::StatementContext &context, 366 mlir::Location *loc = nullptr) override final { 367 return Fortran::lower::createSomeExtendedAddress( 368 loc ? *loc : toLocation(), *this, expr, localSymbols, context); 369 } 370 fir::ExtendedValue 371 genExprValue(const Fortran::lower::SomeExpr &expr, 372 Fortran::lower::StatementContext &context, 373 mlir::Location *loc = nullptr) override final { 374 return Fortran::lower::createSomeExtendedExpression( 375 loc ? *loc : toLocation(), *this, expr, localSymbols, context); 376 } 377 378 fir::ExtendedValue 379 genExprBox(mlir::Location loc, const Fortran::lower::SomeExpr &expr, 380 Fortran::lower::StatementContext &stmtCtx) override final { 381 return Fortran::lower::createBoxValue(loc, *this, expr, localSymbols, 382 stmtCtx); 383 } 384 385 Fortran::evaluate::FoldingContext &getFoldingContext() override final { 386 return foldingContext; 387 } 388 389 mlir::Type genType(const Fortran::lower::SomeExpr &expr) override final { 390 return Fortran::lower::translateSomeExprToFIRType(*this, expr); 391 } 392 mlir::Type genType(const Fortran::lower::pft::Variable &var) override final { 393 return Fortran::lower::translateVariableToFIRType(*this, var); 394 } 395 mlir::Type genType(Fortran::lower::SymbolRef sym) override final { 396 return Fortran::lower::translateSymbolToFIRType(*this, sym); 397 } 398 mlir::Type 399 genType(Fortran::common::TypeCategory tc, int kind, 400 llvm::ArrayRef<std::int64_t> lenParameters) override final { 401 return Fortran::lower::getFIRType(&getMLIRContext(), tc, kind, 402 lenParameters); 403 } 404 mlir::Type 405 genType(const Fortran::semantics::DerivedTypeSpec &tySpec) override final { 406 return Fortran::lower::translateDerivedTypeToFIRType(*this, tySpec); 407 } 408 mlir::Type genType(Fortran::common::TypeCategory tc) override final { 409 return Fortran::lower::getFIRType( 410 &getMLIRContext(), tc, bridge.getDefaultKinds().GetDefaultKind(tc), 411 llvm::None); 412 } 413 414 bool createHostAssociateVarClone( 415 const Fortran::semantics::Symbol &sym) override final { 416 mlir::Location loc = genLocation(sym.name()); 417 mlir::Type symType = genType(sym); 418 const auto *details = sym.detailsIf<Fortran::semantics::HostAssocDetails>(); 419 assert(details && "No host-association found"); 420 const Fortran::semantics::Symbol &hsym = details->symbol(); 421 Fortran::lower::SymbolBox hsb = lookupSymbol(hsym); 422 423 auto allocate = [&](llvm::ArrayRef<mlir::Value> shape, 424 llvm::ArrayRef<mlir::Value> typeParams) -> mlir::Value { 425 mlir::Value allocVal = builder->allocateLocal( 426 loc, symType, mangleName(sym), toStringRef(sym.GetUltimate().name()), 427 /*pinned=*/true, shape, typeParams, 428 sym.GetUltimate().attrs().test(Fortran::semantics::Attr::TARGET)); 429 return allocVal; 430 }; 431 432 fir::ExtendedValue hexv = getExtendedValue(hsb); 433 fir::ExtendedValue exv = hexv.match( 434 [&](const fir::BoxValue &box) -> fir::ExtendedValue { 435 const Fortran::semantics::DeclTypeSpec *type = sym.GetType(); 436 if (type && type->IsPolymorphic()) 437 TODO(loc, "create polymorphic host associated copy"); 438 // Create a contiguous temp with the same shape and length as 439 // the original variable described by a fir.box. 440 llvm::SmallVector<mlir::Value> extents = 441 fir::factory::getExtents(loc, *builder, hexv); 442 if (box.isDerivedWithLenParameters()) 443 TODO(loc, "get length parameters from derived type BoxValue"); 444 if (box.isCharacter()) { 445 mlir::Value len = fir::factory::readCharLen(*builder, loc, box); 446 mlir::Value temp = allocate(extents, {len}); 447 return fir::CharArrayBoxValue{temp, len, extents}; 448 } 449 return fir::ArrayBoxValue{allocate(extents, {}), extents}; 450 }, 451 [&](const fir::MutableBoxValue &box) -> fir::ExtendedValue { 452 // Allocate storage for a pointer/allocatble descriptor. 453 // No shape/lengths to be passed to the alloca. 454 return fir::MutableBoxValue(allocate({}, {}), 455 box.nonDeferredLenParams(), {}); 456 }, 457 [&](const auto &) -> fir::ExtendedValue { 458 mlir::Value temp = 459 allocate(fir::factory::getExtents(loc, *builder, hexv), 460 fir::getTypeParams(hexv)); 461 return fir::substBase(hexv, temp); 462 }); 463 464 return bindIfNewSymbol(sym, exv); 465 } 466 467 void 468 copyHostAssociateVar(const Fortran::semantics::Symbol &sym) override final { 469 // 1) Fetch the original copy of the variable. 470 assert(sym.has<Fortran::semantics::HostAssocDetails>() && 471 "No host-association found"); 472 const Fortran::semantics::Symbol &hsym = sym.GetUltimate(); 473 Fortran::lower::SymbolBox hsb = lookupSymbol(hsym); 474 fir::ExtendedValue hexv = getExtendedValue(hsb); 475 476 // 2) Create a copy that will mask the original. 477 createHostAssociateVarClone(sym); 478 Fortran::lower::SymbolBox sb = lookupSymbol(sym); 479 fir::ExtendedValue exv = getExtendedValue(sb); 480 481 // 3) Perform the assignment. 482 mlir::Location loc = genLocation(sym.name()); 483 mlir::Type symType = genType(sym); 484 if (auto seqTy = symType.dyn_cast<fir::SequenceType>()) { 485 Fortran::lower::StatementContext stmtCtx; 486 Fortran::lower::createSomeArrayAssignment(*this, exv, hexv, localSymbols, 487 stmtCtx); 488 stmtCtx.finalize(); 489 } else if (hexv.getBoxOf<fir::CharBoxValue>()) { 490 fir::factory::CharacterExprHelper{*builder, loc}.createAssign(exv, hexv); 491 } else if (hexv.getBoxOf<fir::MutableBoxValue>()) { 492 TODO(loc, "firstprivatisation of allocatable variables"); 493 } else { 494 auto loadVal = builder->create<fir::LoadOp>(loc, fir::getBase(hexv)); 495 builder->create<fir::StoreOp>(loc, loadVal, fir::getBase(exv)); 496 } 497 } 498 499 //===--------------------------------------------------------------------===// 500 // Utility methods 501 //===--------------------------------------------------------------------===// 502 503 mlir::Location getCurrentLocation() override final { return toLocation(); } 504 505 /// Generate a dummy location. 506 mlir::Location genUnknownLocation() override final { 507 // Note: builder may not be instantiated yet 508 return mlir::UnknownLoc::get(&getMLIRContext()); 509 } 510 511 /// Generate a `Location` from the `CharBlock`. 512 mlir::Location 513 genLocation(const Fortran::parser::CharBlock &block) override final { 514 if (const Fortran::parser::AllCookedSources *cooked = 515 bridge.getCookedSource()) { 516 if (std::optional<std::pair<Fortran::parser::SourcePosition, 517 Fortran::parser::SourcePosition>> 518 loc = cooked->GetSourcePositionRange(block)) { 519 // loc is a pair (begin, end); use the beginning position 520 Fortran::parser::SourcePosition &filePos = loc->first; 521 return mlir::FileLineColLoc::get(&getMLIRContext(), filePos.file.path(), 522 filePos.line, filePos.column); 523 } 524 } 525 return genUnknownLocation(); 526 } 527 528 fir::FirOpBuilder &getFirOpBuilder() override final { return *builder; } 529 530 mlir::ModuleOp &getModuleOp() override final { return bridge.getModule(); } 531 532 mlir::MLIRContext &getMLIRContext() override final { 533 return bridge.getMLIRContext(); 534 } 535 std::string 536 mangleName(const Fortran::semantics::Symbol &symbol) override final { 537 return Fortran::lower::mangle::mangleName(symbol); 538 } 539 540 const fir::KindMapping &getKindMap() override final { 541 return bridge.getKindMap(); 542 } 543 544 mlir::Value hostAssocTupleValue() override final { return hostAssocTuple; } 545 546 /// Record a binding for the ssa-value of the tuple for this function. 547 void bindHostAssocTuple(mlir::Value val) override final { 548 assert(!hostAssocTuple && val); 549 hostAssocTuple = val; 550 } 551 552 void registerRuntimeTypeInfo( 553 mlir::Location loc, 554 Fortran::lower::SymbolRef typeInfoSym) override final { 555 runtimeTypeInfoConverter.registerTypeInfoSymbol(*this, loc, typeInfoSym); 556 } 557 558 private: 559 FirConverter() = delete; 560 FirConverter(const FirConverter &) = delete; 561 FirConverter &operator=(const FirConverter &) = delete; 562 563 //===--------------------------------------------------------------------===// 564 // Helper member functions 565 //===--------------------------------------------------------------------===// 566 567 mlir::Value createFIRExpr(mlir::Location loc, 568 const Fortran::lower::SomeExpr *expr, 569 Fortran::lower::StatementContext &stmtCtx) { 570 return fir::getBase(genExprValue(*expr, stmtCtx, &loc)); 571 } 572 573 /// Find the symbol in the local map or return null. 574 Fortran::lower::SymbolBox 575 lookupSymbol(const Fortran::semantics::Symbol &sym) { 576 if (Fortran::lower::SymbolBox v = localSymbols.lookupSymbol(sym)) 577 return v; 578 return {}; 579 } 580 581 /// Find the symbol in the inner-most level of the local map or return null. 582 Fortran::lower::SymbolBox 583 shallowLookupSymbol(const Fortran::semantics::Symbol &sym) { 584 if (Fortran::lower::SymbolBox v = localSymbols.shallowLookupSymbol(sym)) 585 return v; 586 return {}; 587 } 588 589 /// Add the symbol to the local map and return `true`. If the symbol is 590 /// already in the map and \p forced is `false`, the map is not updated. 591 /// Instead the value `false` is returned. 592 bool addSymbol(const Fortran::semantics::SymbolRef sym, mlir::Value val, 593 bool forced = false) { 594 if (!forced && lookupSymbol(sym)) 595 return false; 596 localSymbols.addSymbol(sym, val, forced); 597 return true; 598 } 599 600 bool addCharSymbol(const Fortran::semantics::SymbolRef sym, mlir::Value val, 601 mlir::Value len, bool forced = false) { 602 if (!forced && lookupSymbol(sym)) 603 return false; 604 // TODO: ensure val type is fir.array<len x fir.char<kind>> like. Insert 605 // cast if needed. 606 localSymbols.addCharSymbol(sym, val, len, forced); 607 return true; 608 } 609 610 fir::ExtendedValue getExtendedValue(Fortran::lower::SymbolBox sb) { 611 return sb.match( 612 [&](const Fortran::lower::SymbolBox::PointerOrAllocatable &box) { 613 return fir::factory::genMutableBoxRead(*builder, getCurrentLocation(), 614 box); 615 }, 616 [&sb](auto &) { return sb.toExtendedValue(); }); 617 } 618 619 /// Generate the address of loop variable \p sym. 620 mlir::Value genLoopVariableAddress(mlir::Location loc, 621 const Fortran::semantics::Symbol &sym) { 622 assert(lookupSymbol(sym) && "loop control variable must already be in map"); 623 Fortran::lower::StatementContext stmtCtx; 624 return fir::getBase( 625 genExprAddr(Fortran::evaluate::AsGenericExpr(sym).value(), stmtCtx)); 626 } 627 628 static bool isNumericScalarCategory(Fortran::common::TypeCategory cat) { 629 return cat == Fortran::common::TypeCategory::Integer || 630 cat == Fortran::common::TypeCategory::Real || 631 cat == Fortran::common::TypeCategory::Complex || 632 cat == Fortran::common::TypeCategory::Logical; 633 } 634 static bool isLogicalCategory(Fortran::common::TypeCategory cat) { 635 return cat == Fortran::common::TypeCategory::Logical; 636 } 637 static bool isCharacterCategory(Fortran::common::TypeCategory cat) { 638 return cat == Fortran::common::TypeCategory::Character; 639 } 640 static bool isDerivedCategory(Fortran::common::TypeCategory cat) { 641 return cat == Fortran::common::TypeCategory::Derived; 642 } 643 644 /// Insert a new block before \p block. Leave the insertion point unchanged. 645 mlir::Block *insertBlock(mlir::Block *block) { 646 mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint(); 647 mlir::Block *newBlock = builder->createBlock(block); 648 builder->restoreInsertionPoint(insertPt); 649 return newBlock; 650 } 651 652 mlir::Block *blockOfLabel(Fortran::lower::pft::Evaluation &eval, 653 Fortran::parser::Label label) { 654 const Fortran::lower::pft::LabelEvalMap &labelEvaluationMap = 655 eval.getOwningProcedure()->labelEvaluationMap; 656 const auto iter = labelEvaluationMap.find(label); 657 assert(iter != labelEvaluationMap.end() && "label missing from map"); 658 mlir::Block *block = iter->second->block; 659 assert(block && "missing labeled evaluation block"); 660 return block; 661 } 662 663 void genFIRBranch(mlir::Block *targetBlock) { 664 assert(targetBlock && "missing unconditional target block"); 665 builder->create<mlir::cf::BranchOp>(toLocation(), targetBlock); 666 } 667 668 void genFIRConditionalBranch(mlir::Value cond, mlir::Block *trueTarget, 669 mlir::Block *falseTarget) { 670 assert(trueTarget && "missing conditional branch true block"); 671 assert(falseTarget && "missing conditional branch false block"); 672 mlir::Location loc = toLocation(); 673 mlir::Value bcc = builder->createConvert(loc, builder->getI1Type(), cond); 674 builder->create<mlir::cf::CondBranchOp>(loc, bcc, trueTarget, llvm::None, 675 falseTarget, llvm::None); 676 } 677 void genFIRConditionalBranch(mlir::Value cond, 678 Fortran::lower::pft::Evaluation *trueTarget, 679 Fortran::lower::pft::Evaluation *falseTarget) { 680 genFIRConditionalBranch(cond, trueTarget->block, falseTarget->block); 681 } 682 void genFIRConditionalBranch(const Fortran::parser::ScalarLogicalExpr &expr, 683 mlir::Block *trueTarget, 684 mlir::Block *falseTarget) { 685 Fortran::lower::StatementContext stmtCtx; 686 mlir::Value cond = 687 createFIRExpr(toLocation(), Fortran::semantics::GetExpr(expr), stmtCtx); 688 stmtCtx.finalize(); 689 genFIRConditionalBranch(cond, trueTarget, falseTarget); 690 } 691 void genFIRConditionalBranch(const Fortran::parser::ScalarLogicalExpr &expr, 692 Fortran::lower::pft::Evaluation *trueTarget, 693 Fortran::lower::pft::Evaluation *falseTarget) { 694 Fortran::lower::StatementContext stmtCtx; 695 mlir::Value cond = 696 createFIRExpr(toLocation(), Fortran::semantics::GetExpr(expr), stmtCtx); 697 stmtCtx.finalize(); 698 genFIRConditionalBranch(cond, trueTarget->block, falseTarget->block); 699 } 700 701 //===--------------------------------------------------------------------===// 702 // Termination of symbolically referenced execution units 703 //===--------------------------------------------------------------------===// 704 705 /// END of program 706 /// 707 /// Generate the cleanup block before the program exits 708 void genExitRoutine() { 709 if (blockIsUnterminated()) 710 builder->create<mlir::func::ReturnOp>(toLocation()); 711 } 712 void genFIR(const Fortran::parser::EndProgramStmt &) { genExitRoutine(); } 713 714 /// END of procedure-like constructs 715 /// 716 /// Generate the cleanup block before the procedure exits 717 void genReturnSymbol(const Fortran::semantics::Symbol &functionSymbol) { 718 const Fortran::semantics::Symbol &resultSym = 719 functionSymbol.get<Fortran::semantics::SubprogramDetails>().result(); 720 Fortran::lower::SymbolBox resultSymBox = lookupSymbol(resultSym); 721 mlir::Location loc = toLocation(); 722 if (!resultSymBox) { 723 mlir::emitError(loc, "failed lowering function return"); 724 return; 725 } 726 mlir::Value resultVal = resultSymBox.match( 727 [&](const fir::CharBoxValue &x) -> mlir::Value { 728 return fir::factory::CharacterExprHelper{*builder, loc} 729 .createEmboxChar(x.getBuffer(), x.getLen()); 730 }, 731 [&](const auto &) -> mlir::Value { 732 mlir::Value resultRef = resultSymBox.getAddr(); 733 mlir::Type resultType = genType(resultSym); 734 mlir::Type resultRefType = builder->getRefType(resultType); 735 // A function with multiple entry points returning different types 736 // tags all result variables with one of the largest types to allow 737 // them to share the same storage. Convert this to the actual type. 738 if (resultRef.getType() != resultRefType) 739 resultRef = builder->createConvert(loc, resultRefType, resultRef); 740 return builder->create<fir::LoadOp>(loc, resultRef); 741 }); 742 builder->create<mlir::func::ReturnOp>(loc, resultVal); 743 } 744 745 /// Get the return value of a call to \p symbol, which is a subroutine entry 746 /// point that has alternative return specifiers. 747 const mlir::Value 748 getAltReturnResult(const Fortran::semantics::Symbol &symbol) { 749 assert(Fortran::semantics::HasAlternateReturns(symbol) && 750 "subroutine does not have alternate returns"); 751 return getSymbolAddress(symbol); 752 } 753 754 void genFIRProcedureExit(Fortran::lower::pft::FunctionLikeUnit &funit, 755 const Fortran::semantics::Symbol &symbol) { 756 if (mlir::Block *finalBlock = funit.finalBlock) { 757 // The current block must end with a terminator. 758 if (blockIsUnterminated()) 759 builder->create<mlir::cf::BranchOp>(toLocation(), finalBlock); 760 // Set insertion point to final block. 761 builder->setInsertionPoint(finalBlock, finalBlock->end()); 762 } 763 if (Fortran::semantics::IsFunction(symbol)) { 764 genReturnSymbol(symbol); 765 } else if (Fortran::semantics::HasAlternateReturns(symbol)) { 766 mlir::Value retval = builder->create<fir::LoadOp>( 767 toLocation(), getAltReturnResult(symbol)); 768 builder->create<mlir::func::ReturnOp>(toLocation(), retval); 769 } else { 770 genExitRoutine(); 771 } 772 } 773 774 // 775 // Statements that have control-flow semantics 776 // 777 778 /// Generate an If[Then]Stmt condition or its negation. 779 template <typename A> 780 mlir::Value genIfCondition(const A *stmt, bool negate = false) { 781 mlir::Location loc = toLocation(); 782 Fortran::lower::StatementContext stmtCtx; 783 mlir::Value condExpr = createFIRExpr( 784 loc, 785 Fortran::semantics::GetExpr( 786 std::get<Fortran::parser::ScalarLogicalExpr>(stmt->t)), 787 stmtCtx); 788 stmtCtx.finalize(); 789 mlir::Value cond = 790 builder->createConvert(loc, builder->getI1Type(), condExpr); 791 if (negate) 792 cond = builder->create<mlir::arith::XOrIOp>( 793 loc, cond, builder->createIntegerConstant(loc, cond.getType(), 1)); 794 return cond; 795 } 796 797 mlir::func::FuncOp getFunc(llvm::StringRef name, mlir::FunctionType ty) { 798 if (mlir::func::FuncOp func = builder->getNamedFunction(name)) { 799 assert(func.getFunctionType() == ty); 800 return func; 801 } 802 return builder->createFunction(toLocation(), name, ty); 803 } 804 805 /// Lowering of CALL statement 806 void genFIR(const Fortran::parser::CallStmt &stmt) { 807 Fortran::lower::StatementContext stmtCtx; 808 Fortran::lower::pft::Evaluation &eval = getEval(); 809 setCurrentPosition(stmt.v.source); 810 assert(stmt.typedCall && "Call was not analyzed"); 811 // Call statement lowering shares code with function call lowering. 812 mlir::Value res = Fortran::lower::createSubroutineCall( 813 *this, *stmt.typedCall, explicitIterSpace, implicitIterSpace, 814 localSymbols, stmtCtx, /*isUserDefAssignment=*/false); 815 if (!res) 816 return; // "Normal" subroutine call. 817 // Call with alternate return specifiers. 818 // The call returns an index that selects an alternate return branch target. 819 llvm::SmallVector<int64_t> indexList; 820 llvm::SmallVector<mlir::Block *> blockList; 821 int64_t index = 0; 822 for (const Fortran::parser::ActualArgSpec &arg : 823 std::get<std::list<Fortran::parser::ActualArgSpec>>(stmt.v.t)) { 824 const auto &actual = std::get<Fortran::parser::ActualArg>(arg.t); 825 if (const auto *altReturn = 826 std::get_if<Fortran::parser::AltReturnSpec>(&actual.u)) { 827 indexList.push_back(++index); 828 blockList.push_back(blockOfLabel(eval, altReturn->v)); 829 } 830 } 831 blockList.push_back(eval.nonNopSuccessor().block); // default = fallthrough 832 stmtCtx.finalize(); 833 builder->create<fir::SelectOp>(toLocation(), res, indexList, blockList); 834 } 835 836 void genFIR(const Fortran::parser::ComputedGotoStmt &stmt) { 837 Fortran::lower::StatementContext stmtCtx; 838 Fortran::lower::pft::Evaluation &eval = getEval(); 839 mlir::Value selectExpr = 840 createFIRExpr(toLocation(), 841 Fortran::semantics::GetExpr( 842 std::get<Fortran::parser::ScalarIntExpr>(stmt.t)), 843 stmtCtx); 844 stmtCtx.finalize(); 845 llvm::SmallVector<int64_t> indexList; 846 llvm::SmallVector<mlir::Block *> blockList; 847 int64_t index = 0; 848 for (Fortran::parser::Label label : 849 std::get<std::list<Fortran::parser::Label>>(stmt.t)) { 850 indexList.push_back(++index); 851 blockList.push_back(blockOfLabel(eval, label)); 852 } 853 blockList.push_back(eval.nonNopSuccessor().block); // default 854 builder->create<fir::SelectOp>(toLocation(), selectExpr, indexList, 855 blockList); 856 } 857 858 void genFIR(const Fortran::parser::ArithmeticIfStmt &stmt) { 859 Fortran::lower::StatementContext stmtCtx; 860 Fortran::lower::pft::Evaluation &eval = getEval(); 861 mlir::Value expr = createFIRExpr( 862 toLocation(), 863 Fortran::semantics::GetExpr(std::get<Fortran::parser::Expr>(stmt.t)), 864 stmtCtx); 865 stmtCtx.finalize(); 866 mlir::Type exprType = expr.getType(); 867 mlir::Location loc = toLocation(); 868 if (exprType.isSignlessInteger()) { 869 // Arithmetic expression has Integer type. Generate a SelectCaseOp 870 // with ranges {(-inf:-1], 0=default, [1:inf)}. 871 mlir::MLIRContext *context = builder->getContext(); 872 llvm::SmallVector<mlir::Attribute> attrList; 873 llvm::SmallVector<mlir::Value> valueList; 874 llvm::SmallVector<mlir::Block *> blockList; 875 attrList.push_back(fir::UpperBoundAttr::get(context)); 876 valueList.push_back(builder->createIntegerConstant(loc, exprType, -1)); 877 blockList.push_back(blockOfLabel(eval, std::get<1>(stmt.t))); 878 attrList.push_back(fir::LowerBoundAttr::get(context)); 879 valueList.push_back(builder->createIntegerConstant(loc, exprType, 1)); 880 blockList.push_back(blockOfLabel(eval, std::get<3>(stmt.t))); 881 attrList.push_back(mlir::UnitAttr::get(context)); // 0 is the "default" 882 blockList.push_back(blockOfLabel(eval, std::get<2>(stmt.t))); 883 builder->create<fir::SelectCaseOp>(loc, expr, attrList, valueList, 884 blockList); 885 return; 886 } 887 // Arithmetic expression has Real type. Generate 888 // sum = expr + expr [ raise an exception if expr is a NaN ] 889 // if (sum < 0.0) goto L1 else if (sum > 0.0) goto L3 else goto L2 890 auto sum = builder->create<mlir::arith::AddFOp>(loc, expr, expr); 891 auto zero = builder->create<mlir::arith::ConstantOp>( 892 loc, exprType, builder->getFloatAttr(exprType, 0.0)); 893 auto cond1 = builder->create<mlir::arith::CmpFOp>( 894 loc, mlir::arith::CmpFPredicate::OLT, sum, zero); 895 mlir::Block *elseIfBlock = 896 builder->getBlock()->splitBlock(builder->getInsertionPoint()); 897 genFIRConditionalBranch(cond1, blockOfLabel(eval, std::get<1>(stmt.t)), 898 elseIfBlock); 899 startBlock(elseIfBlock); 900 auto cond2 = builder->create<mlir::arith::CmpFOp>( 901 loc, mlir::arith::CmpFPredicate::OGT, sum, zero); 902 genFIRConditionalBranch(cond2, blockOfLabel(eval, std::get<3>(stmt.t)), 903 blockOfLabel(eval, std::get<2>(stmt.t))); 904 } 905 906 void genFIR(const Fortran::parser::AssignedGotoStmt &stmt) { 907 // Program requirement 1990 8.2.4 - 908 // 909 // At the time of execution of an assigned GOTO statement, the integer 910 // variable must be defined with the value of a statement label of a 911 // branch target statement that appears in the same scoping unit. 912 // Note that the variable may be defined with a statement label value 913 // only by an ASSIGN statement in the same scoping unit as the assigned 914 // GOTO statement. 915 916 mlir::Location loc = toLocation(); 917 Fortran::lower::pft::Evaluation &eval = getEval(); 918 const Fortran::lower::pft::SymbolLabelMap &symbolLabelMap = 919 eval.getOwningProcedure()->assignSymbolLabelMap; 920 const Fortran::semantics::Symbol &symbol = 921 *std::get<Fortran::parser::Name>(stmt.t).symbol; 922 auto selectExpr = 923 builder->create<fir::LoadOp>(loc, getSymbolAddress(symbol)); 924 auto iter = symbolLabelMap.find(symbol); 925 if (iter == symbolLabelMap.end()) { 926 // Fail for a nonconforming program unit that does not have any ASSIGN 927 // statements. The front end should check for this. 928 mlir::emitError(loc, "(semantics issue) no assigned goto targets"); 929 exit(1); 930 } 931 auto labelSet = iter->second; 932 llvm::SmallVector<int64_t> indexList; 933 llvm::SmallVector<mlir::Block *> blockList; 934 auto addLabel = [&](Fortran::parser::Label label) { 935 indexList.push_back(label); 936 blockList.push_back(blockOfLabel(eval, label)); 937 }; 938 // Add labels from an explicit list. The list may have duplicates. 939 for (Fortran::parser::Label label : 940 std::get<std::list<Fortran::parser::Label>>(stmt.t)) { 941 if (labelSet.count(label) && 942 std::find(indexList.begin(), indexList.end(), label) == 943 indexList.end()) { // ignore duplicates 944 addLabel(label); 945 } 946 } 947 // Absent an explicit list, add all possible label targets. 948 if (indexList.empty()) 949 for (auto &label : labelSet) 950 addLabel(label); 951 // Add a nop/fallthrough branch to the switch for a nonconforming program 952 // unit that violates the program requirement above. 953 blockList.push_back(eval.nonNopSuccessor().block); // default 954 builder->create<fir::SelectOp>(loc, selectExpr, indexList, blockList); 955 } 956 957 /// Generate FIR for a DO construct. There are six variants: 958 /// - unstructured infinite and while loops 959 /// - structured and unstructured increment loops 960 /// - structured and unstructured concurrent loops 961 void genFIR(const Fortran::parser::DoConstruct &doConstruct) { 962 setCurrentPositionAt(doConstruct); 963 // Collect loop nest information. 964 // Generate begin loop code directly for infinite and while loops. 965 Fortran::lower::pft::Evaluation &eval = getEval(); 966 bool unstructuredContext = eval.lowerAsUnstructured(); 967 Fortran::lower::pft::Evaluation &doStmtEval = 968 eval.getFirstNestedEvaluation(); 969 auto *doStmt = doStmtEval.getIf<Fortran::parser::NonLabelDoStmt>(); 970 const auto &loopControl = 971 std::get<std::optional<Fortran::parser::LoopControl>>(doStmt->t); 972 mlir::Block *preheaderBlock = doStmtEval.block; 973 mlir::Block *beginBlock = 974 preheaderBlock ? preheaderBlock : builder->getBlock(); 975 auto createNextBeginBlock = [&]() { 976 // Step beginBlock through unstructured preheader, header, and mask 977 // blocks, created in outermost to innermost order. 978 return beginBlock = beginBlock->splitBlock(beginBlock->end()); 979 }; 980 mlir::Block *headerBlock = 981 unstructuredContext ? createNextBeginBlock() : nullptr; 982 mlir::Block *bodyBlock = doStmtEval.lexicalSuccessor->block; 983 mlir::Block *exitBlock = doStmtEval.parentConstruct->constructExit->block; 984 IncrementLoopNestInfo incrementLoopNestInfo; 985 const Fortran::parser::ScalarLogicalExpr *whileCondition = nullptr; 986 bool infiniteLoop = !loopControl.has_value(); 987 if (infiniteLoop) { 988 assert(unstructuredContext && "infinite loop must be unstructured"); 989 startBlock(headerBlock); 990 } else if ((whileCondition = 991 std::get_if<Fortran::parser::ScalarLogicalExpr>( 992 &loopControl->u))) { 993 assert(unstructuredContext && "while loop must be unstructured"); 994 maybeStartBlock(preheaderBlock); // no block or empty block 995 startBlock(headerBlock); 996 genFIRConditionalBranch(*whileCondition, bodyBlock, exitBlock); 997 } else if (const auto *bounds = 998 std::get_if<Fortran::parser::LoopControl::Bounds>( 999 &loopControl->u)) { 1000 // Non-concurrent increment loop. 1001 IncrementLoopInfo &info = incrementLoopNestInfo.emplace_back( 1002 *bounds->name.thing.symbol, bounds->lower, bounds->upper, 1003 bounds->step); 1004 if (unstructuredContext) { 1005 maybeStartBlock(preheaderBlock); 1006 info.hasRealControl = info.loopVariableSym.GetType()->IsNumeric( 1007 Fortran::common::TypeCategory::Real); 1008 info.headerBlock = headerBlock; 1009 info.bodyBlock = bodyBlock; 1010 info.exitBlock = exitBlock; 1011 } 1012 } else { 1013 TODO(toLocation(), "infinite/unstructured loop/concurrent loop"); 1014 } 1015 1016 // Increment loop begin code. (Infinite/while code was already generated.) 1017 if (!infiniteLoop && !whileCondition) 1018 genFIRIncrementLoopBegin(incrementLoopNestInfo); 1019 1020 // Loop body code - NonLabelDoStmt and EndDoStmt code is generated here. 1021 // Their genFIR calls are nops except for block management in some cases. 1022 for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) 1023 genFIR(e, unstructuredContext); 1024 1025 // Loop end code. 1026 if (infiniteLoop || whileCondition) 1027 genFIRBranch(headerBlock); 1028 else 1029 genFIRIncrementLoopEnd(incrementLoopNestInfo); 1030 } 1031 1032 /// Generate FIR to begin a structured or unstructured increment loop nest. 1033 void genFIRIncrementLoopBegin(IncrementLoopNestInfo &incrementLoopNestInfo) { 1034 assert(!incrementLoopNestInfo.empty() && "empty loop nest"); 1035 mlir::Location loc = toLocation(); 1036 auto genControlValue = [&](const Fortran::lower::SomeExpr *expr, 1037 const IncrementLoopInfo &info) { 1038 mlir::Type controlType = info.isStructured() ? builder->getIndexType() 1039 : info.getLoopVariableType(); 1040 Fortran::lower::StatementContext stmtCtx; 1041 if (expr) 1042 return builder->createConvert(loc, controlType, 1043 createFIRExpr(loc, expr, stmtCtx)); 1044 1045 if (info.hasRealControl) 1046 return builder->createRealConstant(loc, controlType, 1u); 1047 return builder->createIntegerConstant(loc, controlType, 1); // step 1048 }; 1049 for (IncrementLoopInfo &info : incrementLoopNestInfo) { 1050 info.loopVariable = genLoopVariableAddress(loc, info.loopVariableSym); 1051 mlir::Value lowerValue = genControlValue(info.lowerExpr, info); 1052 mlir::Value upperValue = genControlValue(info.upperExpr, info); 1053 info.stepValue = genControlValue(info.stepExpr, info); 1054 1055 // Structured loop - generate fir.do_loop. 1056 if (info.isStructured()) { 1057 info.doLoop = builder->create<fir::DoLoopOp>( 1058 loc, lowerValue, upperValue, info.stepValue, info.isUnordered, 1059 /*finalCountValue=*/!info.isUnordered); 1060 builder->setInsertionPointToStart(info.doLoop.getBody()); 1061 // Update the loop variable value, as it may have non-index references. 1062 mlir::Value value = builder->createConvert( 1063 loc, info.getLoopVariableType(), info.doLoop.getInductionVar()); 1064 builder->create<fir::StoreOp>(loc, value, info.loopVariable); 1065 // TODO: Mask expr 1066 // TODO: handle Locality Spec 1067 continue; 1068 } 1069 1070 // Unstructured loop preheader - initialize tripVariable and loopVariable. 1071 mlir::Value tripCount; 1072 if (info.hasRealControl) { 1073 auto diff1 = 1074 builder->create<mlir::arith::SubFOp>(loc, upperValue, lowerValue); 1075 auto diff2 = 1076 builder->create<mlir::arith::AddFOp>(loc, diff1, info.stepValue); 1077 tripCount = 1078 builder->create<mlir::arith::DivFOp>(loc, diff2, info.stepValue); 1079 tripCount = 1080 builder->createConvert(loc, builder->getIndexType(), tripCount); 1081 1082 } else { 1083 auto diff1 = 1084 builder->create<mlir::arith::SubIOp>(loc, upperValue, lowerValue); 1085 auto diff2 = 1086 builder->create<mlir::arith::AddIOp>(loc, diff1, info.stepValue); 1087 tripCount = 1088 builder->create<mlir::arith::DivSIOp>(loc, diff2, info.stepValue); 1089 } 1090 info.tripVariable = builder->createTemporary(loc, tripCount.getType()); 1091 builder->create<fir::StoreOp>(loc, tripCount, info.tripVariable); 1092 builder->create<fir::StoreOp>(loc, lowerValue, info.loopVariable); 1093 1094 // Unstructured loop header - generate loop condition and mask. 1095 startBlock(info.headerBlock); 1096 tripCount = builder->create<fir::LoadOp>(loc, info.tripVariable); 1097 mlir::Value zero = 1098 builder->createIntegerConstant(loc, tripCount.getType(), 0); 1099 auto cond = builder->create<mlir::arith::CmpIOp>( 1100 loc, mlir::arith::CmpIPredicate::sgt, tripCount, zero); 1101 // TODO: mask expression 1102 genFIRConditionalBranch(cond, info.bodyBlock, info.exitBlock); 1103 if (&info != &incrementLoopNestInfo.back()) // not innermost 1104 startBlock(info.bodyBlock); // preheader block of enclosed dimension 1105 } 1106 } 1107 1108 /// Generate FIR to end a structured or unstructured increment loop nest. 1109 void genFIRIncrementLoopEnd(IncrementLoopNestInfo &incrementLoopNestInfo) { 1110 assert(!incrementLoopNestInfo.empty() && "empty loop nest"); 1111 mlir::Location loc = toLocation(); 1112 for (auto it = incrementLoopNestInfo.rbegin(), 1113 rend = incrementLoopNestInfo.rend(); 1114 it != rend; ++it) { 1115 IncrementLoopInfo &info = *it; 1116 if (info.isStructured()) { 1117 // End fir.do_loop. 1118 if (!info.isUnordered) { 1119 builder->setInsertionPointToEnd(info.doLoop.getBody()); 1120 mlir::Value result = builder->create<mlir::arith::AddIOp>( 1121 loc, info.doLoop.getInductionVar(), info.doLoop.getStep()); 1122 builder->create<fir::ResultOp>(loc, result); 1123 } 1124 builder->setInsertionPointAfter(info.doLoop); 1125 if (info.isUnordered) 1126 continue; 1127 // The loop control variable may be used after loop execution. 1128 mlir::Value lcv = builder->createConvert( 1129 loc, info.getLoopVariableType(), info.doLoop.getResult(0)); 1130 builder->create<fir::StoreOp>(loc, lcv, info.loopVariable); 1131 continue; 1132 } 1133 1134 // Unstructured loop - decrement tripVariable and step loopVariable. 1135 mlir::Value tripCount = 1136 builder->create<fir::LoadOp>(loc, info.tripVariable); 1137 mlir::Value one = 1138 builder->createIntegerConstant(loc, tripCount.getType(), 1); 1139 tripCount = builder->create<mlir::arith::SubIOp>(loc, tripCount, one); 1140 builder->create<fir::StoreOp>(loc, tripCount, info.tripVariable); 1141 mlir::Value value = builder->create<fir::LoadOp>(loc, info.loopVariable); 1142 if (info.hasRealControl) 1143 value = 1144 builder->create<mlir::arith::AddFOp>(loc, value, info.stepValue); 1145 else 1146 value = 1147 builder->create<mlir::arith::AddIOp>(loc, value, info.stepValue); 1148 builder->create<fir::StoreOp>(loc, value, info.loopVariable); 1149 1150 genFIRBranch(info.headerBlock); 1151 if (&info != &incrementLoopNestInfo.front()) // not outermost 1152 startBlock(info.exitBlock); // latch block of enclosing dimension 1153 } 1154 } 1155 1156 /// Generate structured or unstructured FIR for an IF construct. 1157 /// The initial statement may be either an IfStmt or an IfThenStmt. 1158 void genFIR(const Fortran::parser::IfConstruct &) { 1159 mlir::Location loc = toLocation(); 1160 Fortran::lower::pft::Evaluation &eval = getEval(); 1161 if (eval.lowerAsStructured()) { 1162 // Structured fir.if nest. 1163 fir::IfOp topIfOp, currentIfOp; 1164 for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) { 1165 auto genIfOp = [&](mlir::Value cond) { 1166 auto ifOp = builder->create<fir::IfOp>(loc, cond, /*withElse=*/true); 1167 builder->setInsertionPointToStart(&ifOp.getThenRegion().front()); 1168 return ifOp; 1169 }; 1170 if (auto *s = e.getIf<Fortran::parser::IfThenStmt>()) { 1171 topIfOp = currentIfOp = genIfOp(genIfCondition(s, e.negateCondition)); 1172 } else if (auto *s = e.getIf<Fortran::parser::IfStmt>()) { 1173 topIfOp = currentIfOp = genIfOp(genIfCondition(s, e.negateCondition)); 1174 } else if (auto *s = e.getIf<Fortran::parser::ElseIfStmt>()) { 1175 builder->setInsertionPointToStart( 1176 ¤tIfOp.getElseRegion().front()); 1177 currentIfOp = genIfOp(genIfCondition(s)); 1178 } else if (e.isA<Fortran::parser::ElseStmt>()) { 1179 builder->setInsertionPointToStart( 1180 ¤tIfOp.getElseRegion().front()); 1181 } else if (e.isA<Fortran::parser::EndIfStmt>()) { 1182 builder->setInsertionPointAfter(topIfOp); 1183 } else { 1184 genFIR(e, /*unstructuredContext=*/false); 1185 } 1186 } 1187 return; 1188 } 1189 1190 // Unstructured branch sequence. 1191 for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) { 1192 auto genIfBranch = [&](mlir::Value cond) { 1193 if (e.lexicalSuccessor == e.controlSuccessor) // empty block -> exit 1194 genFIRConditionalBranch(cond, e.parentConstruct->constructExit, 1195 e.controlSuccessor); 1196 else // non-empty block 1197 genFIRConditionalBranch(cond, e.lexicalSuccessor, e.controlSuccessor); 1198 }; 1199 if (auto *s = e.getIf<Fortran::parser::IfThenStmt>()) { 1200 maybeStartBlock(e.block); 1201 genIfBranch(genIfCondition(s, e.negateCondition)); 1202 } else if (auto *s = e.getIf<Fortran::parser::IfStmt>()) { 1203 maybeStartBlock(e.block); 1204 genIfBranch(genIfCondition(s, e.negateCondition)); 1205 } else if (auto *s = e.getIf<Fortran::parser::ElseIfStmt>()) { 1206 startBlock(e.block); 1207 genIfBranch(genIfCondition(s)); 1208 } else { 1209 genFIR(e); 1210 } 1211 } 1212 } 1213 1214 void genFIR(const Fortran::parser::CaseConstruct &) { 1215 for (Fortran::lower::pft::Evaluation &e : getEval().getNestedEvaluations()) 1216 genFIR(e); 1217 } 1218 1219 template <typename A> 1220 void genNestedStatement(const Fortran::parser::Statement<A> &stmt) { 1221 setCurrentPosition(stmt.source); 1222 genFIR(stmt.statement); 1223 } 1224 1225 /// Force the binding of an explicit symbol. This is used to bind and re-bind 1226 /// a concurrent control symbol to its value. 1227 void forceControlVariableBinding(const Fortran::semantics::Symbol *sym, 1228 mlir::Value inducVar) { 1229 mlir::Location loc = toLocation(); 1230 assert(sym && "There must be a symbol to bind"); 1231 mlir::Type toTy = genType(*sym); 1232 // FIXME: this should be a "per iteration" temporary. 1233 mlir::Value tmp = builder->createTemporary( 1234 loc, toTy, toStringRef(sym->name()), 1235 llvm::ArrayRef<mlir::NamedAttribute>{ 1236 Fortran::lower::getAdaptToByRefAttr(*builder)}); 1237 mlir::Value cast = builder->createConvert(loc, toTy, inducVar); 1238 builder->create<fir::StoreOp>(loc, cast, tmp); 1239 localSymbols.addSymbol(*sym, tmp, /*force=*/true); 1240 } 1241 1242 /// Process a concurrent header for a FORALL. (Concurrent headers for DO 1243 /// CONCURRENT loops are lowered elsewhere.) 1244 void genFIR(const Fortran::parser::ConcurrentHeader &header) { 1245 llvm::SmallVector<mlir::Value> lows; 1246 llvm::SmallVector<mlir::Value> highs; 1247 llvm::SmallVector<mlir::Value> steps; 1248 if (explicitIterSpace.isOutermostForall()) { 1249 // For the outermost forall, we evaluate the bounds expressions once. 1250 // Contrastingly, if this forall is nested, the bounds expressions are 1251 // assumed to be pure, possibly dependent on outer concurrent control 1252 // variables, possibly variant with respect to arguments, and will be 1253 // re-evaluated. 1254 mlir::Location loc = toLocation(); 1255 mlir::Type idxTy = builder->getIndexType(); 1256 Fortran::lower::StatementContext &stmtCtx = 1257 explicitIterSpace.stmtContext(); 1258 auto lowerExpr = [&](auto &e) { 1259 return fir::getBase(genExprValue(e, stmtCtx)); 1260 }; 1261 for (const Fortran::parser::ConcurrentControl &ctrl : 1262 std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t)) { 1263 const Fortran::lower::SomeExpr *lo = 1264 Fortran::semantics::GetExpr(std::get<1>(ctrl.t)); 1265 const Fortran::lower::SomeExpr *hi = 1266 Fortran::semantics::GetExpr(std::get<2>(ctrl.t)); 1267 auto &optStep = 1268 std::get<std::optional<Fortran::parser::ScalarIntExpr>>(ctrl.t); 1269 lows.push_back(builder->createConvert(loc, idxTy, lowerExpr(*lo))); 1270 highs.push_back(builder->createConvert(loc, idxTy, lowerExpr(*hi))); 1271 steps.push_back( 1272 optStep.has_value() 1273 ? builder->createConvert( 1274 loc, idxTy, 1275 lowerExpr(*Fortran::semantics::GetExpr(*optStep))) 1276 : builder->createIntegerConstant(loc, idxTy, 1)); 1277 } 1278 } 1279 auto lambda = [&, lows, highs, steps]() { 1280 // Create our iteration space from the header spec. 1281 mlir::Location loc = toLocation(); 1282 mlir::Type idxTy = builder->getIndexType(); 1283 llvm::SmallVector<fir::DoLoopOp> loops; 1284 Fortran::lower::StatementContext &stmtCtx = 1285 explicitIterSpace.stmtContext(); 1286 auto lowerExpr = [&](auto &e) { 1287 return fir::getBase(genExprValue(e, stmtCtx)); 1288 }; 1289 const bool outermost = !lows.empty(); 1290 std::size_t headerIndex = 0; 1291 for (const Fortran::parser::ConcurrentControl &ctrl : 1292 std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t)) { 1293 const Fortran::semantics::Symbol *ctrlVar = 1294 std::get<Fortran::parser::Name>(ctrl.t).symbol; 1295 mlir::Value lb; 1296 mlir::Value ub; 1297 mlir::Value by; 1298 if (outermost) { 1299 assert(headerIndex < lows.size()); 1300 if (headerIndex == 0) 1301 explicitIterSpace.resetInnerArgs(); 1302 lb = lows[headerIndex]; 1303 ub = highs[headerIndex]; 1304 by = steps[headerIndex++]; 1305 } else { 1306 const Fortran::lower::SomeExpr *lo = 1307 Fortran::semantics::GetExpr(std::get<1>(ctrl.t)); 1308 const Fortran::lower::SomeExpr *hi = 1309 Fortran::semantics::GetExpr(std::get<2>(ctrl.t)); 1310 auto &optStep = 1311 std::get<std::optional<Fortran::parser::ScalarIntExpr>>(ctrl.t); 1312 lb = builder->createConvert(loc, idxTy, lowerExpr(*lo)); 1313 ub = builder->createConvert(loc, idxTy, lowerExpr(*hi)); 1314 by = optStep.has_value() 1315 ? builder->createConvert( 1316 loc, idxTy, 1317 lowerExpr(*Fortran::semantics::GetExpr(*optStep))) 1318 : builder->createIntegerConstant(loc, idxTy, 1); 1319 } 1320 auto lp = builder->create<fir::DoLoopOp>( 1321 loc, lb, ub, by, /*unordered=*/true, 1322 /*finalCount=*/false, explicitIterSpace.getInnerArgs()); 1323 if (!loops.empty() || !outermost) 1324 builder->create<fir::ResultOp>(loc, lp.getResults()); 1325 explicitIterSpace.setInnerArgs(lp.getRegionIterArgs()); 1326 builder->setInsertionPointToStart(lp.getBody()); 1327 forceControlVariableBinding(ctrlVar, lp.getInductionVar()); 1328 loops.push_back(lp); 1329 } 1330 if (outermost) 1331 explicitIterSpace.setOuterLoop(loops[0]); 1332 explicitIterSpace.appendLoops(loops); 1333 if (const auto &mask = 1334 std::get<std::optional<Fortran::parser::ScalarLogicalExpr>>( 1335 header.t); 1336 mask.has_value()) { 1337 mlir::Type i1Ty = builder->getI1Type(); 1338 fir::ExtendedValue maskExv = 1339 genExprValue(*Fortran::semantics::GetExpr(mask.value()), stmtCtx); 1340 mlir::Value cond = 1341 builder->createConvert(loc, i1Ty, fir::getBase(maskExv)); 1342 auto ifOp = builder->create<fir::IfOp>( 1343 loc, explicitIterSpace.innerArgTypes(), cond, 1344 /*withElseRegion=*/true); 1345 builder->create<fir::ResultOp>(loc, ifOp.getResults()); 1346 builder->setInsertionPointToStart(&ifOp.getElseRegion().front()); 1347 builder->create<fir::ResultOp>(loc, explicitIterSpace.getInnerArgs()); 1348 builder->setInsertionPointToStart(&ifOp.getThenRegion().front()); 1349 } 1350 }; 1351 // Push the lambda to gen the loop nest context. 1352 explicitIterSpace.pushLoopNest(lambda); 1353 } 1354 1355 void genFIR(const Fortran::parser::ForallAssignmentStmt &stmt) { 1356 std::visit([&](const auto &x) { genFIR(x); }, stmt.u); 1357 } 1358 1359 void genFIR(const Fortran::parser::EndForallStmt &) { 1360 cleanupExplicitSpace(); 1361 } 1362 1363 template <typename A> 1364 void prepareExplicitSpace(const A &forall) { 1365 if (!explicitIterSpace.isActive()) 1366 analyzeExplicitSpace(forall); 1367 localSymbols.pushScope(); 1368 explicitIterSpace.enter(); 1369 } 1370 1371 /// Cleanup all the FORALL context information when we exit. 1372 void cleanupExplicitSpace() { 1373 explicitIterSpace.leave(); 1374 localSymbols.popScope(); 1375 } 1376 1377 /// Generate FIR for a FORALL statement. 1378 void genFIR(const Fortran::parser::ForallStmt &stmt) { 1379 prepareExplicitSpace(stmt); 1380 genFIR(std::get< 1381 Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>( 1382 stmt.t) 1383 .value()); 1384 genFIR(std::get<Fortran::parser::UnlabeledStatement< 1385 Fortran::parser::ForallAssignmentStmt>>(stmt.t) 1386 .statement); 1387 cleanupExplicitSpace(); 1388 } 1389 1390 /// Generate FIR for a FORALL construct. 1391 void genFIR(const Fortran::parser::ForallConstruct &forall) { 1392 prepareExplicitSpace(forall); 1393 genNestedStatement( 1394 std::get< 1395 Fortran::parser::Statement<Fortran::parser::ForallConstructStmt>>( 1396 forall.t)); 1397 for (const Fortran::parser::ForallBodyConstruct &s : 1398 std::get<std::list<Fortran::parser::ForallBodyConstruct>>(forall.t)) { 1399 std::visit( 1400 Fortran::common::visitors{ 1401 [&](const Fortran::parser::WhereConstruct &b) { genFIR(b); }, 1402 [&](const Fortran::common::Indirection< 1403 Fortran::parser::ForallConstruct> &b) { genFIR(b.value()); }, 1404 [&](const auto &b) { genNestedStatement(b); }}, 1405 s.u); 1406 } 1407 genNestedStatement( 1408 std::get<Fortran::parser::Statement<Fortran::parser::EndForallStmt>>( 1409 forall.t)); 1410 } 1411 1412 /// Lower the concurrent header specification. 1413 void genFIR(const Fortran::parser::ForallConstructStmt &stmt) { 1414 genFIR(std::get< 1415 Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>( 1416 stmt.t) 1417 .value()); 1418 } 1419 1420 void genFIR(const Fortran::parser::CompilerDirective &) { 1421 TODO(toLocation(), "CompilerDirective lowering"); 1422 } 1423 1424 void genFIR(const Fortran::parser::OpenACCConstruct &acc) { 1425 mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint(); 1426 genOpenACCConstruct(*this, getEval(), acc); 1427 for (Fortran::lower::pft::Evaluation &e : getEval().getNestedEvaluations()) 1428 genFIR(e); 1429 builder->restoreInsertionPoint(insertPt); 1430 } 1431 1432 void genFIR(const Fortran::parser::OpenACCDeclarativeConstruct &accDecl) { 1433 mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint(); 1434 genOpenACCDeclarativeConstruct(*this, getEval(), accDecl); 1435 for (Fortran::lower::pft::Evaluation &e : getEval().getNestedEvaluations()) 1436 genFIR(e); 1437 builder->restoreInsertionPoint(insertPt); 1438 } 1439 1440 void genFIR(const Fortran::parser::OpenMPConstruct &omp) { 1441 mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint(); 1442 localSymbols.pushScope(); 1443 genOpenMPConstruct(*this, getEval(), omp); 1444 1445 const Fortran::parser::OpenMPLoopConstruct *ompLoop = 1446 std::get_if<Fortran::parser::OpenMPLoopConstruct>(&omp.u); 1447 1448 // If loop is part of an OpenMP Construct then the OpenMP dialect 1449 // workshare loop operation has already been created. Only the 1450 // body needs to be created here and the do_loop can be skipped. 1451 // Skip the number of collapsed loops, which is 1 when there is a 1452 // no collapse requested. 1453 1454 Fortran::lower::pft::Evaluation *curEval = &getEval(); 1455 if (ompLoop) { 1456 const auto &wsLoopOpClauseList = std::get<Fortran::parser::OmpClauseList>( 1457 std::get<Fortran::parser::OmpBeginLoopDirective>(ompLoop->t).t); 1458 int64_t collapseValue = 1459 Fortran::lower::getCollapseValue(wsLoopOpClauseList); 1460 1461 curEval = &curEval->getFirstNestedEvaluation(); 1462 for (int64_t i = 1; i < collapseValue; i++) { 1463 curEval = &*std::next(curEval->getNestedEvaluations().begin()); 1464 } 1465 } 1466 1467 for (Fortran::lower::pft::Evaluation &e : curEval->getNestedEvaluations()) 1468 genFIR(e); 1469 localSymbols.popScope(); 1470 builder->restoreInsertionPoint(insertPt); 1471 } 1472 1473 void genFIR(const Fortran::parser::OpenMPDeclarativeConstruct &ompDecl) { 1474 mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint(); 1475 genOpenMPDeclarativeConstruct(*this, getEval(), ompDecl); 1476 for (Fortran::lower::pft::Evaluation &e : getEval().getNestedEvaluations()) 1477 genFIR(e); 1478 builder->restoreInsertionPoint(insertPt); 1479 } 1480 1481 /// Generate FIR for a SELECT CASE statement. 1482 /// The type may be CHARACTER, INTEGER, or LOGICAL. 1483 void genFIR(const Fortran::parser::SelectCaseStmt &stmt) { 1484 Fortran::lower::pft::Evaluation &eval = getEval(); 1485 mlir::MLIRContext *context = builder->getContext(); 1486 mlir::Location loc = toLocation(); 1487 Fortran::lower::StatementContext stmtCtx; 1488 const Fortran::lower::SomeExpr *expr = Fortran::semantics::GetExpr( 1489 std::get<Fortran::parser::Scalar<Fortran::parser::Expr>>(stmt.t)); 1490 bool isCharSelector = isCharacterCategory(expr->GetType()->category()); 1491 bool isLogicalSelector = isLogicalCategory(expr->GetType()->category()); 1492 auto charValue = [&](const Fortran::lower::SomeExpr *expr) { 1493 fir::ExtendedValue exv = genExprAddr(*expr, stmtCtx, &loc); 1494 return exv.match( 1495 [&](const fir::CharBoxValue &cbv) { 1496 return fir::factory::CharacterExprHelper{*builder, loc} 1497 .createEmboxChar(cbv.getAddr(), cbv.getLen()); 1498 }, 1499 [&](auto) { 1500 fir::emitFatalError(loc, "not a character"); 1501 return mlir::Value{}; 1502 }); 1503 }; 1504 mlir::Value selector; 1505 if (isCharSelector) { 1506 selector = charValue(expr); 1507 } else { 1508 selector = createFIRExpr(loc, expr, stmtCtx); 1509 if (isLogicalSelector) 1510 selector = builder->createConvert(loc, builder->getI1Type(), selector); 1511 } 1512 mlir::Type selectType = selector.getType(); 1513 llvm::SmallVector<mlir::Attribute> attrList; 1514 llvm::SmallVector<mlir::Value> valueList; 1515 llvm::SmallVector<mlir::Block *> blockList; 1516 mlir::Block *defaultBlock = eval.parentConstruct->constructExit->block; 1517 using CaseValue = Fortran::parser::Scalar<Fortran::parser::ConstantExpr>; 1518 auto addValue = [&](const CaseValue &caseValue) { 1519 const Fortran::lower::SomeExpr *expr = 1520 Fortran::semantics::GetExpr(caseValue.thing); 1521 if (isCharSelector) 1522 valueList.push_back(charValue(expr)); 1523 else if (isLogicalSelector) 1524 valueList.push_back(builder->createConvert( 1525 loc, selectType, createFIRExpr(toLocation(), expr, stmtCtx))); 1526 else 1527 valueList.push_back(builder->createIntegerConstant( 1528 loc, selectType, *Fortran::evaluate::ToInt64(*expr))); 1529 }; 1530 for (Fortran::lower::pft::Evaluation *e = eval.controlSuccessor; e; 1531 e = e->controlSuccessor) { 1532 const auto &caseStmt = e->getIf<Fortran::parser::CaseStmt>(); 1533 assert(e->block && "missing CaseStmt block"); 1534 const auto &caseSelector = 1535 std::get<Fortran::parser::CaseSelector>(caseStmt->t); 1536 const auto *caseValueRangeList = 1537 std::get_if<std::list<Fortran::parser::CaseValueRange>>( 1538 &caseSelector.u); 1539 if (!caseValueRangeList) { 1540 defaultBlock = e->block; 1541 continue; 1542 } 1543 for (const Fortran::parser::CaseValueRange &caseValueRange : 1544 *caseValueRangeList) { 1545 blockList.push_back(e->block); 1546 if (const auto *caseValue = std::get_if<CaseValue>(&caseValueRange.u)) { 1547 attrList.push_back(fir::PointIntervalAttr::get(context)); 1548 addValue(*caseValue); 1549 continue; 1550 } 1551 const auto &caseRange = 1552 std::get<Fortran::parser::CaseValueRange::Range>(caseValueRange.u); 1553 if (caseRange.lower && caseRange.upper) { 1554 attrList.push_back(fir::ClosedIntervalAttr::get(context)); 1555 addValue(*caseRange.lower); 1556 addValue(*caseRange.upper); 1557 } else if (caseRange.lower) { 1558 attrList.push_back(fir::LowerBoundAttr::get(context)); 1559 addValue(*caseRange.lower); 1560 } else { 1561 attrList.push_back(fir::UpperBoundAttr::get(context)); 1562 addValue(*caseRange.upper); 1563 } 1564 } 1565 } 1566 // Skip a logical default block that can never be referenced. 1567 if (isLogicalSelector && attrList.size() == 2) 1568 defaultBlock = eval.parentConstruct->constructExit->block; 1569 attrList.push_back(mlir::UnitAttr::get(context)); 1570 blockList.push_back(defaultBlock); 1571 1572 // Generate a fir::SelectCaseOp. 1573 // Explicit branch code is better for the LOGICAL type. The CHARACTER type 1574 // does not yet have downstream support, and also uses explicit branch code. 1575 // The -no-structured-fir option can be used to force generation of INTEGER 1576 // type branch code. 1577 if (!isLogicalSelector && !isCharSelector && eval.lowerAsStructured()) { 1578 // Numeric selector is a ssa register, all temps that may have 1579 // been generated while evaluating it can be cleaned-up before the 1580 // fir.select_case. 1581 stmtCtx.finalize(); 1582 builder->create<fir::SelectCaseOp>(loc, selector, attrList, valueList, 1583 blockList); 1584 return; 1585 } 1586 1587 // Generate a sequence of case value comparisons and branches. 1588 auto caseValue = valueList.begin(); 1589 auto caseBlock = blockList.begin(); 1590 for (mlir::Attribute attr : attrList) { 1591 if (attr.isa<mlir::UnitAttr>()) { 1592 genFIRBranch(*caseBlock++); 1593 break; 1594 } 1595 auto genCond = [&](mlir::Value rhs, 1596 mlir::arith::CmpIPredicate pred) -> mlir::Value { 1597 if (!isCharSelector) 1598 return builder->create<mlir::arith::CmpIOp>(loc, pred, selector, rhs); 1599 fir::factory::CharacterExprHelper charHelper{*builder, loc}; 1600 std::pair<mlir::Value, mlir::Value> lhsVal = 1601 charHelper.createUnboxChar(selector); 1602 mlir::Value &lhsAddr = lhsVal.first; 1603 mlir::Value &lhsLen = lhsVal.second; 1604 std::pair<mlir::Value, mlir::Value> rhsVal = 1605 charHelper.createUnboxChar(rhs); 1606 mlir::Value &rhsAddr = rhsVal.first; 1607 mlir::Value &rhsLen = rhsVal.second; 1608 return fir::runtime::genCharCompare(*builder, loc, pred, lhsAddr, 1609 lhsLen, rhsAddr, rhsLen); 1610 }; 1611 mlir::Block *newBlock = insertBlock(*caseBlock); 1612 if (attr.isa<fir::ClosedIntervalAttr>()) { 1613 mlir::Block *newBlock2 = insertBlock(*caseBlock); 1614 mlir::Value cond = 1615 genCond(*caseValue++, mlir::arith::CmpIPredicate::sge); 1616 genFIRConditionalBranch(cond, newBlock, newBlock2); 1617 builder->setInsertionPointToEnd(newBlock); 1618 mlir::Value cond2 = 1619 genCond(*caseValue++, mlir::arith::CmpIPredicate::sle); 1620 genFIRConditionalBranch(cond2, *caseBlock++, newBlock2); 1621 builder->setInsertionPointToEnd(newBlock2); 1622 continue; 1623 } 1624 mlir::arith::CmpIPredicate pred; 1625 if (attr.isa<fir::PointIntervalAttr>()) { 1626 pred = mlir::arith::CmpIPredicate::eq; 1627 } else if (attr.isa<fir::LowerBoundAttr>()) { 1628 pred = mlir::arith::CmpIPredicate::sge; 1629 } else { 1630 assert(attr.isa<fir::UpperBoundAttr>() && "unexpected predicate"); 1631 pred = mlir::arith::CmpIPredicate::sle; 1632 } 1633 mlir::Value cond = genCond(*caseValue++, pred); 1634 genFIRConditionalBranch(cond, *caseBlock++, newBlock); 1635 builder->setInsertionPointToEnd(newBlock); 1636 } 1637 assert(caseValue == valueList.end() && caseBlock == blockList.end() && 1638 "select case list mismatch"); 1639 // Clean-up the selector at the end of the construct if it is a temporary 1640 // (which is possible with characters). 1641 mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint(); 1642 builder->setInsertionPointToEnd(eval.parentConstruct->constructExit->block); 1643 stmtCtx.finalize(); 1644 builder->restoreInsertionPoint(insertPt); 1645 } 1646 1647 fir::ExtendedValue 1648 genAssociateSelector(const Fortran::lower::SomeExpr &selector, 1649 Fortran::lower::StatementContext &stmtCtx) { 1650 return Fortran::lower::isArraySectionWithoutVectorSubscript(selector) 1651 ? Fortran::lower::createSomeArrayBox(*this, selector, 1652 localSymbols, stmtCtx) 1653 : genExprAddr(selector, stmtCtx); 1654 } 1655 1656 void genFIR(const Fortran::parser::AssociateConstruct &) { 1657 Fortran::lower::StatementContext stmtCtx; 1658 Fortran::lower::pft::Evaluation &eval = getEval(); 1659 for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) { 1660 if (auto *stmt = e.getIf<Fortran::parser::AssociateStmt>()) { 1661 if (eval.lowerAsUnstructured()) 1662 maybeStartBlock(e.block); 1663 localSymbols.pushScope(); 1664 for (const Fortran::parser::Association &assoc : 1665 std::get<std::list<Fortran::parser::Association>>(stmt->t)) { 1666 Fortran::semantics::Symbol &sym = 1667 *std::get<Fortran::parser::Name>(assoc.t).symbol; 1668 const Fortran::lower::SomeExpr &selector = 1669 *sym.get<Fortran::semantics::AssocEntityDetails>().expr(); 1670 localSymbols.addSymbol(sym, genAssociateSelector(selector, stmtCtx)); 1671 } 1672 } else if (e.getIf<Fortran::parser::EndAssociateStmt>()) { 1673 if (eval.lowerAsUnstructured()) 1674 maybeStartBlock(e.block); 1675 stmtCtx.finalize(); 1676 localSymbols.popScope(); 1677 } else { 1678 genFIR(e); 1679 } 1680 } 1681 } 1682 1683 void genFIR(const Fortran::parser::BlockConstruct &blockConstruct) { 1684 setCurrentPositionAt(blockConstruct); 1685 TODO(toLocation(), "BlockConstruct lowering"); 1686 } 1687 void genFIR(const Fortran::parser::BlockStmt &) { 1688 TODO(toLocation(), "BlockStmt lowering"); 1689 } 1690 void genFIR(const Fortran::parser::EndBlockStmt &) { 1691 TODO(toLocation(), "EndBlockStmt lowering"); 1692 } 1693 1694 void genFIR(const Fortran::parser::ChangeTeamConstruct &construct) { 1695 TODO(toLocation(), "ChangeTeamConstruct lowering"); 1696 } 1697 void genFIR(const Fortran::parser::ChangeTeamStmt &stmt) { 1698 TODO(toLocation(), "ChangeTeamStmt lowering"); 1699 } 1700 void genFIR(const Fortran::parser::EndChangeTeamStmt &stmt) { 1701 TODO(toLocation(), "EndChangeTeamStmt lowering"); 1702 } 1703 1704 void genFIR(const Fortran::parser::CriticalConstruct &criticalConstruct) { 1705 setCurrentPositionAt(criticalConstruct); 1706 TODO(toLocation(), "CriticalConstruct lowering"); 1707 } 1708 void genFIR(const Fortran::parser::CriticalStmt &) { 1709 TODO(toLocation(), "CriticalStmt lowering"); 1710 } 1711 void genFIR(const Fortran::parser::EndCriticalStmt &) { 1712 TODO(toLocation(), "EndCriticalStmt lowering"); 1713 } 1714 1715 void genFIR(const Fortran::parser::SelectRankConstruct &selectRankConstruct) { 1716 setCurrentPositionAt(selectRankConstruct); 1717 TODO(toLocation(), "SelectRankConstruct lowering"); 1718 } 1719 void genFIR(const Fortran::parser::SelectRankStmt &) { 1720 TODO(toLocation(), "SelectRankStmt lowering"); 1721 } 1722 void genFIR(const Fortran::parser::SelectRankCaseStmt &) { 1723 TODO(toLocation(), "SelectRankCaseStmt lowering"); 1724 } 1725 1726 void genFIR(const Fortran::parser::SelectTypeConstruct &selectTypeConstruct) { 1727 setCurrentPositionAt(selectTypeConstruct); 1728 TODO(toLocation(), "SelectTypeConstruct lowering"); 1729 } 1730 void genFIR(const Fortran::parser::SelectTypeStmt &) { 1731 TODO(toLocation(), "SelectTypeStmt lowering"); 1732 } 1733 void genFIR(const Fortran::parser::TypeGuardStmt &) { 1734 TODO(toLocation(), "TypeGuardStmt lowering"); 1735 } 1736 1737 //===--------------------------------------------------------------------===// 1738 // IO statements (see io.h) 1739 //===--------------------------------------------------------------------===// 1740 1741 void genFIR(const Fortran::parser::BackspaceStmt &stmt) { 1742 mlir::Value iostat = genBackspaceStatement(*this, stmt); 1743 genIoConditionBranches(getEval(), stmt.v, iostat); 1744 } 1745 void genFIR(const Fortran::parser::CloseStmt &stmt) { 1746 mlir::Value iostat = genCloseStatement(*this, stmt); 1747 genIoConditionBranches(getEval(), stmt.v, iostat); 1748 } 1749 void genFIR(const Fortran::parser::EndfileStmt &stmt) { 1750 mlir::Value iostat = genEndfileStatement(*this, stmt); 1751 genIoConditionBranches(getEval(), stmt.v, iostat); 1752 } 1753 void genFIR(const Fortran::parser::FlushStmt &stmt) { 1754 mlir::Value iostat = genFlushStatement(*this, stmt); 1755 genIoConditionBranches(getEval(), stmt.v, iostat); 1756 } 1757 void genFIR(const Fortran::parser::InquireStmt &stmt) { 1758 mlir::Value iostat = genInquireStatement(*this, stmt); 1759 if (const auto *specs = 1760 std::get_if<std::list<Fortran::parser::InquireSpec>>(&stmt.u)) 1761 genIoConditionBranches(getEval(), *specs, iostat); 1762 } 1763 void genFIR(const Fortran::parser::OpenStmt &stmt) { 1764 mlir::Value iostat = genOpenStatement(*this, stmt); 1765 genIoConditionBranches(getEval(), stmt.v, iostat); 1766 } 1767 void genFIR(const Fortran::parser::PrintStmt &stmt) { 1768 genPrintStatement(*this, stmt); 1769 } 1770 void genFIR(const Fortran::parser::ReadStmt &stmt) { 1771 mlir::Value iostat = genReadStatement(*this, stmt); 1772 genIoConditionBranches(getEval(), stmt.controls, iostat); 1773 } 1774 void genFIR(const Fortran::parser::RewindStmt &stmt) { 1775 mlir::Value iostat = genRewindStatement(*this, stmt); 1776 genIoConditionBranches(getEval(), stmt.v, iostat); 1777 } 1778 void genFIR(const Fortran::parser::WaitStmt &stmt) { 1779 mlir::Value iostat = genWaitStatement(*this, stmt); 1780 genIoConditionBranches(getEval(), stmt.v, iostat); 1781 } 1782 void genFIR(const Fortran::parser::WriteStmt &stmt) { 1783 mlir::Value iostat = genWriteStatement(*this, stmt); 1784 genIoConditionBranches(getEval(), stmt.controls, iostat); 1785 } 1786 1787 template <typename A> 1788 void genIoConditionBranches(Fortran::lower::pft::Evaluation &eval, 1789 const A &specList, mlir::Value iostat) { 1790 if (!iostat) 1791 return; 1792 1793 mlir::Block *endBlock = nullptr; 1794 mlir::Block *eorBlock = nullptr; 1795 mlir::Block *errBlock = nullptr; 1796 for (const auto &spec : specList) { 1797 std::visit(Fortran::common::visitors{ 1798 [&](const Fortran::parser::EndLabel &label) { 1799 endBlock = blockOfLabel(eval, label.v); 1800 }, 1801 [&](const Fortran::parser::EorLabel &label) { 1802 eorBlock = blockOfLabel(eval, label.v); 1803 }, 1804 [&](const Fortran::parser::ErrLabel &label) { 1805 errBlock = blockOfLabel(eval, label.v); 1806 }, 1807 [](const auto &) {}}, 1808 spec.u); 1809 } 1810 if (!endBlock && !eorBlock && !errBlock) 1811 return; 1812 1813 mlir::Location loc = toLocation(); 1814 mlir::Type indexType = builder->getIndexType(); 1815 mlir::Value selector = builder->createConvert(loc, indexType, iostat); 1816 llvm::SmallVector<int64_t> indexList; 1817 llvm::SmallVector<mlir::Block *> blockList; 1818 if (eorBlock) { 1819 indexList.push_back(Fortran::runtime::io::IostatEor); 1820 blockList.push_back(eorBlock); 1821 } 1822 if (endBlock) { 1823 indexList.push_back(Fortran::runtime::io::IostatEnd); 1824 blockList.push_back(endBlock); 1825 } 1826 if (errBlock) { 1827 indexList.push_back(0); 1828 blockList.push_back(eval.nonNopSuccessor().block); 1829 // ERR label statement is the default successor. 1830 blockList.push_back(errBlock); 1831 } else { 1832 // Fallthrough successor statement is the default successor. 1833 blockList.push_back(eval.nonNopSuccessor().block); 1834 } 1835 builder->create<fir::SelectOp>(loc, selector, indexList, blockList); 1836 } 1837 1838 //===--------------------------------------------------------------------===// 1839 // Memory allocation and deallocation 1840 //===--------------------------------------------------------------------===// 1841 1842 void genFIR(const Fortran::parser::AllocateStmt &stmt) { 1843 Fortran::lower::genAllocateStmt(*this, stmt, toLocation()); 1844 } 1845 1846 void genFIR(const Fortran::parser::DeallocateStmt &stmt) { 1847 Fortran::lower::genDeallocateStmt(*this, stmt, toLocation()); 1848 } 1849 1850 /// Nullify pointer object list 1851 /// 1852 /// For each pointer object, reset the pointer to a disassociated status. 1853 /// We do this by setting each pointer to null. 1854 void genFIR(const Fortran::parser::NullifyStmt &stmt) { 1855 mlir::Location loc = toLocation(); 1856 for (auto &pointerObject : stmt.v) { 1857 const Fortran::lower::SomeExpr *expr = 1858 Fortran::semantics::GetExpr(pointerObject); 1859 assert(expr); 1860 fir::MutableBoxValue box = genExprMutableBox(loc, *expr); 1861 fir::factory::disassociateMutableBox(*builder, loc, box); 1862 } 1863 } 1864 1865 //===--------------------------------------------------------------------===// 1866 1867 void genFIR(const Fortran::parser::EventPostStmt &stmt) { 1868 genEventPostStatement(*this, stmt); 1869 } 1870 1871 void genFIR(const Fortran::parser::EventWaitStmt &stmt) { 1872 genEventWaitStatement(*this, stmt); 1873 } 1874 1875 void genFIR(const Fortran::parser::FormTeamStmt &stmt) { 1876 genFormTeamStatement(*this, getEval(), stmt); 1877 } 1878 1879 void genFIR(const Fortran::parser::LockStmt &stmt) { 1880 genLockStatement(*this, stmt); 1881 } 1882 1883 fir::ExtendedValue 1884 genInitializerExprValue(const Fortran::lower::SomeExpr &expr, 1885 Fortran::lower::StatementContext &stmtCtx) { 1886 return Fortran::lower::createSomeInitializerExpression( 1887 toLocation(), *this, expr, localSymbols, stmtCtx); 1888 } 1889 1890 /// Return true if the current context is a conditionalized and implied 1891 /// iteration space. 1892 bool implicitIterationSpace() { return !implicitIterSpace.empty(); } 1893 1894 /// Return true if context is currently an explicit iteration space. A scalar 1895 /// assignment expression may be contextually within a user-defined iteration 1896 /// space, transforming it into an array expression. 1897 bool explicitIterationSpace() { return explicitIterSpace.isActive(); } 1898 1899 /// Generate an array assignment. 1900 /// This is an assignment expression with rank > 0. The assignment may or may 1901 /// not be in a WHERE and/or FORALL context. 1902 /// In a FORALL context, the assignment may be a pointer assignment and the \p 1903 /// lbounds and \p ubounds parameters should only be used in such a pointer 1904 /// assignment case. (If both are None then the array assignment cannot be a 1905 /// pointer assignment.) 1906 void genArrayAssignment( 1907 const Fortran::evaluate::Assignment &assign, 1908 Fortran::lower::StatementContext &stmtCtx, 1909 llvm::Optional<llvm::SmallVector<mlir::Value>> lbounds = llvm::None, 1910 llvm::Optional<llvm::SmallVector<mlir::Value>> ubounds = llvm::None) { 1911 if (Fortran::lower::isWholeAllocatable(assign.lhs)) { 1912 // Assignment to allocatables may require the lhs to be 1913 // deallocated/reallocated. See Fortran 2018 10.2.1.3 p3 1914 Fortran::lower::createAllocatableArrayAssignment( 1915 *this, assign.lhs, assign.rhs, explicitIterSpace, implicitIterSpace, 1916 localSymbols, stmtCtx); 1917 return; 1918 } 1919 1920 if (lbounds.hasValue()) { 1921 // Array of POINTER entities, with elemental assignment. 1922 if (!Fortran::lower::isWholePointer(assign.lhs)) 1923 fir::emitFatalError(toLocation(), "pointer assignment to non-pointer"); 1924 1925 Fortran::lower::createArrayOfPointerAssignment( 1926 *this, assign.lhs, assign.rhs, explicitIterSpace, implicitIterSpace, 1927 lbounds.getValue(), ubounds, localSymbols, stmtCtx); 1928 return; 1929 } 1930 1931 if (!implicitIterationSpace() && !explicitIterationSpace()) { 1932 // No masks and the iteration space is implied by the array, so create a 1933 // simple array assignment. 1934 Fortran::lower::createSomeArrayAssignment(*this, assign.lhs, assign.rhs, 1935 localSymbols, stmtCtx); 1936 return; 1937 } 1938 1939 // If there is an explicit iteration space, generate an array assignment 1940 // with a user-specified iteration space and possibly with masks. These 1941 // assignments may *appear* to be scalar expressions, but the scalar 1942 // expression is evaluated at all points in the user-defined space much like 1943 // an ordinary array assignment. More specifically, the semantics inside the 1944 // FORALL much more closely resembles that of WHERE than a scalar 1945 // assignment. 1946 // Otherwise, generate a masked array assignment. The iteration space is 1947 // implied by the lhs array expression. 1948 Fortran::lower::createAnyMaskedArrayAssignment( 1949 *this, assign.lhs, assign.rhs, explicitIterSpace, implicitIterSpace, 1950 localSymbols, 1951 explicitIterationSpace() ? explicitIterSpace.stmtContext() 1952 : implicitIterSpace.stmtContext()); 1953 } 1954 1955 #if !defined(NDEBUG) 1956 static bool isFuncResultDesignator(const Fortran::lower::SomeExpr &expr) { 1957 const Fortran::semantics::Symbol *sym = 1958 Fortran::evaluate::GetFirstSymbol(expr); 1959 return sym && sym->IsFuncResult(); 1960 } 1961 #endif 1962 1963 inline fir::MutableBoxValue 1964 genExprMutableBox(mlir::Location loc, 1965 const Fortran::lower::SomeExpr &expr) override final { 1966 return Fortran::lower::createMutableBox(loc, *this, expr, localSymbols); 1967 } 1968 1969 /// Shared for both assignments and pointer assignments. 1970 void genAssignment(const Fortran::evaluate::Assignment &assign) { 1971 Fortran::lower::StatementContext stmtCtx; 1972 mlir::Location loc = toLocation(); 1973 if (explicitIterationSpace()) { 1974 Fortran::lower::createArrayLoads(*this, explicitIterSpace, localSymbols); 1975 explicitIterSpace.genLoopNest(); 1976 } 1977 std::visit( 1978 Fortran::common::visitors{ 1979 // [1] Plain old assignment. 1980 [&](const Fortran::evaluate::Assignment::Intrinsic &) { 1981 const Fortran::semantics::Symbol *sym = 1982 Fortran::evaluate::GetLastSymbol(assign.lhs); 1983 1984 if (!sym) 1985 TODO(loc, "assignment to pointer result of function reference"); 1986 1987 std::optional<Fortran::evaluate::DynamicType> lhsType = 1988 assign.lhs.GetType(); 1989 assert(lhsType && "lhs cannot be typeless"); 1990 // Assignment to polymorphic allocatables may require changing the 1991 // variable dynamic type (See Fortran 2018 10.2.1.3 p3). 1992 if (lhsType->IsPolymorphic() && 1993 Fortran::lower::isWholeAllocatable(assign.lhs)) 1994 TODO(loc, "assignment to polymorphic allocatable"); 1995 1996 // Note: No ad-hoc handling for pointers is required here. The 1997 // target will be assigned as per 2018 10.2.1.3 p2. genExprAddr 1998 // on a pointer returns the target address and not the address of 1999 // the pointer variable. 2000 2001 if (assign.lhs.Rank() > 0 || explicitIterationSpace()) { 2002 // Array assignment 2003 // See Fortran 2018 10.2.1.3 p5, p6, and p7 2004 genArrayAssignment(assign, stmtCtx); 2005 return; 2006 } 2007 2008 // Scalar assignment 2009 const bool isNumericScalar = 2010 isNumericScalarCategory(lhsType->category()); 2011 fir::ExtendedValue rhs = isNumericScalar 2012 ? genExprValue(assign.rhs, stmtCtx) 2013 : genExprAddr(assign.rhs, stmtCtx); 2014 const bool lhsIsWholeAllocatable = 2015 Fortran::lower::isWholeAllocatable(assign.lhs); 2016 llvm::Optional<fir::factory::MutableBoxReallocation> lhsRealloc; 2017 llvm::Optional<fir::MutableBoxValue> lhsMutableBox; 2018 auto lhs = [&]() -> fir::ExtendedValue { 2019 if (lhsIsWholeAllocatable) { 2020 lhsMutableBox = genExprMutableBox(loc, assign.lhs); 2021 llvm::SmallVector<mlir::Value> lengthParams; 2022 if (const fir::CharBoxValue *charBox = rhs.getCharBox()) 2023 lengthParams.push_back(charBox->getLen()); 2024 else if (fir::isDerivedWithLenParameters(rhs)) 2025 TODO(loc, "assignment to derived type allocatable with " 2026 "length parameters"); 2027 lhsRealloc = fir::factory::genReallocIfNeeded( 2028 *builder, loc, *lhsMutableBox, 2029 /*shape=*/llvm::None, lengthParams); 2030 return lhsRealloc->newValue; 2031 } 2032 return genExprAddr(assign.lhs, stmtCtx); 2033 }(); 2034 2035 if (isNumericScalar) { 2036 // Fortran 2018 10.2.1.3 p8 and p9 2037 // Conversions should have been inserted by semantic analysis, 2038 // but they can be incorrect between the rhs and lhs. Correct 2039 // that here. 2040 mlir::Value addr = fir::getBase(lhs); 2041 mlir::Value val = fir::getBase(rhs); 2042 // A function with multiple entry points returning different 2043 // types tags all result variables with one of the largest 2044 // types to allow them to share the same storage. Assignment 2045 // to a result variable of one of the other types requires 2046 // conversion to the actual type. 2047 mlir::Type toTy = genType(assign.lhs); 2048 mlir::Value cast = 2049 builder->convertWithSemantics(loc, toTy, val); 2050 if (fir::dyn_cast_ptrEleTy(addr.getType()) != toTy) { 2051 assert(isFuncResultDesignator(assign.lhs) && "type mismatch"); 2052 addr = builder->createConvert( 2053 toLocation(), builder->getRefType(toTy), addr); 2054 } 2055 builder->create<fir::StoreOp>(loc, cast, addr); 2056 } else if (isCharacterCategory(lhsType->category())) { 2057 // Fortran 2018 10.2.1.3 p10 and p11 2058 fir::factory::CharacterExprHelper{*builder, loc}.createAssign( 2059 lhs, rhs); 2060 } else if (isDerivedCategory(lhsType->category())) { 2061 // Fortran 2018 10.2.1.3 p13 and p14 2062 // Recursively gen an assignment on each element pair. 2063 fir::factory::genRecordAssignment(*builder, loc, lhs, rhs); 2064 } else { 2065 llvm_unreachable("unknown category"); 2066 } 2067 if (lhsIsWholeAllocatable) 2068 fir::factory::finalizeRealloc( 2069 *builder, loc, lhsMutableBox.getValue(), 2070 /*lbounds=*/llvm::None, /*takeLboundsIfRealloc=*/false, 2071 lhsRealloc.getValue()); 2072 }, 2073 2074 // [2] User defined assignment. If the context is a scalar 2075 // expression then call the procedure. 2076 [&](const Fortran::evaluate::ProcedureRef &procRef) { 2077 Fortran::lower::StatementContext &ctx = 2078 explicitIterationSpace() ? explicitIterSpace.stmtContext() 2079 : stmtCtx; 2080 Fortran::lower::createSubroutineCall( 2081 *this, procRef, explicitIterSpace, implicitIterSpace, 2082 localSymbols, ctx, /*isUserDefAssignment=*/true); 2083 }, 2084 2085 // [3] Pointer assignment with possibly empty bounds-spec. R1035: a 2086 // bounds-spec is a lower bound value. 2087 [&](const Fortran::evaluate::Assignment::BoundsSpec &lbExprs) { 2088 if (Fortran::evaluate::IsProcedure(assign.rhs)) 2089 TODO(loc, "procedure pointer assignment"); 2090 std::optional<Fortran::evaluate::DynamicType> lhsType = 2091 assign.lhs.GetType(); 2092 std::optional<Fortran::evaluate::DynamicType> rhsType = 2093 assign.rhs.GetType(); 2094 // Polymorphic lhs/rhs may need more care. See F2018 10.2.2.3. 2095 if ((lhsType && lhsType->IsPolymorphic()) || 2096 (rhsType && rhsType->IsPolymorphic())) 2097 TODO(loc, "pointer assignment involving polymorphic entity"); 2098 2099 llvm::SmallVector<mlir::Value> lbounds; 2100 for (const Fortran::evaluate::ExtentExpr &lbExpr : lbExprs) 2101 lbounds.push_back( 2102 fir::getBase(genExprValue(toEvExpr(lbExpr), stmtCtx))); 2103 if (explicitIterationSpace()) { 2104 // Pointer assignment in FORALL context. Copy the rhs box value 2105 // into the lhs box variable. 2106 genArrayAssignment(assign, stmtCtx, lbounds); 2107 return; 2108 } 2109 fir::MutableBoxValue lhs = genExprMutableBox(loc, assign.lhs); 2110 Fortran::lower::associateMutableBox(*this, loc, lhs, assign.rhs, 2111 lbounds, stmtCtx); 2112 }, 2113 2114 // [4] Pointer assignment with bounds-remapping. R1036: a 2115 // bounds-remapping is a pair, lower bound and upper bound. 2116 [&](const Fortran::evaluate::Assignment::BoundsRemapping 2117 &boundExprs) { 2118 std::optional<Fortran::evaluate::DynamicType> lhsType = 2119 assign.lhs.GetType(); 2120 std::optional<Fortran::evaluate::DynamicType> rhsType = 2121 assign.rhs.GetType(); 2122 // Polymorphic lhs/rhs may need more care. See F2018 10.2.2.3. 2123 if ((lhsType && lhsType->IsPolymorphic()) || 2124 (rhsType && rhsType->IsPolymorphic())) 2125 TODO(loc, "pointer assignment involving polymorphic entity"); 2126 2127 llvm::SmallVector<mlir::Value> lbounds; 2128 llvm::SmallVector<mlir::Value> ubounds; 2129 for (const std::pair<Fortran::evaluate::ExtentExpr, 2130 Fortran::evaluate::ExtentExpr> &pair : 2131 boundExprs) { 2132 const Fortran::evaluate::ExtentExpr &lbExpr = pair.first; 2133 const Fortran::evaluate::ExtentExpr &ubExpr = pair.second; 2134 lbounds.push_back( 2135 fir::getBase(genExprValue(toEvExpr(lbExpr), stmtCtx))); 2136 ubounds.push_back( 2137 fir::getBase(genExprValue(toEvExpr(ubExpr), stmtCtx))); 2138 } 2139 if (explicitIterationSpace()) { 2140 // Pointer assignment in FORALL context. Copy the rhs box value 2141 // into the lhs box variable. 2142 genArrayAssignment(assign, stmtCtx, lbounds, ubounds); 2143 return; 2144 } 2145 fir::MutableBoxValue lhs = genExprMutableBox(loc, assign.lhs); 2146 if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>( 2147 assign.rhs)) { 2148 fir::factory::disassociateMutableBox(*builder, loc, lhs); 2149 return; 2150 } 2151 // Do not generate a temp in case rhs is an array section. 2152 fir::ExtendedValue rhs = 2153 Fortran::lower::isArraySectionWithoutVectorSubscript( 2154 assign.rhs) 2155 ? Fortran::lower::createSomeArrayBox( 2156 *this, assign.rhs, localSymbols, stmtCtx) 2157 : genExprAddr(assign.rhs, stmtCtx); 2158 fir::factory::associateMutableBoxWithRemap(*builder, loc, lhs, 2159 rhs, lbounds, ubounds); 2160 if (explicitIterationSpace()) { 2161 mlir::ValueRange inners = explicitIterSpace.getInnerArgs(); 2162 if (!inners.empty()) 2163 builder->create<fir::ResultOp>(loc, inners); 2164 } 2165 }, 2166 }, 2167 assign.u); 2168 if (explicitIterationSpace()) 2169 Fortran::lower::createArrayMergeStores(*this, explicitIterSpace); 2170 } 2171 2172 void genFIR(const Fortran::parser::WhereConstruct &c) { 2173 implicitIterSpace.growStack(); 2174 genNestedStatement( 2175 std::get< 2176 Fortran::parser::Statement<Fortran::parser::WhereConstructStmt>>( 2177 c.t)); 2178 for (const auto &body : 2179 std::get<std::list<Fortran::parser::WhereBodyConstruct>>(c.t)) 2180 genFIR(body); 2181 for (const auto &e : 2182 std::get<std::list<Fortran::parser::WhereConstruct::MaskedElsewhere>>( 2183 c.t)) 2184 genFIR(e); 2185 if (const auto &e = 2186 std::get<std::optional<Fortran::parser::WhereConstruct::Elsewhere>>( 2187 c.t); 2188 e.has_value()) 2189 genFIR(*e); 2190 genNestedStatement( 2191 std::get<Fortran::parser::Statement<Fortran::parser::EndWhereStmt>>( 2192 c.t)); 2193 } 2194 void genFIR(const Fortran::parser::WhereBodyConstruct &body) { 2195 std::visit( 2196 Fortran::common::visitors{ 2197 [&](const Fortran::parser::Statement< 2198 Fortran::parser::AssignmentStmt> &stmt) { 2199 genNestedStatement(stmt); 2200 }, 2201 [&](const Fortran::parser::Statement<Fortran::parser::WhereStmt> 2202 &stmt) { genNestedStatement(stmt); }, 2203 [&](const Fortran::common::Indirection< 2204 Fortran::parser::WhereConstruct> &c) { genFIR(c.value()); }, 2205 }, 2206 body.u); 2207 } 2208 void genFIR(const Fortran::parser::WhereConstructStmt &stmt) { 2209 implicitIterSpace.append(Fortran::semantics::GetExpr( 2210 std::get<Fortran::parser::LogicalExpr>(stmt.t))); 2211 } 2212 void genFIR(const Fortran::parser::WhereConstruct::MaskedElsewhere &ew) { 2213 genNestedStatement( 2214 std::get< 2215 Fortran::parser::Statement<Fortran::parser::MaskedElsewhereStmt>>( 2216 ew.t)); 2217 for (const auto &body : 2218 std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew.t)) 2219 genFIR(body); 2220 } 2221 void genFIR(const Fortran::parser::MaskedElsewhereStmt &stmt) { 2222 implicitIterSpace.append(Fortran::semantics::GetExpr( 2223 std::get<Fortran::parser::LogicalExpr>(stmt.t))); 2224 } 2225 void genFIR(const Fortran::parser::WhereConstruct::Elsewhere &ew) { 2226 genNestedStatement( 2227 std::get<Fortran::parser::Statement<Fortran::parser::ElsewhereStmt>>( 2228 ew.t)); 2229 for (const auto &body : 2230 std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew.t)) 2231 genFIR(body); 2232 } 2233 void genFIR(const Fortran::parser::ElsewhereStmt &stmt) { 2234 implicitIterSpace.append(nullptr); 2235 } 2236 void genFIR(const Fortran::parser::EndWhereStmt &) { 2237 implicitIterSpace.shrinkStack(); 2238 } 2239 2240 void genFIR(const Fortran::parser::WhereStmt &stmt) { 2241 Fortran::lower::StatementContext stmtCtx; 2242 const auto &assign = std::get<Fortran::parser::AssignmentStmt>(stmt.t); 2243 implicitIterSpace.growStack(); 2244 implicitIterSpace.append(Fortran::semantics::GetExpr( 2245 std::get<Fortran::parser::LogicalExpr>(stmt.t))); 2246 genAssignment(*assign.typedAssignment->v); 2247 implicitIterSpace.shrinkStack(); 2248 } 2249 2250 void genFIR(const Fortran::parser::PointerAssignmentStmt &stmt) { 2251 genAssignment(*stmt.typedAssignment->v); 2252 } 2253 2254 void genFIR(const Fortran::parser::AssignmentStmt &stmt) { 2255 genAssignment(*stmt.typedAssignment->v); 2256 } 2257 2258 void genFIR(const Fortran::parser::SyncAllStmt &stmt) { 2259 genSyncAllStatement(*this, stmt); 2260 } 2261 2262 void genFIR(const Fortran::parser::SyncImagesStmt &stmt) { 2263 genSyncImagesStatement(*this, stmt); 2264 } 2265 2266 void genFIR(const Fortran::parser::SyncMemoryStmt &stmt) { 2267 genSyncMemoryStatement(*this, stmt); 2268 } 2269 2270 void genFIR(const Fortran::parser::SyncTeamStmt &stmt) { 2271 genSyncTeamStatement(*this, stmt); 2272 } 2273 2274 void genFIR(const Fortran::parser::UnlockStmt &stmt) { 2275 genUnlockStatement(*this, stmt); 2276 } 2277 2278 void genFIR(const Fortran::parser::AssignStmt &stmt) { 2279 const Fortran::semantics::Symbol &symbol = 2280 *std::get<Fortran::parser::Name>(stmt.t).symbol; 2281 mlir::Location loc = toLocation(); 2282 mlir::Value labelValue = builder->createIntegerConstant( 2283 loc, genType(symbol), std::get<Fortran::parser::Label>(stmt.t)); 2284 builder->create<fir::StoreOp>(loc, labelValue, getSymbolAddress(symbol)); 2285 } 2286 2287 void genFIR(const Fortran::parser::FormatStmt &) { 2288 // do nothing. 2289 2290 // FORMAT statements have no semantics. They may be lowered if used by a 2291 // data transfer statement. 2292 } 2293 2294 void genFIR(const Fortran::parser::PauseStmt &stmt) { 2295 genPauseStatement(*this, stmt); 2296 } 2297 2298 // call FAIL IMAGE in runtime 2299 void genFIR(const Fortran::parser::FailImageStmt &stmt) { 2300 genFailImageStatement(*this); 2301 } 2302 2303 // call STOP, ERROR STOP in runtime 2304 void genFIR(const Fortran::parser::StopStmt &stmt) { 2305 genStopStatement(*this, stmt); 2306 } 2307 2308 void genFIR(const Fortran::parser::ReturnStmt &stmt) { 2309 Fortran::lower::pft::FunctionLikeUnit *funit = 2310 getEval().getOwningProcedure(); 2311 assert(funit && "not inside main program, function or subroutine"); 2312 if (funit->isMainProgram()) { 2313 genExitRoutine(); 2314 return; 2315 } 2316 mlir::Location loc = toLocation(); 2317 if (stmt.v) { 2318 // Alternate return statement - If this is a subroutine where some 2319 // alternate entries have alternate returns, but the active entry point 2320 // does not, ignore the alternate return value. Otherwise, assign it 2321 // to the compiler-generated result variable. 2322 const Fortran::semantics::Symbol &symbol = funit->getSubprogramSymbol(); 2323 if (Fortran::semantics::HasAlternateReturns(symbol)) { 2324 Fortran::lower::StatementContext stmtCtx; 2325 const Fortran::lower::SomeExpr *expr = 2326 Fortran::semantics::GetExpr(*stmt.v); 2327 assert(expr && "missing alternate return expression"); 2328 mlir::Value altReturnIndex = builder->createConvert( 2329 loc, builder->getIndexType(), createFIRExpr(loc, expr, stmtCtx)); 2330 builder->create<fir::StoreOp>(loc, altReturnIndex, 2331 getAltReturnResult(symbol)); 2332 } 2333 } 2334 // Branch to the last block of the SUBROUTINE, which has the actual return. 2335 if (!funit->finalBlock) { 2336 mlir::OpBuilder::InsertPoint insPt = builder->saveInsertionPoint(); 2337 funit->finalBlock = builder->createBlock(&builder->getRegion()); 2338 builder->restoreInsertionPoint(insPt); 2339 } 2340 builder->create<mlir::cf::BranchOp>(loc, funit->finalBlock); 2341 } 2342 2343 void genFIR(const Fortran::parser::CycleStmt &) { 2344 genFIRBranch(getEval().controlSuccessor->block); 2345 } 2346 void genFIR(const Fortran::parser::ExitStmt &) { 2347 genFIRBranch(getEval().controlSuccessor->block); 2348 } 2349 void genFIR(const Fortran::parser::GotoStmt &) { 2350 genFIRBranch(getEval().controlSuccessor->block); 2351 } 2352 2353 // Nop statements - No code, or code is generated at the construct level. 2354 void genFIR(const Fortran::parser::AssociateStmt &) {} // nop 2355 void genFIR(const Fortran::parser::CaseStmt &) {} // nop 2356 void genFIR(const Fortran::parser::ContinueStmt &) {} // nop 2357 void genFIR(const Fortran::parser::ElseIfStmt &) {} // nop 2358 void genFIR(const Fortran::parser::ElseStmt &) {} // nop 2359 void genFIR(const Fortran::parser::EndAssociateStmt &) {} // nop 2360 void genFIR(const Fortran::parser::EndDoStmt &) {} // nop 2361 void genFIR(const Fortran::parser::EndFunctionStmt &) {} // nop 2362 void genFIR(const Fortran::parser::EndIfStmt &) {} // nop 2363 void genFIR(const Fortran::parser::EndMpSubprogramStmt &) {} // nop 2364 void genFIR(const Fortran::parser::EndSelectStmt &) {} // nop 2365 void genFIR(const Fortran::parser::EndSubroutineStmt &) {} // nop 2366 void genFIR(const Fortran::parser::EntryStmt &) {} // nop 2367 void genFIR(const Fortran::parser::IfStmt &) {} // nop 2368 void genFIR(const Fortran::parser::IfThenStmt &) {} // nop 2369 void genFIR(const Fortran::parser::NonLabelDoStmt &) {} // nop 2370 void genFIR(const Fortran::parser::OmpEndLoopDirective &) {} // nop 2371 2372 void genFIR(const Fortran::parser::NamelistStmt &) { 2373 TODO(toLocation(), "NamelistStmt lowering"); 2374 } 2375 2376 /// Generate FIR for the Evaluation `eval`. 2377 void genFIR(Fortran::lower::pft::Evaluation &eval, 2378 bool unstructuredContext = true) { 2379 if (unstructuredContext) { 2380 // When transitioning from unstructured to structured code, 2381 // the structured code could be a target that starts a new block. 2382 maybeStartBlock(eval.isConstruct() && eval.lowerAsStructured() 2383 ? eval.getFirstNestedEvaluation().block 2384 : eval.block); 2385 } 2386 2387 setCurrentEval(eval); 2388 setCurrentPosition(eval.position); 2389 eval.visit([&](const auto &stmt) { genFIR(stmt); }); 2390 2391 if (unstructuredContext && blockIsUnterminated()) { 2392 // Exit from an unstructured IF or SELECT construct block. 2393 Fortran::lower::pft::Evaluation *successor{}; 2394 if (eval.isActionStmt()) 2395 successor = eval.controlSuccessor; 2396 else if (eval.isConstruct() && 2397 eval.getLastNestedEvaluation() 2398 .lexicalSuccessor->isIntermediateConstructStmt()) 2399 successor = eval.constructExit; 2400 if (successor && successor->block) 2401 genFIRBranch(successor->block); 2402 } 2403 } 2404 2405 /// Map mlir function block arguments to the corresponding Fortran dummy 2406 /// variables. When the result is passed as a hidden argument, the Fortran 2407 /// result is also mapped. The symbol map is used to hold this mapping. 2408 void mapDummiesAndResults(Fortran::lower::pft::FunctionLikeUnit &funit, 2409 const Fortran::lower::CalleeInterface &callee) { 2410 assert(builder && "require a builder object at this point"); 2411 using PassBy = Fortran::lower::CalleeInterface::PassEntityBy; 2412 auto mapPassedEntity = [&](const auto arg) { 2413 if (arg.passBy == PassBy::AddressAndLength) { 2414 // TODO: now that fir call has some attributes regarding character 2415 // return, PassBy::AddressAndLength should be retired. 2416 mlir::Location loc = toLocation(); 2417 fir::factory::CharacterExprHelper charHelp{*builder, loc}; 2418 mlir::Value box = 2419 charHelp.createEmboxChar(arg.firArgument, arg.firLength); 2420 addSymbol(arg.entity->get(), box); 2421 } else { 2422 if (arg.entity.has_value()) { 2423 addSymbol(arg.entity->get(), arg.firArgument); 2424 } else { 2425 assert(funit.parentHasHostAssoc()); 2426 funit.parentHostAssoc().internalProcedureBindings(*this, 2427 localSymbols); 2428 } 2429 } 2430 }; 2431 for (const Fortran::lower::CalleeInterface::PassedEntity &arg : 2432 callee.getPassedArguments()) 2433 mapPassedEntity(arg); 2434 if (std::optional<Fortran::lower::CalleeInterface::PassedEntity> 2435 passedResult = callee.getPassedResult()) { 2436 mapPassedEntity(*passedResult); 2437 // FIXME: need to make sure things are OK here. addSymbol may not be OK 2438 if (funit.primaryResult && 2439 passedResult->entity->get() != *funit.primaryResult) 2440 addSymbol(*funit.primaryResult, 2441 getSymbolAddress(passedResult->entity->get())); 2442 } 2443 } 2444 2445 /// Instantiate variable \p var and add it to the symbol map. 2446 /// See ConvertVariable.cpp. 2447 void instantiateVar(const Fortran::lower::pft::Variable &var, 2448 Fortran::lower::AggregateStoreMap &storeMap) { 2449 Fortran::lower::instantiateVariable(*this, var, localSymbols, storeMap); 2450 } 2451 2452 /// Prepare to translate a new function 2453 void startNewFunction(Fortran::lower::pft::FunctionLikeUnit &funit) { 2454 assert(!builder && "expected nullptr"); 2455 Fortran::lower::CalleeInterface callee(funit, *this); 2456 mlir::func::FuncOp func = callee.addEntryBlockAndMapArguments(); 2457 builder = new fir::FirOpBuilder(func, bridge.getKindMap()); 2458 assert(builder && "FirOpBuilder did not instantiate"); 2459 builder->setInsertionPointToStart(&func.front()); 2460 func.setVisibility(mlir::SymbolTable::Visibility::Public); 2461 2462 mapDummiesAndResults(funit, callee); 2463 2464 // Note: not storing Variable references because getOrderedSymbolTable 2465 // below returns a temporary. 2466 llvm::SmallVector<Fortran::lower::pft::Variable> deferredFuncResultList; 2467 2468 // Backup actual argument for entry character results 2469 // with different lengths. It needs to be added to the non 2470 // primary results symbol before mapSymbolAttributes is called. 2471 Fortran::lower::SymbolBox resultArg; 2472 if (std::optional<Fortran::lower::CalleeInterface::PassedEntity> 2473 passedResult = callee.getPassedResult()) 2474 resultArg = lookupSymbol(passedResult->entity->get()); 2475 2476 Fortran::lower::AggregateStoreMap storeMap; 2477 // The front-end is currently not adding module variables referenced 2478 // in a module procedure as host associated. As a result we need to 2479 // instantiate all module variables here if this is a module procedure. 2480 // It is likely that the front-end behavior should change here. 2481 // This also applies to internal procedures inside module procedures. 2482 if (auto *module = Fortran::lower::pft::getAncestor< 2483 Fortran::lower::pft::ModuleLikeUnit>(funit)) 2484 for (const Fortran::lower::pft::Variable &var : 2485 module->getOrderedSymbolTable()) 2486 instantiateVar(var, storeMap); 2487 2488 mlir::Value primaryFuncResultStorage; 2489 for (const Fortran::lower::pft::Variable &var : 2490 funit.getOrderedSymbolTable()) { 2491 // Always instantiate aggregate storage blocks. 2492 if (var.isAggregateStore()) { 2493 instantiateVar(var, storeMap); 2494 continue; 2495 } 2496 const Fortran::semantics::Symbol &sym = var.getSymbol(); 2497 if (funit.parentHasHostAssoc()) { 2498 // Never instantitate host associated variables, as they are already 2499 // instantiated from an argument tuple. Instead, just bind the symbol to 2500 // the reference to the host variable, which must be in the map. 2501 const Fortran::semantics::Symbol &ultimate = sym.GetUltimate(); 2502 if (funit.parentHostAssoc().isAssociated(ultimate)) { 2503 Fortran::lower::SymbolBox hostBox = 2504 localSymbols.lookupSymbol(ultimate); 2505 assert(hostBox && "host association is not in map"); 2506 localSymbols.addSymbol(sym, hostBox.toExtendedValue()); 2507 continue; 2508 } 2509 } 2510 if (!sym.IsFuncResult() || !funit.primaryResult) { 2511 instantiateVar(var, storeMap); 2512 } else if (&sym == funit.primaryResult) { 2513 instantiateVar(var, storeMap); 2514 primaryFuncResultStorage = getSymbolAddress(sym); 2515 } else { 2516 deferredFuncResultList.push_back(var); 2517 } 2518 } 2519 2520 // TODO: should use same mechanism as equivalence? 2521 // One blocking point is character entry returns that need special handling 2522 // since they are not locally allocated but come as argument. CHARACTER(*) 2523 // is not something that fits well with equivalence lowering. 2524 for (const Fortran::lower::pft::Variable &altResult : 2525 deferredFuncResultList) { 2526 if (std::optional<Fortran::lower::CalleeInterface::PassedEntity> 2527 passedResult = callee.getPassedResult()) 2528 addSymbol(altResult.getSymbol(), resultArg.getAddr()); 2529 Fortran::lower::StatementContext stmtCtx; 2530 Fortran::lower::mapSymbolAttributes(*this, altResult, localSymbols, 2531 stmtCtx, primaryFuncResultStorage); 2532 } 2533 2534 // If this is a host procedure with host associations, then create the tuple 2535 // of pointers for passing to the internal procedures. 2536 if (!funit.getHostAssoc().empty()) 2537 funit.getHostAssoc().hostProcedureBindings(*this, localSymbols); 2538 2539 // Create most function blocks in advance. 2540 createEmptyBlocks(funit.evaluationList); 2541 2542 // Reinstate entry block as the current insertion point. 2543 builder->setInsertionPointToEnd(&func.front()); 2544 2545 if (callee.hasAlternateReturns()) { 2546 // Create a local temp to hold the alternate return index. 2547 // Give it an integer index type and the subroutine name (for dumps). 2548 // Attach it to the subroutine symbol in the localSymbols map. 2549 // Initialize it to zero, the "fallthrough" alternate return value. 2550 const Fortran::semantics::Symbol &symbol = funit.getSubprogramSymbol(); 2551 mlir::Location loc = toLocation(); 2552 mlir::Type idxTy = builder->getIndexType(); 2553 mlir::Value altResult = 2554 builder->createTemporary(loc, idxTy, toStringRef(symbol.name())); 2555 addSymbol(symbol, altResult); 2556 mlir::Value zero = builder->createIntegerConstant(loc, idxTy, 0); 2557 builder->create<fir::StoreOp>(loc, zero, altResult); 2558 } 2559 2560 if (Fortran::lower::pft::Evaluation *alternateEntryEval = 2561 funit.getEntryEval()) 2562 genFIRBranch(alternateEntryEval->lexicalSuccessor->block); 2563 } 2564 2565 /// Create global blocks for the current function. This eliminates the 2566 /// distinction between forward and backward targets when generating 2567 /// branches. A block is "global" if it can be the target of a GOTO or 2568 /// other source code branch. A block that can only be targeted by a 2569 /// compiler generated branch is "local". For example, a DO loop preheader 2570 /// block containing loop initialization code is global. A loop header 2571 /// block, which is the target of the loop back edge, is local. Blocks 2572 /// belong to a region. Any block within a nested region must be replaced 2573 /// with a block belonging to that region. Branches may not cross region 2574 /// boundaries. 2575 void createEmptyBlocks( 2576 std::list<Fortran::lower::pft::Evaluation> &evaluationList) { 2577 mlir::Region *region = &builder->getRegion(); 2578 for (Fortran::lower::pft::Evaluation &eval : evaluationList) { 2579 if (eval.isNewBlock) 2580 eval.block = builder->createBlock(region); 2581 if (eval.isConstruct() || eval.isDirective()) { 2582 if (eval.lowerAsUnstructured()) { 2583 createEmptyBlocks(eval.getNestedEvaluations()); 2584 } else if (eval.hasNestedEvaluations()) { 2585 // A structured construct that is a target starts a new block. 2586 Fortran::lower::pft::Evaluation &constructStmt = 2587 eval.getFirstNestedEvaluation(); 2588 if (constructStmt.isNewBlock) 2589 constructStmt.block = builder->createBlock(region); 2590 } 2591 } 2592 } 2593 } 2594 2595 /// Return the predicate: "current block does not have a terminator branch". 2596 bool blockIsUnterminated() { 2597 mlir::Block *currentBlock = builder->getBlock(); 2598 return currentBlock->empty() || 2599 !currentBlock->back().hasTrait<mlir::OpTrait::IsTerminator>(); 2600 } 2601 2602 /// Unconditionally switch code insertion to a new block. 2603 void startBlock(mlir::Block *newBlock) { 2604 assert(newBlock && "missing block"); 2605 // Default termination for the current block is a fallthrough branch to 2606 // the new block. 2607 if (blockIsUnterminated()) 2608 genFIRBranch(newBlock); 2609 // Some blocks may be re/started more than once, and might not be empty. 2610 // If the new block already has (only) a terminator, set the insertion 2611 // point to the start of the block. Otherwise set it to the end. 2612 builder->setInsertionPointToStart(newBlock); 2613 if (blockIsUnterminated()) 2614 builder->setInsertionPointToEnd(newBlock); 2615 } 2616 2617 /// Conditionally switch code insertion to a new block. 2618 void maybeStartBlock(mlir::Block *newBlock) { 2619 if (newBlock) 2620 startBlock(newBlock); 2621 } 2622 2623 /// Emit return and cleanup after the function has been translated. 2624 void endNewFunction(Fortran::lower::pft::FunctionLikeUnit &funit) { 2625 setCurrentPosition(Fortran::lower::pft::stmtSourceLoc(funit.endStmt)); 2626 if (funit.isMainProgram()) 2627 genExitRoutine(); 2628 else 2629 genFIRProcedureExit(funit, funit.getSubprogramSymbol()); 2630 funit.finalBlock = nullptr; 2631 LLVM_DEBUG(llvm::dbgs() << "*** Lowering result:\n\n" 2632 << *builder->getFunction() << '\n'); 2633 // FIXME: Simplification should happen in a normal pass, not here. 2634 mlir::IRRewriter rewriter(*builder); 2635 (void)mlir::simplifyRegions(rewriter, 2636 {builder->getRegion()}); // remove dead code 2637 delete builder; 2638 builder = nullptr; 2639 hostAssocTuple = mlir::Value{}; 2640 localSymbols.clear(); 2641 } 2642 2643 /// Helper to generate GlobalOps when the builder is not positioned in any 2644 /// region block. This is required because the FirOpBuilder assumes it is 2645 /// always positioned inside a region block when creating globals, the easiest 2646 /// way comply is to create a dummy function and to throw it afterwards. 2647 void createGlobalOutsideOfFunctionLowering( 2648 const std::function<void()> &createGlobals) { 2649 // FIXME: get rid of the bogus function context and instantiate the 2650 // globals directly into the module. 2651 mlir::MLIRContext *context = &getMLIRContext(); 2652 mlir::func::FuncOp func = fir::FirOpBuilder::createFunction( 2653 mlir::UnknownLoc::get(context), getModuleOp(), 2654 fir::NameUniquer::doGenerated("Sham"), 2655 mlir::FunctionType::get(context, llvm::None, llvm::None)); 2656 func.addEntryBlock(); 2657 builder = new fir::FirOpBuilder(func, bridge.getKindMap()); 2658 createGlobals(); 2659 if (mlir::Region *region = func.getCallableRegion()) 2660 region->dropAllReferences(); 2661 func.erase(); 2662 delete builder; 2663 builder = nullptr; 2664 localSymbols.clear(); 2665 } 2666 /// Instantiate the data from a BLOCK DATA unit. 2667 void lowerBlockData(Fortran::lower::pft::BlockDataUnit &bdunit) { 2668 createGlobalOutsideOfFunctionLowering([&]() { 2669 Fortran::lower::AggregateStoreMap fakeMap; 2670 for (const auto &[_, sym] : bdunit.symTab) { 2671 if (sym->has<Fortran::semantics::ObjectEntityDetails>()) { 2672 Fortran::lower::pft::Variable var(*sym, true); 2673 instantiateVar(var, fakeMap); 2674 } 2675 } 2676 }); 2677 } 2678 2679 /// Create fir::Global for all the common blocks that appear in the program. 2680 void 2681 lowerCommonBlocks(const Fortran::semantics::CommonBlockList &commonBlocks) { 2682 createGlobalOutsideOfFunctionLowering( 2683 [&]() { Fortran::lower::defineCommonBlocks(*this, commonBlocks); }); 2684 } 2685 2686 /// Lower a procedure (nest). 2687 void lowerFunc(Fortran::lower::pft::FunctionLikeUnit &funit) { 2688 if (!funit.isMainProgram()) { 2689 const Fortran::semantics::Symbol &procSymbol = 2690 funit.getSubprogramSymbol(); 2691 if (procSymbol.owner().IsSubmodule()) { 2692 TODO(toLocation(), "support submodules"); 2693 return; 2694 } 2695 } 2696 setCurrentPosition(funit.getStartingSourceLoc()); 2697 for (int entryIndex = 0, last = funit.entryPointList.size(); 2698 entryIndex < last; ++entryIndex) { 2699 funit.setActiveEntry(entryIndex); 2700 startNewFunction(funit); // the entry point for lowering this procedure 2701 for (Fortran::lower::pft::Evaluation &eval : funit.evaluationList) 2702 genFIR(eval); 2703 endNewFunction(funit); 2704 } 2705 funit.setActiveEntry(0); 2706 for (Fortran::lower::pft::FunctionLikeUnit &f : funit.nestedFunctions) 2707 lowerFunc(f); // internal procedure 2708 } 2709 2710 /// Lower module variable definitions to fir::globalOp and OpenMP/OpenACC 2711 /// declarative construct. 2712 void lowerModuleDeclScope(Fortran::lower::pft::ModuleLikeUnit &mod) { 2713 setCurrentPosition(mod.getStartingSourceLoc()); 2714 createGlobalOutsideOfFunctionLowering([&]() { 2715 for (const Fortran::lower::pft::Variable &var : 2716 mod.getOrderedSymbolTable()) { 2717 // Only define the variables owned by this module. 2718 const Fortran::semantics::Scope *owningScope = var.getOwningScope(); 2719 if (!owningScope || mod.getScope() == *owningScope) 2720 Fortran::lower::defineModuleVariable(*this, var); 2721 } 2722 for (auto &eval : mod.evaluationList) 2723 genFIR(eval); 2724 }); 2725 } 2726 2727 /// Lower functions contained in a module. 2728 void lowerMod(Fortran::lower::pft::ModuleLikeUnit &mod) { 2729 for (Fortran::lower::pft::FunctionLikeUnit &f : mod.nestedFunctions) 2730 lowerFunc(f); 2731 } 2732 2733 void setCurrentPosition(const Fortran::parser::CharBlock &position) { 2734 if (position != Fortran::parser::CharBlock{}) 2735 currentPosition = position; 2736 } 2737 2738 /// Set current position at the location of \p parseTreeNode. Note that the 2739 /// position is updated automatically when visiting statements, but not when 2740 /// entering higher level nodes like constructs or procedures. This helper is 2741 /// intended to cover the latter cases. 2742 template <typename A> 2743 void setCurrentPositionAt(const A &parseTreeNode) { 2744 setCurrentPosition(Fortran::parser::FindSourceLocation(parseTreeNode)); 2745 } 2746 2747 //===--------------------------------------------------------------------===// 2748 // Utility methods 2749 //===--------------------------------------------------------------------===// 2750 2751 /// Convert a parser CharBlock to a Location 2752 mlir::Location toLocation(const Fortran::parser::CharBlock &cb) { 2753 return genLocation(cb); 2754 } 2755 2756 mlir::Location toLocation() { return toLocation(currentPosition); } 2757 void setCurrentEval(Fortran::lower::pft::Evaluation &eval) { 2758 evalPtr = &eval; 2759 } 2760 Fortran::lower::pft::Evaluation &getEval() { 2761 assert(evalPtr); 2762 return *evalPtr; 2763 } 2764 2765 std::optional<Fortran::evaluate::Shape> 2766 getShape(const Fortran::lower::SomeExpr &expr) { 2767 return Fortran::evaluate::GetShape(foldingContext, expr); 2768 } 2769 2770 //===--------------------------------------------------------------------===// 2771 // Analysis on a nested explicit iteration space. 2772 //===--------------------------------------------------------------------===// 2773 2774 void analyzeExplicitSpace(const Fortran::parser::ConcurrentHeader &header) { 2775 explicitIterSpace.pushLevel(); 2776 for (const Fortran::parser::ConcurrentControl &ctrl : 2777 std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t)) { 2778 const Fortran::semantics::Symbol *ctrlVar = 2779 std::get<Fortran::parser::Name>(ctrl.t).symbol; 2780 explicitIterSpace.addSymbol(ctrlVar); 2781 } 2782 if (const auto &mask = 2783 std::get<std::optional<Fortran::parser::ScalarLogicalExpr>>( 2784 header.t); 2785 mask.has_value()) 2786 analyzeExplicitSpace(*Fortran::semantics::GetExpr(*mask)); 2787 } 2788 template <bool LHS = false, typename A> 2789 void analyzeExplicitSpace(const Fortran::evaluate::Expr<A> &e) { 2790 explicitIterSpace.exprBase(&e, LHS); 2791 } 2792 void analyzeExplicitSpace(const Fortran::evaluate::Assignment *assign) { 2793 auto analyzeAssign = [&](const Fortran::lower::SomeExpr &lhs, 2794 const Fortran::lower::SomeExpr &rhs) { 2795 analyzeExplicitSpace</*LHS=*/true>(lhs); 2796 analyzeExplicitSpace(rhs); 2797 }; 2798 std::visit( 2799 Fortran::common::visitors{ 2800 [&](const Fortran::evaluate::ProcedureRef &procRef) { 2801 // Ensure the procRef expressions are the one being visited. 2802 assert(procRef.arguments().size() == 2); 2803 const Fortran::lower::SomeExpr *lhs = 2804 procRef.arguments()[0].value().UnwrapExpr(); 2805 const Fortran::lower::SomeExpr *rhs = 2806 procRef.arguments()[1].value().UnwrapExpr(); 2807 assert(lhs && rhs && 2808 "user defined assignment arguments must be expressions"); 2809 analyzeAssign(*lhs, *rhs); 2810 }, 2811 [&](const auto &) { analyzeAssign(assign->lhs, assign->rhs); }}, 2812 assign->u); 2813 explicitIterSpace.endAssign(); 2814 } 2815 void analyzeExplicitSpace(const Fortran::parser::ForallAssignmentStmt &stmt) { 2816 std::visit([&](const auto &s) { analyzeExplicitSpace(s); }, stmt.u); 2817 } 2818 void analyzeExplicitSpace(const Fortran::parser::AssignmentStmt &s) { 2819 analyzeExplicitSpace(s.typedAssignment->v.operator->()); 2820 } 2821 void analyzeExplicitSpace(const Fortran::parser::PointerAssignmentStmt &s) { 2822 analyzeExplicitSpace(s.typedAssignment->v.operator->()); 2823 } 2824 void analyzeExplicitSpace(const Fortran::parser::WhereConstruct &c) { 2825 analyzeExplicitSpace( 2826 std::get< 2827 Fortran::parser::Statement<Fortran::parser::WhereConstructStmt>>( 2828 c.t) 2829 .statement); 2830 for (const Fortran::parser::WhereBodyConstruct &body : 2831 std::get<std::list<Fortran::parser::WhereBodyConstruct>>(c.t)) 2832 analyzeExplicitSpace(body); 2833 for (const Fortran::parser::WhereConstruct::MaskedElsewhere &e : 2834 std::get<std::list<Fortran::parser::WhereConstruct::MaskedElsewhere>>( 2835 c.t)) 2836 analyzeExplicitSpace(e); 2837 if (const auto &e = 2838 std::get<std::optional<Fortran::parser::WhereConstruct::Elsewhere>>( 2839 c.t); 2840 e.has_value()) 2841 analyzeExplicitSpace(e.operator->()); 2842 } 2843 void analyzeExplicitSpace(const Fortran::parser::WhereConstructStmt &ws) { 2844 const Fortran::lower::SomeExpr *exp = Fortran::semantics::GetExpr( 2845 std::get<Fortran::parser::LogicalExpr>(ws.t)); 2846 addMaskVariable(exp); 2847 analyzeExplicitSpace(*exp); 2848 } 2849 void analyzeExplicitSpace( 2850 const Fortran::parser::WhereConstruct::MaskedElsewhere &ew) { 2851 analyzeExplicitSpace( 2852 std::get< 2853 Fortran::parser::Statement<Fortran::parser::MaskedElsewhereStmt>>( 2854 ew.t) 2855 .statement); 2856 for (const Fortran::parser::WhereBodyConstruct &e : 2857 std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew.t)) 2858 analyzeExplicitSpace(e); 2859 } 2860 void analyzeExplicitSpace(const Fortran::parser::WhereBodyConstruct &body) { 2861 std::visit(Fortran::common::visitors{ 2862 [&](const Fortran::common::Indirection< 2863 Fortran::parser::WhereConstruct> &wc) { 2864 analyzeExplicitSpace(wc.value()); 2865 }, 2866 [&](const auto &s) { analyzeExplicitSpace(s.statement); }}, 2867 body.u); 2868 } 2869 void analyzeExplicitSpace(const Fortran::parser::MaskedElsewhereStmt &stmt) { 2870 const Fortran::lower::SomeExpr *exp = Fortran::semantics::GetExpr( 2871 std::get<Fortran::parser::LogicalExpr>(stmt.t)); 2872 addMaskVariable(exp); 2873 analyzeExplicitSpace(*exp); 2874 } 2875 void 2876 analyzeExplicitSpace(const Fortran::parser::WhereConstruct::Elsewhere *ew) { 2877 for (const Fortran::parser::WhereBodyConstruct &e : 2878 std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew->t)) 2879 analyzeExplicitSpace(e); 2880 } 2881 void analyzeExplicitSpace(const Fortran::parser::WhereStmt &stmt) { 2882 const Fortran::lower::SomeExpr *exp = Fortran::semantics::GetExpr( 2883 std::get<Fortran::parser::LogicalExpr>(stmt.t)); 2884 addMaskVariable(exp); 2885 analyzeExplicitSpace(*exp); 2886 const std::optional<Fortran::evaluate::Assignment> &assign = 2887 std::get<Fortran::parser::AssignmentStmt>(stmt.t).typedAssignment->v; 2888 assert(assign.has_value() && "WHERE has no statement"); 2889 analyzeExplicitSpace(assign.operator->()); 2890 } 2891 void analyzeExplicitSpace(const Fortran::parser::ForallStmt &forall) { 2892 analyzeExplicitSpace( 2893 std::get< 2894 Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>( 2895 forall.t) 2896 .value()); 2897 analyzeExplicitSpace(std::get<Fortran::parser::UnlabeledStatement< 2898 Fortran::parser::ForallAssignmentStmt>>(forall.t) 2899 .statement); 2900 analyzeExplicitSpacePop(); 2901 } 2902 void 2903 analyzeExplicitSpace(const Fortran::parser::ForallConstructStmt &forall) { 2904 analyzeExplicitSpace( 2905 std::get< 2906 Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>( 2907 forall.t) 2908 .value()); 2909 } 2910 void analyzeExplicitSpace(const Fortran::parser::ForallConstruct &forall) { 2911 analyzeExplicitSpace( 2912 std::get< 2913 Fortran::parser::Statement<Fortran::parser::ForallConstructStmt>>( 2914 forall.t) 2915 .statement); 2916 for (const Fortran::parser::ForallBodyConstruct &s : 2917 std::get<std::list<Fortran::parser::ForallBodyConstruct>>(forall.t)) { 2918 std::visit(Fortran::common::visitors{ 2919 [&](const Fortran::common::Indirection< 2920 Fortran::parser::ForallConstruct> &b) { 2921 analyzeExplicitSpace(b.value()); 2922 }, 2923 [&](const Fortran::parser::WhereConstruct &w) { 2924 analyzeExplicitSpace(w); 2925 }, 2926 [&](const auto &b) { analyzeExplicitSpace(b.statement); }}, 2927 s.u); 2928 } 2929 analyzeExplicitSpacePop(); 2930 } 2931 2932 void analyzeExplicitSpacePop() { explicitIterSpace.popLevel(); } 2933 2934 void addMaskVariable(Fortran::lower::FrontEndExpr exp) { 2935 // Note: use i8 to store bool values. This avoids round-down behavior found 2936 // with sequences of i1. That is, an array of i1 will be truncated in size 2937 // and be too small. For example, a buffer of type fir.array<7xi1> will have 2938 // 0 size. 2939 mlir::Type i64Ty = builder->getIntegerType(64); 2940 mlir::TupleType ty = fir::factory::getRaggedArrayHeaderType(*builder); 2941 mlir::Type buffTy = ty.getType(1); 2942 mlir::Type shTy = ty.getType(2); 2943 mlir::Location loc = toLocation(); 2944 mlir::Value hdr = builder->createTemporary(loc, ty); 2945 // FIXME: Is there a way to create a `zeroinitializer` in LLVM-IR dialect? 2946 // For now, explicitly set lazy ragged header to all zeros. 2947 // auto nilTup = builder->createNullConstant(loc, ty); 2948 // builder->create<fir::StoreOp>(loc, nilTup, hdr); 2949 mlir::Type i32Ty = builder->getIntegerType(32); 2950 mlir::Value zero = builder->createIntegerConstant(loc, i32Ty, 0); 2951 mlir::Value zero64 = builder->createIntegerConstant(loc, i64Ty, 0); 2952 mlir::Value flags = builder->create<fir::CoordinateOp>( 2953 loc, builder->getRefType(i64Ty), hdr, zero); 2954 builder->create<fir::StoreOp>(loc, zero64, flags); 2955 mlir::Value one = builder->createIntegerConstant(loc, i32Ty, 1); 2956 mlir::Value nullPtr1 = builder->createNullConstant(loc, buffTy); 2957 mlir::Value var = builder->create<fir::CoordinateOp>( 2958 loc, builder->getRefType(buffTy), hdr, one); 2959 builder->create<fir::StoreOp>(loc, nullPtr1, var); 2960 mlir::Value two = builder->createIntegerConstant(loc, i32Ty, 2); 2961 mlir::Value nullPtr2 = builder->createNullConstant(loc, shTy); 2962 mlir::Value shape = builder->create<fir::CoordinateOp>( 2963 loc, builder->getRefType(shTy), hdr, two); 2964 builder->create<fir::StoreOp>(loc, nullPtr2, shape); 2965 implicitIterSpace.addMaskVariable(exp, var, shape, hdr); 2966 explicitIterSpace.outermostContext().attachCleanup( 2967 [builder = this->builder, hdr, loc]() { 2968 fir::runtime::genRaggedArrayDeallocate(loc, *builder, hdr); 2969 }); 2970 } 2971 2972 void createRuntimeTypeInfoGlobals() {} 2973 2974 //===--------------------------------------------------------------------===// 2975 2976 Fortran::lower::LoweringBridge &bridge; 2977 Fortran::evaluate::FoldingContext foldingContext; 2978 fir::FirOpBuilder *builder = nullptr; 2979 Fortran::lower::pft::Evaluation *evalPtr = nullptr; 2980 Fortran::lower::SymMap localSymbols; 2981 Fortran::parser::CharBlock currentPosition; 2982 RuntimeTypeInfoConverter runtimeTypeInfoConverter; 2983 2984 /// WHERE statement/construct mask expression stack. 2985 Fortran::lower::ImplicitIterSpace implicitIterSpace; 2986 2987 /// FORALL context 2988 Fortran::lower::ExplicitIterSpace explicitIterSpace; 2989 2990 /// Tuple of host assoicated variables. 2991 mlir::Value hostAssocTuple; 2992 }; 2993 2994 } // namespace 2995 2996 Fortran::evaluate::FoldingContext 2997 Fortran::lower::LoweringBridge::createFoldingContext() const { 2998 return {getDefaultKinds(), getIntrinsicTable()}; 2999 } 3000 3001 void Fortran::lower::LoweringBridge::lower( 3002 const Fortran::parser::Program &prg, 3003 const Fortran::semantics::SemanticsContext &semanticsContext) { 3004 std::unique_ptr<Fortran::lower::pft::Program> pft = 3005 Fortran::lower::createPFT(prg, semanticsContext); 3006 if (dumpBeforeFir) 3007 Fortran::lower::dumpPFT(llvm::errs(), *pft); 3008 FirConverter converter{*this}; 3009 converter.run(*pft); 3010 } 3011 3012 void Fortran::lower::LoweringBridge::parseSourceFile(llvm::SourceMgr &srcMgr) { 3013 mlir::OwningOpRef<mlir::ModuleOp> owningRef = 3014 mlir::parseSourceFile<mlir::ModuleOp>(srcMgr, &context); 3015 module.reset(new mlir::ModuleOp(owningRef.get().getOperation())); 3016 owningRef.release(); 3017 } 3018 3019 Fortran::lower::LoweringBridge::LoweringBridge( 3020 mlir::MLIRContext &context, 3021 const Fortran::common::IntrinsicTypeDefaultKinds &defaultKinds, 3022 const Fortran::evaluate::IntrinsicProcTable &intrinsics, 3023 const Fortran::parser::AllCookedSources &cooked, llvm::StringRef triple, 3024 fir::KindMapping &kindMap) 3025 : defaultKinds{defaultKinds}, intrinsics{intrinsics}, cooked{&cooked}, 3026 context{context}, kindMap{kindMap} { 3027 // Register the diagnostic handler. 3028 context.getDiagEngine().registerHandler([](mlir::Diagnostic &diag) { 3029 llvm::raw_ostream &os = llvm::errs(); 3030 switch (diag.getSeverity()) { 3031 case mlir::DiagnosticSeverity::Error: 3032 os << "error: "; 3033 break; 3034 case mlir::DiagnosticSeverity::Remark: 3035 os << "info: "; 3036 break; 3037 case mlir::DiagnosticSeverity::Warning: 3038 os << "warning: "; 3039 break; 3040 default: 3041 break; 3042 } 3043 if (!diag.getLocation().isa<mlir::UnknownLoc>()) 3044 os << diag.getLocation() << ": "; 3045 os << diag << '\n'; 3046 os.flush(); 3047 return mlir::success(); 3048 }); 3049 3050 // Create the module and attach the attributes. 3051 module = std::make_unique<mlir::ModuleOp>( 3052 mlir::ModuleOp::create(mlir::UnknownLoc::get(&context))); 3053 assert(module.get() && "module was not created"); 3054 fir::setTargetTriple(*module.get(), triple); 3055 fir::setKindMapping(*module.get(), kindMap); 3056 } 3057