1 //===-- OpenMP.cpp -- Open MP directive lowering --------------------------===// 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/OpenMP.h" 14 #include "flang/Common/idioms.h" 15 #include "flang/Lower/Bridge.h" 16 #include "flang/Lower/ConvertExpr.h" 17 #include "flang/Lower/PFTBuilder.h" 18 #include "flang/Lower/StatementContext.h" 19 #include "flang/Lower/Todo.h" 20 #include "flang/Optimizer/Builder/BoxValue.h" 21 #include "flang/Optimizer/Builder/FIRBuilder.h" 22 #include "flang/Parser/parse-tree.h" 23 #include "flang/Semantics/tools.h" 24 #include "mlir/Dialect/OpenMP/OpenMPDialect.h" 25 #include "llvm/Frontend/OpenMP/OMPConstants.h" 26 27 using namespace mlir; 28 29 int64_t Fortran::lower::getCollapseValue( 30 const Fortran::parser::OmpClauseList &clauseList) { 31 for (const auto &clause : clauseList.v) { 32 if (const auto &collapseClause = 33 std::get_if<Fortran::parser::OmpClause::Collapse>(&clause.u)) { 34 const auto *expr = Fortran::semantics::GetExpr(collapseClause->v); 35 return Fortran::evaluate::ToInt64(*expr).value(); 36 } 37 } 38 return 1; 39 } 40 41 static const Fortran::parser::Name * 42 getDesignatorNameIfDataRef(const Fortran::parser::Designator &designator) { 43 const auto *dataRef = std::get_if<Fortran::parser::DataRef>(&designator.u); 44 return dataRef ? std::get_if<Fortran::parser::Name>(&dataRef->u) : nullptr; 45 } 46 47 static Fortran::semantics::Symbol * 48 getOmpObjectSymbol(const Fortran::parser::OmpObject &ompObject) { 49 Fortran::semantics::Symbol *sym = nullptr; 50 std::visit(Fortran::common::visitors{ 51 [&](const Fortran::parser::Designator &designator) { 52 if (const Fortran::parser::Name *name = 53 getDesignatorNameIfDataRef(designator)) { 54 sym = name->symbol; 55 } 56 }, 57 [&](const Fortran::parser::Name &name) { sym = name.symbol; }}, 58 ompObject.u); 59 return sym; 60 } 61 62 template <typename T> 63 static void createPrivateVarSyms(Fortran::lower::AbstractConverter &converter, 64 const T *clause) { 65 const Fortran::parser::OmpObjectList &ompObjectList = clause->v; 66 for (const Fortran::parser::OmpObject &ompObject : ompObjectList.v) { 67 Fortran::semantics::Symbol *sym = getOmpObjectSymbol(ompObject); 68 // Privatization for symbols which are pre-determined (like loop index 69 // variables) happen separately, for everything else privatize here 70 if constexpr (std::is_same_v<T, Fortran::parser::OmpClause::Firstprivate>) { 71 converter.copyHostAssociateVar(*sym); 72 } else { 73 bool success = converter.createHostAssociateVarClone(*sym); 74 (void)success; 75 assert(success && "Privatization failed due to existing binding"); 76 } 77 } 78 } 79 80 static void privatizeVars(Fortran::lower::AbstractConverter &converter, 81 const Fortran::parser::OmpClauseList &opClauseList) { 82 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder(); 83 auto insPt = firOpBuilder.saveInsertionPoint(); 84 firOpBuilder.setInsertionPointToStart(firOpBuilder.getAllocaBlock()); 85 for (const Fortran::parser::OmpClause &clause : opClauseList.v) { 86 if (const auto &privateClause = 87 std::get_if<Fortran::parser::OmpClause::Private>(&clause.u)) { 88 createPrivateVarSyms(converter, privateClause); 89 } else if (const auto &firstPrivateClause = 90 std::get_if<Fortran::parser::OmpClause::Firstprivate>( 91 &clause.u)) { 92 createPrivateVarSyms(converter, firstPrivateClause); 93 } 94 } 95 firOpBuilder.restoreInsertionPoint(insPt); 96 } 97 98 /// The COMMON block is a global structure. \p commonValue is the base address 99 /// of the the COMMON block. As the offset from the symbol \p sym, generate the 100 /// COMMON block member value (commonValue + offset) for the symbol. 101 /// FIXME: Share the code with `instantiateCommon` in ConvertVariable.cpp. 102 static mlir::Value 103 genCommonBlockMember(Fortran::lower::AbstractConverter &converter, 104 const Fortran::semantics::Symbol &sym, 105 mlir::Value commonValue) { 106 auto &firOpBuilder = converter.getFirOpBuilder(); 107 mlir::Location currentLocation = converter.getCurrentLocation(); 108 mlir::IntegerType i8Ty = firOpBuilder.getIntegerType(8); 109 mlir::Type i8Ptr = firOpBuilder.getRefType(i8Ty); 110 mlir::Type seqTy = firOpBuilder.getRefType(firOpBuilder.getVarLenSeqTy(i8Ty)); 111 mlir::Value base = 112 firOpBuilder.createConvert(currentLocation, seqTy, commonValue); 113 std::size_t byteOffset = sym.GetUltimate().offset(); 114 mlir::Value offs = firOpBuilder.createIntegerConstant( 115 currentLocation, firOpBuilder.getIndexType(), byteOffset); 116 mlir::Value varAddr = firOpBuilder.create<fir::CoordinateOp>( 117 currentLocation, i8Ptr, base, mlir::ValueRange{offs}); 118 mlir::Type symType = converter.genType(sym); 119 return firOpBuilder.createConvert(currentLocation, 120 firOpBuilder.getRefType(symType), varAddr); 121 } 122 123 // Get the extended value for \p val by extracting additional variable 124 // information from \p base. 125 static fir::ExtendedValue getExtendedValue(fir::ExtendedValue base, 126 mlir::Value val) { 127 return base.match( 128 [&](const fir::MutableBoxValue &box) -> fir::ExtendedValue { 129 return fir::MutableBoxValue(val, box.nonDeferredLenParams(), {}); 130 }, 131 [&](const auto &) -> fir::ExtendedValue { 132 return fir::substBase(base, val); 133 }); 134 } 135 136 static void threadPrivatizeVars(Fortran::lower::AbstractConverter &converter, 137 Fortran::lower::pft::Evaluation &eval) { 138 auto &firOpBuilder = converter.getFirOpBuilder(); 139 mlir::Location currentLocation = converter.getCurrentLocation(); 140 auto insPt = firOpBuilder.saveInsertionPoint(); 141 firOpBuilder.setInsertionPointToStart(firOpBuilder.getAllocaBlock()); 142 143 // Get the original ThreadprivateOp corresponding to the symbol and use the 144 // symbol value from that opeartion to create one ThreadprivateOp copy 145 // operation inside the parallel region. 146 auto genThreadprivateOp = [&](Fortran::lower::SymbolRef sym) -> mlir::Value { 147 mlir::Value symOriThreadprivateValue = converter.getSymbolAddress(sym); 148 mlir::Operation *op = symOriThreadprivateValue.getDefiningOp(); 149 assert(mlir::isa<mlir::omp::ThreadprivateOp>(op) && 150 "The threadprivate operation not created"); 151 mlir::Value symValue = 152 mlir::dyn_cast<mlir::omp::ThreadprivateOp>(op).sym_addr(); 153 return firOpBuilder.create<mlir::omp::ThreadprivateOp>( 154 currentLocation, symValue.getType(), symValue); 155 }; 156 157 llvm::SetVector<const Fortran::semantics::Symbol *> threadprivateSyms; 158 converter.collectSymbolSet( 159 eval, threadprivateSyms, 160 Fortran::semantics::Symbol::Flag::OmpThreadprivate); 161 162 // For a COMMON block, the ThreadprivateOp is generated for itself instead of 163 // its members, so only bind the value of the new copied ThreadprivateOp 164 // inside the parallel region to the common block symbol only once for 165 // multiple members in one COMMON block. 166 llvm::SetVector<const Fortran::semantics::Symbol *> commonSyms; 167 for (std::size_t i = 0; i < threadprivateSyms.size(); i++) { 168 auto sym = threadprivateSyms[i]; 169 mlir::Value symThreadprivateValue; 170 if (const Fortran::semantics::Symbol *common = 171 Fortran::semantics::FindCommonBlockContaining(sym->GetUltimate())) { 172 mlir::Value commonThreadprivateValue; 173 if (commonSyms.contains(common)) { 174 commonThreadprivateValue = converter.getSymbolAddress(*common); 175 } else { 176 commonThreadprivateValue = genThreadprivateOp(*common); 177 converter.bindSymbol(*common, commonThreadprivateValue); 178 commonSyms.insert(common); 179 } 180 symThreadprivateValue = 181 genCommonBlockMember(converter, *sym, commonThreadprivateValue); 182 } else { 183 symThreadprivateValue = genThreadprivateOp(*sym); 184 } 185 186 fir::ExtendedValue sexv = converter.getSymbolExtendedValue(*sym); 187 fir::ExtendedValue symThreadprivateExv = 188 getExtendedValue(sexv, symThreadprivateValue); 189 converter.bindSymbol(*sym, symThreadprivateExv); 190 } 191 192 firOpBuilder.restoreInsertionPoint(insPt); 193 } 194 195 static void genObjectList(const Fortran::parser::OmpObjectList &objectList, 196 Fortran::lower::AbstractConverter &converter, 197 llvm::SmallVectorImpl<Value> &operands) { 198 auto addOperands = [&](Fortran::lower::SymbolRef sym) { 199 const mlir::Value variable = converter.getSymbolAddress(sym); 200 if (variable) { 201 operands.push_back(variable); 202 } else { 203 if (const auto *details = 204 sym->detailsIf<Fortran::semantics::HostAssocDetails>()) { 205 operands.push_back(converter.getSymbolAddress(details->symbol())); 206 converter.copySymbolBinding(details->symbol(), sym); 207 } 208 } 209 }; 210 for (const Fortran::parser::OmpObject &ompObject : objectList.v) { 211 Fortran::semantics::Symbol *sym = getOmpObjectSymbol(ompObject); 212 addOperands(*sym); 213 } 214 } 215 216 static mlir::Type getLoopVarType(Fortran::lower::AbstractConverter &converter, 217 std::size_t loopVarTypeSize) { 218 // OpenMP runtime requires 32-bit or 64-bit loop variables. 219 loopVarTypeSize = loopVarTypeSize * 8; 220 if (loopVarTypeSize < 32) { 221 loopVarTypeSize = 32; 222 } else if (loopVarTypeSize > 64) { 223 loopVarTypeSize = 64; 224 mlir::emitWarning(converter.getCurrentLocation(), 225 "OpenMP loop iteration variable cannot have more than 64 " 226 "bits size and will be narrowed into 64 bits."); 227 } 228 assert((loopVarTypeSize == 32 || loopVarTypeSize == 64) && 229 "OpenMP loop iteration variable size must be transformed into 32-bit " 230 "or 64-bit"); 231 return converter.getFirOpBuilder().getIntegerType(loopVarTypeSize); 232 } 233 234 /// Create empty blocks for the current region. 235 /// These blocks replace blocks parented to an enclosing region. 236 void createEmptyRegionBlocks( 237 fir::FirOpBuilder &firOpBuilder, 238 std::list<Fortran::lower::pft::Evaluation> &evaluationList) { 239 auto *region = &firOpBuilder.getRegion(); 240 for (auto &eval : evaluationList) { 241 if (eval.block) { 242 if (eval.block->empty()) { 243 eval.block->erase(); 244 eval.block = firOpBuilder.createBlock(region); 245 } else { 246 [[maybe_unused]] auto &terminatorOp = eval.block->back(); 247 assert((mlir::isa<mlir::omp::TerminatorOp>(terminatorOp) || 248 mlir::isa<mlir::omp::YieldOp>(terminatorOp)) && 249 "expected terminator op"); 250 } 251 } 252 if (!eval.isDirective() && eval.hasNestedEvaluations()) 253 createEmptyRegionBlocks(firOpBuilder, eval.getNestedEvaluations()); 254 } 255 } 256 257 /// Create the body (block) for an OpenMP Operation. 258 /// 259 /// \param [in] op - the operation the body belongs to. 260 /// \param [inout] converter - converter to use for the clauses. 261 /// \param [in] loc - location in source code. 262 /// \param [in] eval - current PFT node/evaluation. 263 /// \oaran [in] clauses - list of clauses to process. 264 /// \param [in] args - block arguments (induction variable[s]) for the 265 //// region. 266 /// \param [in] outerCombined - is this an outer operation - prevents 267 /// privatization. 268 template <typename Op> 269 static void 270 createBodyOfOp(Op &op, Fortran::lower::AbstractConverter &converter, 271 mlir::Location &loc, Fortran::lower::pft::Evaluation &eval, 272 const Fortran::parser::OmpClauseList *clauses = nullptr, 273 const SmallVector<const Fortran::semantics::Symbol *> &args = {}, 274 bool outerCombined = false) { 275 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder(); 276 // If an argument for the region is provided then create the block with that 277 // argument. Also update the symbol's address with the mlir argument value. 278 // e.g. For loops the argument is the induction variable. And all further 279 // uses of the induction variable should use this mlir value. 280 mlir::Operation *storeOp = nullptr; 281 if (args.size()) { 282 std::size_t loopVarTypeSize = 0; 283 for (const Fortran::semantics::Symbol *arg : args) 284 loopVarTypeSize = std::max(loopVarTypeSize, arg->GetUltimate().size()); 285 mlir::Type loopVarType = getLoopVarType(converter, loopVarTypeSize); 286 SmallVector<Type> tiv; 287 SmallVector<Location> locs; 288 for (int i = 0; i < (int)args.size(); i++) { 289 tiv.push_back(loopVarType); 290 locs.push_back(loc); 291 } 292 firOpBuilder.createBlock(&op.getRegion(), {}, tiv, locs); 293 int argIndex = 0; 294 // The argument is not currently in memory, so make a temporary for the 295 // argument, and store it there, then bind that location to the argument. 296 for (const Fortran::semantics::Symbol *arg : args) { 297 mlir::Value val = 298 fir::getBase(op.getRegion().front().getArgument(argIndex)); 299 mlir::Value temp = firOpBuilder.createTemporary( 300 loc, loopVarType, 301 llvm::ArrayRef<mlir::NamedAttribute>{ 302 Fortran::lower::getAdaptToByRefAttr(firOpBuilder)}); 303 storeOp = firOpBuilder.create<fir::StoreOp>(loc, val, temp); 304 converter.bindSymbol(*arg, temp); 305 argIndex++; 306 } 307 } else { 308 firOpBuilder.createBlock(&op.getRegion()); 309 } 310 // Set the insert for the terminator operation to go at the end of the 311 // block - this is either empty or the block with the stores above, 312 // the end of the block works for both. 313 mlir::Block &block = op.getRegion().back(); 314 firOpBuilder.setInsertionPointToEnd(&block); 315 316 // If it is an unstructured region and is not the outer region of a combined 317 // construct, create empty blocks for all evaluations. 318 if (eval.lowerAsUnstructured() && !outerCombined) 319 createEmptyRegionBlocks(firOpBuilder, eval.getNestedEvaluations()); 320 321 // Insert the terminator. 322 if constexpr (std::is_same_v<Op, omp::WsLoopOp>) { 323 mlir::ValueRange results; 324 firOpBuilder.create<mlir::omp::YieldOp>(loc, results); 325 } else { 326 firOpBuilder.create<mlir::omp::TerminatorOp>(loc); 327 } 328 329 // Reset the insert point to before the terminator. 330 if (storeOp) 331 firOpBuilder.setInsertionPointAfter(storeOp); 332 else 333 firOpBuilder.setInsertionPointToStart(&block); 334 335 // Handle privatization. Do not privatize if this is the outer operation. 336 if (clauses && !outerCombined) 337 privatizeVars(converter, *clauses); 338 339 if (std::is_same_v<Op, omp::ParallelOp>) 340 threadPrivatizeVars(converter, eval); 341 } 342 343 static void genOMP(Fortran::lower::AbstractConverter &converter, 344 Fortran::lower::pft::Evaluation &eval, 345 const Fortran::parser::OpenMPSimpleStandaloneConstruct 346 &simpleStandaloneConstruct) { 347 const auto &directive = 348 std::get<Fortran::parser::OmpSimpleStandaloneDirective>( 349 simpleStandaloneConstruct.t); 350 switch (directive.v) { 351 default: 352 break; 353 case llvm::omp::Directive::OMPD_barrier: 354 converter.getFirOpBuilder().create<mlir::omp::BarrierOp>( 355 converter.getCurrentLocation()); 356 break; 357 case llvm::omp::Directive::OMPD_taskwait: 358 converter.getFirOpBuilder().create<mlir::omp::TaskwaitOp>( 359 converter.getCurrentLocation()); 360 break; 361 case llvm::omp::Directive::OMPD_taskyield: 362 converter.getFirOpBuilder().create<mlir::omp::TaskyieldOp>( 363 converter.getCurrentLocation()); 364 break; 365 case llvm::omp::Directive::OMPD_target_enter_data: 366 TODO(converter.getCurrentLocation(), "OMPD_target_enter_data"); 367 case llvm::omp::Directive::OMPD_target_exit_data: 368 TODO(converter.getCurrentLocation(), "OMPD_target_exit_data"); 369 case llvm::omp::Directive::OMPD_target_update: 370 TODO(converter.getCurrentLocation(), "OMPD_target_update"); 371 case llvm::omp::Directive::OMPD_ordered: 372 TODO(converter.getCurrentLocation(), "OMPD_ordered"); 373 } 374 } 375 376 static void 377 genAllocateClause(Fortran::lower::AbstractConverter &converter, 378 const Fortran::parser::OmpAllocateClause &ompAllocateClause, 379 SmallVector<Value> &allocatorOperands, 380 SmallVector<Value> &allocateOperands) { 381 auto &firOpBuilder = converter.getFirOpBuilder(); 382 auto currentLocation = converter.getCurrentLocation(); 383 Fortran::lower::StatementContext stmtCtx; 384 385 mlir::Value allocatorOperand; 386 const Fortran::parser::OmpObjectList &ompObjectList = 387 std::get<Fortran::parser::OmpObjectList>(ompAllocateClause.t); 388 const auto &allocatorValue = 389 std::get<std::optional<Fortran::parser::OmpAllocateClause::Allocator>>( 390 ompAllocateClause.t); 391 // Check if allocate clause has allocator specified. If so, add it 392 // to list of allocators, otherwise, add default allocator to 393 // list of allocators. 394 if (allocatorValue) { 395 allocatorOperand = fir::getBase(converter.genExprValue( 396 *Fortran::semantics::GetExpr(allocatorValue->v), stmtCtx)); 397 allocatorOperands.insert(allocatorOperands.end(), ompObjectList.v.size(), 398 allocatorOperand); 399 } else { 400 allocatorOperand = firOpBuilder.createIntegerConstant( 401 currentLocation, firOpBuilder.getI32Type(), 1); 402 allocatorOperands.insert(allocatorOperands.end(), ompObjectList.v.size(), 403 allocatorOperand); 404 } 405 genObjectList(ompObjectList, converter, allocateOperands); 406 } 407 408 static void 409 genOMP(Fortran::lower::AbstractConverter &converter, 410 Fortran::lower::pft::Evaluation &eval, 411 const Fortran::parser::OpenMPStandaloneConstruct &standaloneConstruct) { 412 std::visit( 413 Fortran::common::visitors{ 414 [&](const Fortran::parser::OpenMPSimpleStandaloneConstruct 415 &simpleStandaloneConstruct) { 416 genOMP(converter, eval, simpleStandaloneConstruct); 417 }, 418 [&](const Fortran::parser::OpenMPFlushConstruct &flushConstruct) { 419 SmallVector<Value, 4> operandRange; 420 if (const auto &ompObjectList = 421 std::get<std::optional<Fortran::parser::OmpObjectList>>( 422 flushConstruct.t)) 423 genObjectList(*ompObjectList, converter, operandRange); 424 const auto &memOrderClause = std::get<std::optional< 425 std::list<Fortran::parser::OmpMemoryOrderClause>>>( 426 flushConstruct.t); 427 if (memOrderClause.has_value() && memOrderClause->size() > 0) 428 TODO(converter.getCurrentLocation(), 429 "Handle OmpMemoryOrderClause"); 430 converter.getFirOpBuilder().create<mlir::omp::FlushOp>( 431 converter.getCurrentLocation(), operandRange); 432 }, 433 [&](const Fortran::parser::OpenMPCancelConstruct &cancelConstruct) { 434 TODO(converter.getCurrentLocation(), "OpenMPCancelConstruct"); 435 }, 436 [&](const Fortran::parser::OpenMPCancellationPointConstruct 437 &cancellationPointConstruct) { 438 TODO(converter.getCurrentLocation(), "OpenMPCancelConstruct"); 439 }, 440 }, 441 standaloneConstruct.u); 442 } 443 444 static omp::ClauseProcBindKindAttr genProcBindKindAttr( 445 fir::FirOpBuilder &firOpBuilder, 446 const Fortran::parser::OmpClause::ProcBind *procBindClause) { 447 omp::ClauseProcBindKind pbKind; 448 switch (procBindClause->v.v) { 449 case Fortran::parser::OmpProcBindClause::Type::Master: 450 pbKind = omp::ClauseProcBindKind::Master; 451 break; 452 case Fortran::parser::OmpProcBindClause::Type::Close: 453 pbKind = omp::ClauseProcBindKind::Close; 454 break; 455 case Fortran::parser::OmpProcBindClause::Type::Spread: 456 pbKind = omp::ClauseProcBindKind::Spread; 457 break; 458 case Fortran::parser::OmpProcBindClause::Type::Primary: 459 pbKind = omp::ClauseProcBindKind::Primary; 460 break; 461 } 462 return omp::ClauseProcBindKindAttr::get(firOpBuilder.getContext(), pbKind); 463 } 464 465 /* When parallel is used in a combined construct, then use this function to 466 * create the parallel operation. It handles the parallel specific clauses 467 * and leaves the rest for handling at the inner operations. 468 * TODO: Refactor clause handling 469 */ 470 template <typename Directive> 471 static void 472 createCombinedParallelOp(Fortran::lower::AbstractConverter &converter, 473 Fortran::lower::pft::Evaluation &eval, 474 const Directive &directive) { 475 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder(); 476 mlir::Location currentLocation = converter.getCurrentLocation(); 477 Fortran::lower::StatementContext stmtCtx; 478 llvm::ArrayRef<mlir::Type> argTy; 479 mlir::Value ifClauseOperand, numThreadsClauseOperand; 480 SmallVector<Value> allocatorOperands, allocateOperands; 481 mlir::omp::ClauseProcBindKindAttr procBindKindAttr; 482 const auto &opClauseList = 483 std::get<Fortran::parser::OmpClauseList>(directive.t); 484 // TODO: Handle the following clauses 485 // 1. default 486 // 2. copyin 487 // Note: rest of the clauses are handled when the inner operation is created 488 for (const Fortran::parser::OmpClause &clause : opClauseList.v) { 489 if (const auto &ifClause = 490 std::get_if<Fortran::parser::OmpClause::If>(&clause.u)) { 491 auto &expr = std::get<Fortran::parser::ScalarLogicalExpr>(ifClause->v.t); 492 mlir::Value ifVal = fir::getBase( 493 converter.genExprValue(*Fortran::semantics::GetExpr(expr), stmtCtx)); 494 ifClauseOperand = firOpBuilder.createConvert( 495 currentLocation, firOpBuilder.getI1Type(), ifVal); 496 } else if (const auto &numThreadsClause = 497 std::get_if<Fortran::parser::OmpClause::NumThreads>( 498 &clause.u)) { 499 numThreadsClauseOperand = fir::getBase(converter.genExprValue( 500 *Fortran::semantics::GetExpr(numThreadsClause->v), stmtCtx)); 501 } else if (const auto &procBindClause = 502 std::get_if<Fortran::parser::OmpClause::ProcBind>( 503 &clause.u)) { 504 procBindKindAttr = genProcBindKindAttr(firOpBuilder, procBindClause); 505 } 506 } 507 // Create and insert the operation. 508 auto parallelOp = firOpBuilder.create<mlir::omp::ParallelOp>( 509 currentLocation, argTy, ifClauseOperand, numThreadsClauseOperand, 510 allocateOperands, allocatorOperands, /*reduction_vars=*/ValueRange(), 511 /*reductions=*/nullptr, procBindKindAttr); 512 513 createBodyOfOp<omp::ParallelOp>(parallelOp, converter, currentLocation, eval, 514 &opClauseList, /*iv=*/{}, 515 /*isCombined=*/true); 516 } 517 518 static void 519 genOMP(Fortran::lower::AbstractConverter &converter, 520 Fortran::lower::pft::Evaluation &eval, 521 const Fortran::parser::OpenMPBlockConstruct &blockConstruct) { 522 const auto &beginBlockDirective = 523 std::get<Fortran::parser::OmpBeginBlockDirective>(blockConstruct.t); 524 const auto &blockDirective = 525 std::get<Fortran::parser::OmpBlockDirective>(beginBlockDirective.t); 526 const auto &endBlockDirective = 527 std::get<Fortran::parser::OmpEndBlockDirective>(blockConstruct.t); 528 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder(); 529 mlir::Location currentLocation = converter.getCurrentLocation(); 530 531 Fortran::lower::StatementContext stmtCtx; 532 llvm::ArrayRef<mlir::Type> argTy; 533 mlir::Value ifClauseOperand, numThreadsClauseOperand, finalClauseOperand, 534 priorityClauseOperand; 535 mlir::omp::ClauseProcBindKindAttr procBindKindAttr; 536 SmallVector<Value> allocateOperands, allocatorOperands; 537 mlir::UnitAttr nowaitAttr, untiedAttr, mergeableAttr; 538 539 const auto &opClauseList = 540 std::get<Fortran::parser::OmpClauseList>(beginBlockDirective.t); 541 for (const auto &clause : opClauseList.v) { 542 if (const auto &ifClause = 543 std::get_if<Fortran::parser::OmpClause::If>(&clause.u)) { 544 auto &expr = std::get<Fortran::parser::ScalarLogicalExpr>(ifClause->v.t); 545 mlir::Value ifVal = fir::getBase( 546 converter.genExprValue(*Fortran::semantics::GetExpr(expr), stmtCtx)); 547 ifClauseOperand = firOpBuilder.createConvert( 548 currentLocation, firOpBuilder.getI1Type(), ifVal); 549 } else if (const auto &numThreadsClause = 550 std::get_if<Fortran::parser::OmpClause::NumThreads>( 551 &clause.u)) { 552 // OMPIRBuilder expects `NUM_THREAD` clause as a `Value`. 553 numThreadsClauseOperand = fir::getBase(converter.genExprValue( 554 *Fortran::semantics::GetExpr(numThreadsClause->v), stmtCtx)); 555 } else if (const auto &procBindClause = 556 std::get_if<Fortran::parser::OmpClause::ProcBind>( 557 &clause.u)) { 558 procBindKindAttr = genProcBindKindAttr(firOpBuilder, procBindClause); 559 } else if (const auto &allocateClause = 560 std::get_if<Fortran::parser::OmpClause::Allocate>( 561 &clause.u)) { 562 genAllocateClause(converter, allocateClause->v, allocatorOperands, 563 allocateOperands); 564 } else if (std::get_if<Fortran::parser::OmpClause::Private>(&clause.u) || 565 std::get_if<Fortran::parser::OmpClause::Firstprivate>( 566 &clause.u)) { 567 // Privatisation clauses are handled elsewhere. 568 continue; 569 } else if (std::get_if<Fortran::parser::OmpClause::Threads>(&clause.u)) { 570 // Nothing needs to be done for threads clause. 571 continue; 572 } else if (const auto &finalClause = 573 std::get_if<Fortran::parser::OmpClause::Final>(&clause.u)) { 574 mlir::Value finalVal = fir::getBase(converter.genExprValue( 575 *Fortran::semantics::GetExpr(finalClause->v), stmtCtx)); 576 finalClauseOperand = firOpBuilder.createConvert( 577 currentLocation, firOpBuilder.getI1Type(), finalVal); 578 } else if (std::get_if<Fortran::parser::OmpClause::Untied>(&clause.u)) { 579 untiedAttr = firOpBuilder.getUnitAttr(); 580 } else if (std::get_if<Fortran::parser::OmpClause::Mergeable>(&clause.u)) { 581 mergeableAttr = firOpBuilder.getUnitAttr(); 582 } else if (const auto &priorityClause = 583 std::get_if<Fortran::parser::OmpClause::Priority>( 584 &clause.u)) { 585 priorityClauseOperand = fir::getBase(converter.genExprValue( 586 *Fortran::semantics::GetExpr(priorityClause->v), stmtCtx)); 587 } else { 588 TODO(currentLocation, "OpenMP Block construct clauses"); 589 } 590 } 591 592 for (const auto &clause : 593 std::get<Fortran::parser::OmpClauseList>(endBlockDirective.t).v) { 594 if (std::get_if<Fortran::parser::OmpClause::Nowait>(&clause.u)) 595 nowaitAttr = firOpBuilder.getUnitAttr(); 596 } 597 598 if (blockDirective.v == llvm::omp::OMPD_parallel) { 599 // Create and insert the operation. 600 auto parallelOp = firOpBuilder.create<mlir::omp::ParallelOp>( 601 currentLocation, argTy, ifClauseOperand, numThreadsClauseOperand, 602 allocateOperands, allocatorOperands, /*reduction_vars=*/ValueRange(), 603 /*reductions=*/nullptr, procBindKindAttr); 604 createBodyOfOp<omp::ParallelOp>(parallelOp, converter, currentLocation, 605 eval, &opClauseList); 606 } else if (blockDirective.v == llvm::omp::OMPD_master) { 607 auto masterOp = 608 firOpBuilder.create<mlir::omp::MasterOp>(currentLocation, argTy); 609 createBodyOfOp<omp::MasterOp>(masterOp, converter, currentLocation, eval); 610 } else if (blockDirective.v == llvm::omp::OMPD_single) { 611 auto singleOp = firOpBuilder.create<mlir::omp::SingleOp>( 612 currentLocation, allocateOperands, allocatorOperands, nowaitAttr); 613 createBodyOfOp<omp::SingleOp>(singleOp, converter, currentLocation, eval); 614 } else if (blockDirective.v == llvm::omp::OMPD_ordered) { 615 auto orderedOp = firOpBuilder.create<mlir::omp::OrderedRegionOp>( 616 currentLocation, /*simd=*/nullptr); 617 createBodyOfOp<omp::OrderedRegionOp>(orderedOp, converter, currentLocation, 618 eval); 619 } else if (blockDirective.v == llvm::omp::OMPD_task) { 620 auto taskOp = firOpBuilder.create<mlir::omp::TaskOp>( 621 currentLocation, ifClauseOperand, finalClauseOperand, untiedAttr, 622 mergeableAttr, /*in_reduction_vars=*/ValueRange(), 623 /*in_reductions=*/nullptr, priorityClauseOperand, allocateOperands, 624 allocatorOperands); 625 createBodyOfOp(taskOp, converter, currentLocation, eval, &opClauseList); 626 } else { 627 TODO(converter.getCurrentLocation(), "Unhandled block directive"); 628 } 629 } 630 631 static void genOMP(Fortran::lower::AbstractConverter &converter, 632 Fortran::lower::pft::Evaluation &eval, 633 const Fortran::parser::OpenMPLoopConstruct &loopConstruct) { 634 635 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder(); 636 mlir::Location currentLocation = converter.getCurrentLocation(); 637 llvm::SmallVector<mlir::Value> lowerBound, upperBound, step, linearVars, 638 linearStepVars, reductionVars; 639 mlir::Value scheduleChunkClauseOperand; 640 mlir::Attribute scheduleClauseOperand, collapseClauseOperand, 641 noWaitClauseOperand, orderedClauseOperand, orderClauseOperand; 642 const auto &wsLoopOpClauseList = std::get<Fortran::parser::OmpClauseList>( 643 std::get<Fortran::parser::OmpBeginLoopDirective>(loopConstruct.t).t); 644 645 const auto ompDirective = 646 std::get<Fortran::parser::OmpLoopDirective>( 647 std::get<Fortran::parser::OmpBeginLoopDirective>(loopConstruct.t).t) 648 .v; 649 if (llvm::omp::OMPD_parallel_do == ompDirective) { 650 createCombinedParallelOp<Fortran::parser::OmpBeginLoopDirective>( 651 converter, eval, 652 std::get<Fortran::parser::OmpBeginLoopDirective>(loopConstruct.t)); 653 } else if (llvm::omp::OMPD_do != ompDirective) { 654 TODO(converter.getCurrentLocation(), "Construct enclosing do loop"); 655 } 656 657 // Collect the loops to collapse. 658 auto *doConstructEval = &eval.getFirstNestedEvaluation(); 659 660 std::int64_t collapseValue = 661 Fortran::lower::getCollapseValue(wsLoopOpClauseList); 662 std::size_t loopVarTypeSize = 0; 663 SmallVector<const Fortran::semantics::Symbol *> iv; 664 do { 665 auto *doLoop = &doConstructEval->getFirstNestedEvaluation(); 666 auto *doStmt = doLoop->getIf<Fortran::parser::NonLabelDoStmt>(); 667 assert(doStmt && "Expected do loop to be in the nested evaluation"); 668 const auto &loopControl = 669 std::get<std::optional<Fortran::parser::LoopControl>>(doStmt->t); 670 const Fortran::parser::LoopControl::Bounds *bounds = 671 std::get_if<Fortran::parser::LoopControl::Bounds>(&loopControl->u); 672 assert(bounds && "Expected bounds for worksharing do loop"); 673 Fortran::lower::StatementContext stmtCtx; 674 lowerBound.push_back(fir::getBase(converter.genExprValue( 675 *Fortran::semantics::GetExpr(bounds->lower), stmtCtx))); 676 upperBound.push_back(fir::getBase(converter.genExprValue( 677 *Fortran::semantics::GetExpr(bounds->upper), stmtCtx))); 678 if (bounds->step) { 679 step.push_back(fir::getBase(converter.genExprValue( 680 *Fortran::semantics::GetExpr(bounds->step), stmtCtx))); 681 } else { // If `step` is not present, assume it as `1`. 682 step.push_back(firOpBuilder.createIntegerConstant( 683 currentLocation, firOpBuilder.getIntegerType(32), 1)); 684 } 685 iv.push_back(bounds->name.thing.symbol); 686 loopVarTypeSize = std::max(loopVarTypeSize, 687 bounds->name.thing.symbol->GetUltimate().size()); 688 689 collapseValue--; 690 doConstructEval = 691 &*std::next(doConstructEval->getNestedEvaluations().begin()); 692 } while (collapseValue > 0); 693 694 for (const auto &clause : wsLoopOpClauseList.v) { 695 if (const auto &scheduleClause = 696 std::get_if<Fortran::parser::OmpClause::Schedule>(&clause.u)) { 697 if (const auto &chunkExpr = 698 std::get<std::optional<Fortran::parser::ScalarIntExpr>>( 699 scheduleClause->v.t)) { 700 if (const auto *expr = Fortran::semantics::GetExpr(*chunkExpr)) { 701 Fortran::lower::StatementContext stmtCtx; 702 scheduleChunkClauseOperand = 703 fir::getBase(converter.genExprValue(*expr, stmtCtx)); 704 } 705 } 706 } 707 } 708 709 // The types of lower bound, upper bound, and step are converted into the 710 // type of the loop variable if necessary. 711 mlir::Type loopVarType = getLoopVarType(converter, loopVarTypeSize); 712 for (unsigned it = 0; it < (unsigned)lowerBound.size(); it++) { 713 lowerBound[it] = firOpBuilder.createConvert(currentLocation, loopVarType, 714 lowerBound[it]); 715 upperBound[it] = firOpBuilder.createConvert(currentLocation, loopVarType, 716 upperBound[it]); 717 step[it] = 718 firOpBuilder.createConvert(currentLocation, loopVarType, step[it]); 719 } 720 721 // FIXME: Add support for following clauses: 722 // 1. linear 723 // 2. order 724 auto wsLoopOp = firOpBuilder.create<mlir::omp::WsLoopOp>( 725 currentLocation, lowerBound, upperBound, step, linearVars, linearStepVars, 726 reductionVars, /*reductions=*/nullptr, 727 scheduleClauseOperand.dyn_cast_or_null<omp::ClauseScheduleKindAttr>(), 728 scheduleChunkClauseOperand, /*schedule_modifiers=*/nullptr, 729 /*simd_modifier=*/nullptr, 730 collapseClauseOperand.dyn_cast_or_null<IntegerAttr>(), 731 noWaitClauseOperand.dyn_cast_or_null<UnitAttr>(), 732 orderedClauseOperand.dyn_cast_or_null<IntegerAttr>(), 733 orderClauseOperand.dyn_cast_or_null<omp::ClauseOrderKindAttr>(), 734 /*inclusive=*/firOpBuilder.getUnitAttr()); 735 736 // Handle attribute based clauses. 737 for (const Fortran::parser::OmpClause &clause : wsLoopOpClauseList.v) { 738 if (const auto &orderedClause = 739 std::get_if<Fortran::parser::OmpClause::Ordered>(&clause.u)) { 740 if (orderedClause->v.has_value()) { 741 const auto *expr = Fortran::semantics::GetExpr(orderedClause->v); 742 const std::optional<std::int64_t> orderedClauseValue = 743 Fortran::evaluate::ToInt64(*expr); 744 wsLoopOp.ordered_valAttr( 745 firOpBuilder.getI64IntegerAttr(*orderedClauseValue)); 746 } else { 747 wsLoopOp.ordered_valAttr(firOpBuilder.getI64IntegerAttr(0)); 748 } 749 } else if (const auto &collapseClause = 750 std::get_if<Fortran::parser::OmpClause::Collapse>( 751 &clause.u)) { 752 const auto *expr = Fortran::semantics::GetExpr(collapseClause->v); 753 const std::optional<std::int64_t> collapseValue = 754 Fortran::evaluate::ToInt64(*expr); 755 wsLoopOp.collapse_valAttr(firOpBuilder.getI64IntegerAttr(*collapseValue)); 756 } else if (const auto &scheduleClause = 757 std::get_if<Fortran::parser::OmpClause::Schedule>( 758 &clause.u)) { 759 mlir::MLIRContext *context = firOpBuilder.getContext(); 760 const auto &scheduleType = scheduleClause->v; 761 const auto &scheduleKind = 762 std::get<Fortran::parser::OmpScheduleClause::ScheduleType>( 763 scheduleType.t); 764 switch (scheduleKind) { 765 case Fortran::parser::OmpScheduleClause::ScheduleType::Static: 766 wsLoopOp.schedule_valAttr(omp::ClauseScheduleKindAttr::get( 767 context, omp::ClauseScheduleKind::Static)); 768 break; 769 case Fortran::parser::OmpScheduleClause::ScheduleType::Dynamic: 770 wsLoopOp.schedule_valAttr(omp::ClauseScheduleKindAttr::get( 771 context, omp::ClauseScheduleKind::Dynamic)); 772 break; 773 case Fortran::parser::OmpScheduleClause::ScheduleType::Guided: 774 wsLoopOp.schedule_valAttr(omp::ClauseScheduleKindAttr::get( 775 context, omp::ClauseScheduleKind::Guided)); 776 break; 777 case Fortran::parser::OmpScheduleClause::ScheduleType::Auto: 778 wsLoopOp.schedule_valAttr(omp::ClauseScheduleKindAttr::get( 779 context, omp::ClauseScheduleKind::Auto)); 780 break; 781 case Fortran::parser::OmpScheduleClause::ScheduleType::Runtime: 782 wsLoopOp.schedule_valAttr(omp::ClauseScheduleKindAttr::get( 783 context, omp::ClauseScheduleKind::Runtime)); 784 break; 785 } 786 } 787 } 788 // In FORTRAN `nowait` clause occur at the end of `omp do` directive. 789 // i.e 790 // !$omp do 791 // <...> 792 // !$omp end do nowait 793 if (const auto &endClauseList = 794 std::get<std::optional<Fortran::parser::OmpEndLoopDirective>>( 795 loopConstruct.t)) { 796 const auto &clauseList = 797 std::get<Fortran::parser::OmpClauseList>((*endClauseList).t); 798 for (const Fortran::parser::OmpClause &clause : clauseList.v) 799 if (std::get_if<Fortran::parser::OmpClause::Nowait>(&clause.u)) 800 wsLoopOp.nowaitAttr(firOpBuilder.getUnitAttr()); 801 } 802 803 createBodyOfOp<omp::WsLoopOp>(wsLoopOp, converter, currentLocation, eval, 804 &wsLoopOpClauseList, iv); 805 } 806 807 static void 808 genOMP(Fortran::lower::AbstractConverter &converter, 809 Fortran::lower::pft::Evaluation &eval, 810 const Fortran::parser::OpenMPCriticalConstruct &criticalConstruct) { 811 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder(); 812 mlir::Location currentLocation = converter.getCurrentLocation(); 813 std::string name; 814 const Fortran::parser::OmpCriticalDirective &cd = 815 std::get<Fortran::parser::OmpCriticalDirective>(criticalConstruct.t); 816 if (std::get<std::optional<Fortran::parser::Name>>(cd.t).has_value()) { 817 name = 818 std::get<std::optional<Fortran::parser::Name>>(cd.t).value().ToString(); 819 } 820 821 uint64_t hint = 0; 822 const auto &clauseList = std::get<Fortran::parser::OmpClauseList>(cd.t); 823 for (const Fortran::parser::OmpClause &clause : clauseList.v) 824 if (auto hintClause = 825 std::get_if<Fortran::parser::OmpClause::Hint>(&clause.u)) { 826 const auto *expr = Fortran::semantics::GetExpr(hintClause->v); 827 hint = *Fortran::evaluate::ToInt64(*expr); 828 break; 829 } 830 831 mlir::omp::CriticalOp criticalOp = [&]() { 832 if (name.empty()) { 833 return firOpBuilder.create<mlir::omp::CriticalOp>(currentLocation, 834 FlatSymbolRefAttr()); 835 } else { 836 mlir::ModuleOp module = firOpBuilder.getModule(); 837 mlir::OpBuilder modBuilder(module.getBodyRegion()); 838 auto global = module.lookupSymbol<mlir::omp::CriticalDeclareOp>(name); 839 if (!global) 840 global = modBuilder.create<mlir::omp::CriticalDeclareOp>( 841 currentLocation, name, hint); 842 return firOpBuilder.create<mlir::omp::CriticalOp>( 843 currentLocation, mlir::FlatSymbolRefAttr::get( 844 firOpBuilder.getContext(), global.sym_name())); 845 } 846 }(); 847 createBodyOfOp<omp::CriticalOp>(criticalOp, converter, currentLocation, eval); 848 } 849 850 static void 851 genOMP(Fortran::lower::AbstractConverter &converter, 852 Fortran::lower::pft::Evaluation &eval, 853 const Fortran::parser::OpenMPSectionConstruct §ionConstruct) { 854 855 auto &firOpBuilder = converter.getFirOpBuilder(); 856 auto currentLocation = converter.getCurrentLocation(); 857 mlir::omp::SectionOp sectionOp = 858 firOpBuilder.create<mlir::omp::SectionOp>(currentLocation); 859 createBodyOfOp<omp::SectionOp>(sectionOp, converter, currentLocation, eval); 860 } 861 862 // TODO: Add support for reduction 863 static void 864 genOMP(Fortran::lower::AbstractConverter &converter, 865 Fortran::lower::pft::Evaluation &eval, 866 const Fortran::parser::OpenMPSectionsConstruct §ionsConstruct) { 867 auto &firOpBuilder = converter.getFirOpBuilder(); 868 auto currentLocation = converter.getCurrentLocation(); 869 SmallVector<Value> reductionVars, allocateOperands, allocatorOperands; 870 mlir::UnitAttr noWaitClauseOperand; 871 const auto §ionsClauseList = std::get<Fortran::parser::OmpClauseList>( 872 std::get<Fortran::parser::OmpBeginSectionsDirective>(sectionsConstruct.t) 873 .t); 874 for (const Fortran::parser::OmpClause &clause : sectionsClauseList.v) { 875 876 // Reduction Clause 877 if (std::get_if<Fortran::parser::OmpClause::Reduction>(&clause.u)) { 878 TODO(currentLocation, "OMPC_Reduction"); 879 880 // Allocate clause 881 } else if (const auto &allocateClause = 882 std::get_if<Fortran::parser::OmpClause::Allocate>( 883 &clause.u)) { 884 genAllocateClause(converter, allocateClause->v, allocatorOperands, 885 allocateOperands); 886 } 887 } 888 const auto &endSectionsClauseList = 889 std::get<Fortran::parser::OmpEndSectionsDirective>(sectionsConstruct.t); 890 const auto &clauseList = 891 std::get<Fortran::parser::OmpClauseList>(endSectionsClauseList.t); 892 for (const auto &clause : clauseList.v) { 893 // Nowait clause 894 if (std::get_if<Fortran::parser::OmpClause::Nowait>(&clause.u)) { 895 noWaitClauseOperand = firOpBuilder.getUnitAttr(); 896 } 897 } 898 899 llvm::omp::Directive dir = 900 std::get<Fortran::parser::OmpSectionsDirective>( 901 std::get<Fortran::parser::OmpBeginSectionsDirective>( 902 sectionsConstruct.t) 903 .t) 904 .v; 905 906 // Parallel Sections Construct 907 if (dir == llvm::omp::Directive::OMPD_parallel_sections) { 908 createCombinedParallelOp<Fortran::parser::OmpBeginSectionsDirective>( 909 converter, eval, 910 std::get<Fortran::parser::OmpBeginSectionsDirective>( 911 sectionsConstruct.t)); 912 auto sectionsOp = firOpBuilder.create<mlir::omp::SectionsOp>( 913 currentLocation, /*reduction_vars*/ ValueRange(), 914 /*reductions=*/nullptr, allocateOperands, allocatorOperands, 915 /*nowait=*/nullptr); 916 createBodyOfOp(sectionsOp, converter, currentLocation, eval); 917 918 // Sections Construct 919 } else if (dir == llvm::omp::Directive::OMPD_sections) { 920 auto sectionsOp = firOpBuilder.create<mlir::omp::SectionsOp>( 921 currentLocation, reductionVars, /*reductions = */ nullptr, 922 allocateOperands, allocatorOperands, noWaitClauseOperand); 923 createBodyOfOp<omp::SectionsOp>(sectionsOp, converter, currentLocation, 924 eval); 925 } 926 } 927 928 static void genOmpAtomicHintAndMemoryOrderClauses( 929 Fortran::lower::AbstractConverter &converter, 930 const Fortran::parser::OmpAtomicClauseList &clauseList, 931 mlir::IntegerAttr &hint, 932 mlir::omp::ClauseMemoryOrderKindAttr &memory_order) { 933 auto &firOpBuilder = converter.getFirOpBuilder(); 934 for (const auto &clause : clauseList.v) { 935 if (auto ompClause = std::get_if<Fortran::parser::OmpClause>(&clause.u)) { 936 if (auto hintClause = 937 std::get_if<Fortran::parser::OmpClause::Hint>(&ompClause->u)) { 938 const auto *expr = Fortran::semantics::GetExpr(hintClause->v); 939 uint64_t hintExprValue = *Fortran::evaluate::ToInt64(*expr); 940 hint = firOpBuilder.getI64IntegerAttr(hintExprValue); 941 } 942 } else if (auto ompMemoryOrderClause = 943 std::get_if<Fortran::parser::OmpMemoryOrderClause>( 944 &clause.u)) { 945 if (std::get_if<Fortran::parser::OmpClause::Acquire>( 946 &ompMemoryOrderClause->v.u)) { 947 memory_order = mlir::omp::ClauseMemoryOrderKindAttr::get( 948 firOpBuilder.getContext(), omp::ClauseMemoryOrderKind::Acquire); 949 } else if (std::get_if<Fortran::parser::OmpClause::Relaxed>( 950 &ompMemoryOrderClause->v.u)) { 951 memory_order = mlir::omp::ClauseMemoryOrderKindAttr::get( 952 firOpBuilder.getContext(), omp::ClauseMemoryOrderKind::Relaxed); 953 } else if (std::get_if<Fortran::parser::OmpClause::SeqCst>( 954 &ompMemoryOrderClause->v.u)) { 955 memory_order = mlir::omp::ClauseMemoryOrderKindAttr::get( 956 firOpBuilder.getContext(), omp::ClauseMemoryOrderKind::Seq_cst); 957 } else if (std::get_if<Fortran::parser::OmpClause::Release>( 958 &ompMemoryOrderClause->v.u)) { 959 memory_order = mlir::omp::ClauseMemoryOrderKindAttr::get( 960 firOpBuilder.getContext(), omp::ClauseMemoryOrderKind::Release); 961 } 962 } 963 } 964 } 965 966 static void 967 genOmpAtomicWrite(Fortran::lower::AbstractConverter &converter, 968 Fortran::lower::pft::Evaluation &eval, 969 const Fortran::parser::OmpAtomicWrite &atomicWrite) { 970 auto &firOpBuilder = converter.getFirOpBuilder(); 971 auto currentLocation = converter.getCurrentLocation(); 972 // Get the value and address of atomic write operands. 973 const Fortran::parser::OmpAtomicClauseList &rightHandClauseList = 974 std::get<2>(atomicWrite.t); 975 const Fortran::parser::OmpAtomicClauseList &leftHandClauseList = 976 std::get<0>(atomicWrite.t); 977 const auto &assignmentStmtExpr = 978 std::get<Fortran::parser::Expr>(std::get<3>(atomicWrite.t).statement.t); 979 const auto &assignmentStmtVariable = std::get<Fortran::parser::Variable>( 980 std::get<3>(atomicWrite.t).statement.t); 981 Fortran::lower::StatementContext stmtCtx; 982 mlir::Value value = fir::getBase(converter.genExprValue( 983 *Fortran::semantics::GetExpr(assignmentStmtExpr), stmtCtx)); 984 mlir::Value address = fir::getBase(converter.genExprAddr( 985 *Fortran::semantics::GetExpr(assignmentStmtVariable), stmtCtx)); 986 // If no hint clause is specified, the effect is as if 987 // hint(omp_sync_hint_none) had been specified. 988 mlir::IntegerAttr hint = nullptr; 989 mlir::omp::ClauseMemoryOrderKindAttr memory_order = nullptr; 990 genOmpAtomicHintAndMemoryOrderClauses(converter, leftHandClauseList, hint, 991 memory_order); 992 genOmpAtomicHintAndMemoryOrderClauses(converter, rightHandClauseList, hint, 993 memory_order); 994 firOpBuilder.create<mlir::omp::AtomicWriteOp>(currentLocation, address, value, 995 hint, memory_order); 996 } 997 998 static void genOmpAtomicRead(Fortran::lower::AbstractConverter &converter, 999 Fortran::lower::pft::Evaluation &eval, 1000 const Fortran::parser::OmpAtomicRead &atomicRead) { 1001 auto &firOpBuilder = converter.getFirOpBuilder(); 1002 auto currentLocation = converter.getCurrentLocation(); 1003 // Get the address of atomic read operands. 1004 const Fortran::parser::OmpAtomicClauseList &rightHandClauseList = 1005 std::get<2>(atomicRead.t); 1006 const Fortran::parser::OmpAtomicClauseList &leftHandClauseList = 1007 std::get<0>(atomicRead.t); 1008 const auto &assignmentStmtExpr = 1009 std::get<Fortran::parser::Expr>(std::get<3>(atomicRead.t).statement.t); 1010 const auto &assignmentStmtVariable = std::get<Fortran::parser::Variable>( 1011 std::get<3>(atomicRead.t).statement.t); 1012 Fortran::lower::StatementContext stmtCtx; 1013 mlir::Value from_address = fir::getBase(converter.genExprAddr( 1014 *Fortran::semantics::GetExpr(assignmentStmtExpr), stmtCtx)); 1015 mlir::Value to_address = fir::getBase(converter.genExprAddr( 1016 *Fortran::semantics::GetExpr(assignmentStmtVariable), stmtCtx)); 1017 // If no hint clause is specified, the effect is as if 1018 // hint(omp_sync_hint_none) had been specified. 1019 mlir::IntegerAttr hint = nullptr; 1020 mlir::omp::ClauseMemoryOrderKindAttr memory_order = nullptr; 1021 genOmpAtomicHintAndMemoryOrderClauses(converter, leftHandClauseList, hint, 1022 memory_order); 1023 genOmpAtomicHintAndMemoryOrderClauses(converter, rightHandClauseList, hint, 1024 memory_order); 1025 firOpBuilder.create<mlir::omp::AtomicReadOp>(currentLocation, from_address, 1026 to_address, hint, memory_order); 1027 } 1028 1029 static void 1030 genOMP(Fortran::lower::AbstractConverter &converter, 1031 Fortran::lower::pft::Evaluation &eval, 1032 const Fortran::parser::OpenMPAtomicConstruct &atomicConstruct) { 1033 std::visit(Fortran::common::visitors{ 1034 [&](const Fortran::parser::OmpAtomicRead &atomicRead) { 1035 genOmpAtomicRead(converter, eval, atomicRead); 1036 }, 1037 [&](const Fortran::parser::OmpAtomicWrite &atomicWrite) { 1038 genOmpAtomicWrite(converter, eval, atomicWrite); 1039 }, 1040 [&](const auto &) { 1041 TODO(converter.getCurrentLocation(), 1042 "Atomic update & capture"); 1043 }, 1044 }, 1045 atomicConstruct.u); 1046 } 1047 1048 void Fortran::lower::genOpenMPConstruct( 1049 Fortran::lower::AbstractConverter &converter, 1050 Fortran::lower::pft::Evaluation &eval, 1051 const Fortran::parser::OpenMPConstruct &ompConstruct) { 1052 1053 std::visit( 1054 common::visitors{ 1055 [&](const Fortran::parser::OpenMPStandaloneConstruct 1056 &standaloneConstruct) { 1057 genOMP(converter, eval, standaloneConstruct); 1058 }, 1059 [&](const Fortran::parser::OpenMPSectionsConstruct 1060 §ionsConstruct) { 1061 genOMP(converter, eval, sectionsConstruct); 1062 }, 1063 [&](const Fortran::parser::OpenMPSectionConstruct §ionConstruct) { 1064 genOMP(converter, eval, sectionConstruct); 1065 }, 1066 [&](const Fortran::parser::OpenMPLoopConstruct &loopConstruct) { 1067 genOMP(converter, eval, loopConstruct); 1068 }, 1069 [&](const Fortran::parser::OpenMPDeclarativeAllocate 1070 &execAllocConstruct) { 1071 TODO(converter.getCurrentLocation(), "OpenMPDeclarativeAllocate"); 1072 }, 1073 [&](const Fortran::parser::OpenMPExecutableAllocate 1074 &execAllocConstruct) { 1075 TODO(converter.getCurrentLocation(), "OpenMPExecutableAllocate"); 1076 }, 1077 [&](const Fortran::parser::OpenMPBlockConstruct &blockConstruct) { 1078 genOMP(converter, eval, blockConstruct); 1079 }, 1080 [&](const Fortran::parser::OpenMPAtomicConstruct &atomicConstruct) { 1081 genOMP(converter, eval, atomicConstruct); 1082 }, 1083 [&](const Fortran::parser::OpenMPCriticalConstruct 1084 &criticalConstruct) { 1085 genOMP(converter, eval, criticalConstruct); 1086 }, 1087 }, 1088 ompConstruct.u); 1089 } 1090 1091 void Fortran::lower::genThreadprivateOp( 1092 Fortran::lower::AbstractConverter &converter, 1093 const Fortran::lower::pft::Variable &var) { 1094 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder(); 1095 mlir::Location currentLocation = converter.getCurrentLocation(); 1096 1097 const Fortran::semantics::Symbol &sym = var.getSymbol(); 1098 mlir::Value symThreadprivateValue; 1099 if (const Fortran::semantics::Symbol *common = 1100 Fortran::semantics::FindCommonBlockContaining(sym.GetUltimate())) { 1101 mlir::Value commonValue = converter.getSymbolAddress(*common); 1102 if (mlir::isa<mlir::omp::ThreadprivateOp>(commonValue.getDefiningOp())) { 1103 // Generate ThreadprivateOp for a common block instead of its members and 1104 // only do it once for a common block. 1105 return; 1106 } 1107 // Generate ThreadprivateOp and rebind the common block. 1108 mlir::Value commonThreadprivateValue = 1109 firOpBuilder.create<mlir::omp::ThreadprivateOp>( 1110 currentLocation, commonValue.getType(), commonValue); 1111 converter.bindSymbol(*common, commonThreadprivateValue); 1112 // Generate the threadprivate value for the common block member. 1113 symThreadprivateValue = 1114 genCommonBlockMember(converter, sym, commonThreadprivateValue); 1115 } else { 1116 mlir::Value symValue = converter.getSymbolAddress(sym); 1117 symThreadprivateValue = firOpBuilder.create<mlir::omp::ThreadprivateOp>( 1118 currentLocation, symValue.getType(), symValue); 1119 } 1120 1121 fir::ExtendedValue sexv = converter.getSymbolExtendedValue(sym); 1122 fir::ExtendedValue symThreadprivateExv = 1123 getExtendedValue(sexv, symThreadprivateValue); 1124 converter.bindSymbol(sym, symThreadprivateExv); 1125 } 1126 1127 void Fortran::lower::genOpenMPDeclarativeConstruct( 1128 Fortran::lower::AbstractConverter &converter, 1129 Fortran::lower::pft::Evaluation &eval, 1130 const Fortran::parser::OpenMPDeclarativeConstruct &ompDeclConstruct) { 1131 1132 std::visit( 1133 common::visitors{ 1134 [&](const Fortran::parser::OpenMPDeclarativeAllocate 1135 &declarativeAllocate) { 1136 TODO(converter.getCurrentLocation(), "OpenMPDeclarativeAllocate"); 1137 }, 1138 [&](const Fortran::parser::OpenMPDeclareReductionConstruct 1139 &declareReductionConstruct) { 1140 TODO(converter.getCurrentLocation(), 1141 "OpenMPDeclareReductionConstruct"); 1142 }, 1143 [&](const Fortran::parser::OpenMPDeclareSimdConstruct 1144 &declareSimdConstruct) { 1145 TODO(converter.getCurrentLocation(), "OpenMPDeclareSimdConstruct"); 1146 }, 1147 [&](const Fortran::parser::OpenMPDeclareTargetConstruct 1148 &declareTargetConstruct) { 1149 TODO(converter.getCurrentLocation(), 1150 "OpenMPDeclareTargetConstruct"); 1151 }, 1152 [&](const Fortran::parser::OpenMPThreadprivate &threadprivate) { 1153 // The directive is lowered when instantiating the variable to 1154 // support the case of threadprivate variable declared in module. 1155 }, 1156 }, 1157 ompDeclConstruct.u); 1158 } 1159