Debian Codegraph @

flang/lib/Lower/OpenMP/DataSharingProcessor.cpp

raw
1 //===-- DataSharingProcessor.cpp --------------------------------*- C++ -*-===//
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 "DataSharingProcessor.h"
14
15 #include "Utils.h"
16 #include "flang/Lower/ConvertVariable.h"
17 #include "flang/Lower/PFTBuilder.h"
18 #include "flang/Lower/SymbolMap.h"
19 #include "flang/Optimizer/Builder/HLFIRTools.h"
20 #include "flang/Optimizer/Builder/Todo.h"
21 #include "flang/Optimizer/HLFIR/HLFIROps.h"
22 #include "flang/Semantics/tools.h"
23
24 namespace Fortran {
25 namespace lower {
26 namespace omp {
27 bool DataSharingProcessor::OMPConstructSymbolVisitor::isSymbolDefineBy(
28 const semantics::Symbol *symbol, lower::pft::Evaluation &eval) const {
29 return eval.visit(
30 common::visitors{[&](const parser::OpenMPConstruct &functionParserNode) {
31 return symDefMap.count(symbol) &&
32 symDefMap.at(symbol) == &functionParserNode;
33 },
34 [](const auto &functionParserNode) { return false; }});
35 }
36
37 DataSharingProcessor::DataSharingProcessor(
38 lower::AbstractConverter &converter, semantics::SemanticsContext &semaCtx,
39 const List<Clause> &clauses, lower::pft::Evaluation &eval,
40 bool shouldCollectPreDeterminedSymbols, bool useDelayedPrivatization,
41 lower::SymMap *symTable)
42 : hasLastPrivateOp(false), converter(converter), semaCtx(semaCtx),
43 firOpBuilder(converter.getFirOpBuilder()), clauses(clauses), eval(eval),
44 shouldCollectPreDeterminedSymbols(shouldCollectPreDeterminedSymbols),
45 useDelayedPrivatization(useDelayedPrivatization), symTable(symTable),
46 visitor() {
47 eval.visit([&](const auto &functionParserNode) {
48 parser::Walk(functionParserNode, visitor);
49 });
50 }
51
52 void DataSharingProcessor::processStep1(
53 mlir::omp::PrivateClauseOps *clauseOps) {
54 collectSymbolsForPrivatization();
55 collectDefaultSymbols();
56 collectImplicitSymbols();
57 collectPreDeterminedSymbols();
58
59 privatize(clauseOps);
60
61 insertBarrier();
62 }
63
64 void DataSharingProcessor::processStep2(mlir::Operation *op, bool isLoop) {
65 // 'sections' lastprivate is handled by genOMP()
66 if (!mlir::isa<mlir::omp::SectionsOp>(op)) {
67 insPt = firOpBuilder.saveInsertionPoint();
68 copyLastPrivatize(op);
69 firOpBuilder.restoreInsertionPoint(insPt);
70 }
71
72 if (isLoop) {
73 // push deallocs out of the loop
74 firOpBuilder.setInsertionPointAfter(op);
75 insertDeallocs();
76 } else {
77 mlir::OpBuilder::InsertionGuard guard(firOpBuilder);
78 insertDeallocs();
79 }
80 }
81
82 void DataSharingProcessor::insertDeallocs() {
83 for (const semantics::Symbol *sym : allPrivatizedSymbols)
84 if (semantics::IsAllocatable(sym->GetUltimate())) {
85 if (!useDelayedPrivatization) {
86 converter.createHostAssociateVarCloneDealloc(*sym);
87 continue;
88 }
89
90 lower::SymbolBox hsb = converter.lookupOneLevelUpSymbol(*sym);
91 assert(hsb && "Host symbol box not found");
92 mlir::Type symType = hsb.getAddr().getType();
93 mlir::Location symLoc = hsb.getAddr().getLoc();
94 fir::ExtendedValue symExV = converter.getSymbolExtendedValue(*sym);
95 mlir::omp::PrivateClauseOp privatizer = symToPrivatizer.at(sym);
96
97 symTable->pushScope();
98
99 mlir::OpBuilder::InsertionGuard guard(firOpBuilder);
100
101 mlir::Region &deallocRegion = privatizer.getDeallocRegion();
102 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
103 mlir::Block *deallocEntryBlock = firOpBuilder.createBlock(
104 &deallocRegion, /*insertPt=*/{}, symType, symLoc);
105
106 firOpBuilder.setInsertionPointToEnd(deallocEntryBlock);
107 symTable->addSymbol(*sym,
108 fir::substBase(symExV, deallocRegion.getArgument(0)));
109
110 converter.createHostAssociateVarCloneDealloc(*sym);
111 firOpBuilder.create<mlir::omp::YieldOp>(hsb.getAddr().getLoc());
112
113 symTable->popScope();
114 }
115 }
116
117 void DataSharingProcessor::cloneSymbol(const semantics::Symbol *sym) {
118 bool success = converter.createHostAssociateVarClone(*sym);
119 (void)success;
120 assert(success && "Privatization failed due to existing binding");
121
122 bool isFirstPrivate = sym->test(semantics::Symbol::Flag::OmpFirstPrivate);
123 if (!isFirstPrivate &&
124 Fortran::lower::hasDefaultInitialization(sym->GetUltimate()))
125 Fortran::lower::defaultInitializeAtRuntime(converter, *sym, *symTable);
126 }
127
128 void DataSharingProcessor::copyFirstPrivateSymbol(
129 const semantics::Symbol *sym, mlir::OpBuilder::InsertPoint *copyAssignIP) {
130 if (sym->test(semantics::Symbol::Flag::OmpFirstPrivate))
131 converter.copyHostAssociateVar(*sym, copyAssignIP);
132 }
133
134 void DataSharingProcessor::copyLastPrivateSymbol(
135 const semantics::Symbol *sym,
136 [[maybe_unused]] mlir::OpBuilder::InsertPoint *lastPrivIP) {
137 if (sym->test(semantics::Symbol::Flag::OmpLastPrivate)) {
138 bool allocatable = semantics::IsAllocatable(sym->GetUltimate());
139 if (!allocatable) {
140 converter.copyHostAssociateVar(*sym, lastPrivIP);
141 return;
142 }
143
144 // copyHostAssociateVar doesn't work properly if the privatised copy was
145 // reallocated (e.g. by assignment): it will only copy if the ultimate
146 // symbol was already allocated, and it only copies data so any reallocated
147 // lengths etc are lost
148
149 // 1) Fetch the original copy of the variable.
150 assert(sym->has<Fortran::semantics::HostAssocDetails>() &&
151 "No host-association found");
152 const Fortran::semantics::Symbol &hsym = sym->GetUltimate();
153 Fortran::lower::SymbolBox hsb = symTable->lookupOneLevelUpSymbol(hsym);
154 assert(hsb && "Host symbol box not found");
155
156 // 2) Fetch the copied one that will mask the original.
157 Fortran::lower::SymbolBox sb = symTable->shallowLookupSymbol(sym);
158 assert(sb && "Host-associated symbol box not found");
159 assert(hsb.getAddr() != sb.getAddr() &&
160 "Host and associated symbol boxes are the same");
161
162 // 3) Perform the assignment.
163 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
164 mlir::Location loc = converter.genLocation(sym->name());
165 mlir::OpBuilder::InsertPoint insPt = builder.saveInsertionPoint();
166 if (lastPrivIP && lastPrivIP->isSet())
167 builder.restoreInsertionPoint(*lastPrivIP);
168 else
169 builder.setInsertionPointAfter(sb.getAddr().getDefiningOp());
170
171 hlfir::Entity dst{hsb.getAddr()};
172 hlfir::Entity src{sb.getAddr()};
173 builder.create<hlfir::AssignOp>(
174 loc, src, dst, /*isWholeAllocatableAssignment=*/allocatable,
175 /*keepLhsLengthInAllocatableAssignment=*/false,
176 /*temporary_lhs=*/false);
177
178 if (lastPrivIP && lastPrivIP->isSet() &&
179 sym->test(Fortran::semantics::Symbol::Flag::OmpLastPrivate)) {
180 builder.restoreInsertionPoint(insPt);
181 }
182 }
183 }
184
185 void DataSharingProcessor::collectOmpObjectListSymbol(
186 const omp::ObjectList &objects,
187 llvm::SetVector<const semantics::Symbol *> &symbolSet) {
188 for (const omp::Object &object : objects)
189 symbolSet.insert(object.sym());
190 }
191
192 void DataSharingProcessor::collectSymbolsForPrivatization() {
193 for (const omp::Clause &clause : clauses) {
194 if (const auto &privateClause =
195 std::get_if<omp::clause::Private>(&clause.u)) {
196 collectOmpObjectListSymbol(privateClause->v, explicitlyPrivatizedSymbols);
197 } else if (const auto &firstPrivateClause =
198 std::get_if<omp::clause::Firstprivate>(&clause.u)) {
199 collectOmpObjectListSymbol(firstPrivateClause->v,
200 explicitlyPrivatizedSymbols);
201 } else if (const auto &lastPrivateClause =
202 std::get_if<omp::clause::Lastprivate>(&clause.u)) {
203 const ObjectList &objects = std::get<ObjectList>(lastPrivateClause->t);
204 collectOmpObjectListSymbol(objects, explicitlyPrivatizedSymbols);
205 hasLastPrivateOp = true;
206 }
207 }
208
209 for (auto *sym : explicitlyPrivatizedSymbols)
210 allPrivatizedSymbols.insert(sym);
211 }
212
213 bool DataSharingProcessor::needBarrier() {
214 // Emit implicit barrier to synchronize threads and avoid data races on
215 // initialization of firstprivate variables and post-update of lastprivate
216 // variables.
217 // Emit implicit barrier for linear clause. Maybe on somewhere else.
218 for (const semantics::Symbol *sym : allPrivatizedSymbols) {
219 if (sym->test(semantics::Symbol::Flag::OmpFirstPrivate) &&
220 sym->test(semantics::Symbol::Flag::OmpLastPrivate))
221 return true;
222 }
223 return false;
224 }
225
226 void DataSharingProcessor::insertBarrier() {
227 if (needBarrier())
228 firOpBuilder.create<mlir::omp::BarrierOp>(converter.getCurrentLocation());
229 }
230
231 void DataSharingProcessor::insertLastPrivateCompare(mlir::Operation *op) {
232 mlir::omp::LoopNestOp loopOp;
233 if (auto wrapper = mlir::dyn_cast<mlir::omp::LoopWrapperInterface>(op))
234 loopOp = wrapper.isWrapper()
235 ? mlir::cast<mlir::omp::LoopNestOp>(wrapper.getWrappedLoop())
236 : nullptr;
237
238 bool cmpCreated = false;
239 mlir::OpBuilder::InsertionGuard guard(firOpBuilder);
240 for (const omp::Clause &clause : clauses) {
241 if (clause.id != llvm::omp::OMPC_lastprivate)
242 continue;
243 // TODO: Add lastprivate support for simd construct
244 if (mlir::isa<mlir::omp::WsloopOp>(op)) {
245 // Update the original variable just before exiting the worksharing
246 // loop. Conversion as follows:
247 //
248 // omp.wsloop { omp.wsloop {
249 // omp.loop_nest { omp.loop_nest {
250 // ... ...
251 // store ===> store
252 // omp.yield %v = arith.addi %iv, %step
253 // } %cmp = %step < 0 ? %v < %ub : %v > %ub
254 // omp.terminator fir.if %cmp {
255 // } fir.store %v to %loopIV
256 // ^%lpv_update_blk:
257 // }
258 // omp.yield
259 // }
260 // omp.terminator
261 // }
262
263 // Only generate the compare once in presence of multiple LastPrivate
264 // clauses.
265 if (cmpCreated)
266 continue;
267 cmpCreated = true;
268
269 mlir::Location loc = loopOp.getLoc();
270 mlir::Operation *lastOper = loopOp.getRegion().back().getTerminator();
271 firOpBuilder.setInsertionPoint(lastOper);
272
273 mlir::Value cmpOp;
274 llvm::SmallVector<mlir::Value> vs;
275 vs.reserve(loopOp.getIVs().size());
276 for (auto [iv, ub, step] : llvm::zip_equal(
277 loopOp.getIVs(), loopOp.getUpperBound(), loopOp.getStep())) {
278 // v = iv + step
279 // cmp = step < 0 ? v < ub : v > ub
280 mlir::Value v = firOpBuilder.create<mlir::arith::AddIOp>(loc, iv, step);
281 vs.push_back(v);
282 mlir::Value zero =
283 firOpBuilder.createIntegerConstant(loc, step.getType(), 0);
284 mlir::Value negativeStep = firOpBuilder.create<mlir::arith::CmpIOp>(
285 loc, mlir::arith::CmpIPredicate::slt, step, zero);
286 mlir::Value vLT = firOpBuilder.create<mlir::arith::CmpIOp>(
287 loc, mlir::arith::CmpIPredicate::slt, v, ub);
288 mlir::Value vGT = firOpBuilder.create<mlir::arith::CmpIOp>(
289 loc, mlir::arith::CmpIPredicate::sgt, v, ub);
290 mlir::Value icmpOp = firOpBuilder.create<mlir::arith::SelectOp>(
291 loc, negativeStep, vLT, vGT);
292
293 if (cmpOp) {
294 cmpOp = firOpBuilder.create<mlir::arith::AndIOp>(loc, cmpOp, icmpOp);
295 } else {
296 cmpOp = icmpOp;
297 }
298 }
299
300 auto ifOp = firOpBuilder.create<fir::IfOp>(loc, cmpOp, /*else*/ false);
301 firOpBuilder.setInsertionPointToStart(&ifOp.getThenRegion().front());
302 for (auto [v, loopIV] : llvm::zip_equal(vs, loopIVs)) {
303 assert(loopIV && "loopIV was not set");
304 firOpBuilder.createStoreWithConvert(loc, v, loopIV);
305 }
306 lastPrivIP = firOpBuilder.saveInsertionPoint();
307 } else if (mlir::isa<mlir::omp::SectionsOp>(op)) {
308 // Already handled by genOMP()
309 } else {
310 TODO(converter.getCurrentLocation(),
311 "lastprivate clause in constructs other than "
312 "simd/worksharing-loop");
313 }
314 }
315 }
316
317 static const parser::CharBlock *
318 getSource(const semantics::SemanticsContext &semaCtx,
319 const lower::pft::Evaluation &eval) {
320 const parser::CharBlock *source = nullptr;
321
322 auto ompConsVisit = [&](const parser::OpenMPConstruct &x) {
323 std::visit(common::visitors{
324 [&](const parser::OpenMPSectionsConstruct &x) {
325 source = &std::get<0>(x.t).source;
326 },
327 [&](const parser::OpenMPLoopConstruct &x) {
328 source = &std::get<0>(x.t).source;
329 },
330 [&](const parser::OpenMPBlockConstruct &x) {
331 source = &std::get<0>(x.t).source;
332 },
333 [&](const parser::OpenMPCriticalConstruct &x) {
334 source = &std::get<0>(x.t).source;
335 },
336 [&](const parser::OpenMPAtomicConstruct &x) {
337 std::visit([&](const auto &x) { source = &x.source; },
338 x.u);
339 },
340 [&](const auto &x) { source = &x.source; },
341 },
342 x.u);
343 };
344
345 eval.visit(common::visitors{
346 [&](const parser::OpenMPConstruct &x) { ompConsVisit(x); },
347 [&](const parser::OpenMPDeclarativeConstruct &x) { source = &x.source; },
348 [&](const parser::OmpEndLoopDirective &x) { source = &x.source; },
349 [&](const auto &x) {},
350 });
351
352 return source;
353 }
354
355 void DataSharingProcessor::collectSymbolsInNestedRegions(
356 lower::pft::Evaluation &eval, semantics::Symbol::Flag flag,
357 llvm::SetVector<const semantics::Symbol *> &symbolsInNestedRegions) {
358 for (lower::pft::Evaluation &nestedEval : eval.getNestedEvaluations()) {
359 if (nestedEval.hasNestedEvaluations()) {
360 if (nestedEval.isConstruct())
361 // Recursively look for OpenMP constructs within `nestedEval`'s region
362 collectSymbolsInNestedRegions(nestedEval, flag, symbolsInNestedRegions);
363 else {
364 converter.collectSymbolSet(nestedEval, symbolsInNestedRegions, flag,
365 /*collectSymbols=*/true,
366 /*collectHostAssociatedSymbols=*/false);
367 }
368 }
369 }
370 }
371
372 // Collect symbols to be default privatized in two steps.
373 // In step 1, collect all symbols in `eval` that match `flag` into
374 // `defaultSymbols`. In step 2, for nested constructs (if any), if and only if
375 // the nested construct is an OpenMP construct, collect those nested
376 // symbols skipping host associated symbols into `symbolsInNestedRegions`.
377 // Later, in current context, all symbols in the set
378 // `defaultSymbols` - `symbolsInNestedRegions` will be privatized.
379 void DataSharingProcessor::collectSymbols(
380 semantics::Symbol::Flag flag,
381 llvm::SetVector<const semantics::Symbol *> &symbols) {
382 // Collect all scopes associated with 'eval'.
383 llvm::SetVector<const semantics::Scope *> clauseScopes;
384 std::function<void(const semantics::Scope *)> collectScopes =
385 [&](const semantics::Scope *scope) {
386 clauseScopes.insert(scope);
387 for (const semantics::Scope &child : scope->children())
388 collectScopes(&child);
389 };
390 const parser::CharBlock *source =
391 clauses.empty() ? getSource(semaCtx, eval) : &clauses.front().source;
392 const semantics::Scope *curScope = nullptr;
393 if (source && !source->empty()) {
394 curScope = &semaCtx.FindScope(*source);
395 collectScopes(curScope);
396 }
397 // Collect all symbols referenced in the evaluation being processed,
398 // that matches 'flag'.
399 llvm::SetVector<const semantics::Symbol *> allSymbols;
400 converter.collectSymbolSet(eval, allSymbols, flag,
401 /*collectSymbols=*/true,
402 /*collectHostAssociatedSymbols=*/true);
403
404 llvm::SetVector<const semantics::Symbol *> symbolsInNestedRegions;
405 collectSymbolsInNestedRegions(eval, flag, symbolsInNestedRegions);
406
407 for (auto *symbol : allSymbols)
408 if (visitor.isSymbolDefineBy(symbol, eval))
409 symbolsInNestedRegions.remove(symbol);
410
411 // Filter-out symbols that must not be privatized.
412 bool collectImplicit = flag == semantics::Symbol::Flag::OmpImplicit;
413 bool collectPreDetermined = flag == semantics::Symbol::Flag::OmpPreDetermined;
414
415 auto isPrivatizable = [](const semantics::Symbol &sym) -> bool {
416 return !semantics::IsProcedure(sym) &&
417 !sym.GetUltimate().has<semantics::DerivedTypeDetails>() &&
418 !sym.GetUltimate().has<semantics::NamelistDetails>() &&
419 !semantics::IsImpliedDoIndex(sym.GetUltimate());
420 };
421
422 auto shouldCollectSymbol = [&](const semantics::Symbol *sym) {
423 if (collectImplicit)
424 return sym->test(semantics::Symbol::Flag::OmpImplicit);
425
426 if (collectPreDetermined)
427 return sym->test(semantics::Symbol::Flag::OmpPreDetermined);
428
429 return !sym->test(semantics::Symbol::Flag::OmpImplicit) &&
430 !sym->test(semantics::Symbol::Flag::OmpPreDetermined);
431 };
432
433 for (const auto *sym : allSymbols) {
434 assert(curScope && "couldn't find current scope");
435 if (isPrivatizable(*sym) && !symbolsInNestedRegions.contains(sym) &&
436 !explicitlyPrivatizedSymbols.contains(sym) &&
437 shouldCollectSymbol(sym) && clauseScopes.contains(&sym->owner())) {
438 allPrivatizedSymbols.insert(sym);
439 symbols.insert(sym);
440 }
441 }
442 }
443
444 void DataSharingProcessor::collectDefaultSymbols() {
445 using DataSharingAttribute = omp::clause::Default::DataSharingAttribute;
446 for (const omp::Clause &clause : clauses) {
447 if (const auto *defaultClause =
448 std::get_if<omp::clause::Default>(&clause.u)) {
449 if (defaultClause->v == DataSharingAttribute::Private)
450 collectSymbols(semantics::Symbol::Flag::OmpPrivate, defaultSymbols);
451 else if (defaultClause->v == DataSharingAttribute::Firstprivate)
452 collectSymbols(semantics::Symbol::Flag::OmpFirstPrivate,
453 defaultSymbols);
454 }
455 }
456 }
457
458 void DataSharingProcessor::collectImplicitSymbols() {
459 // There will be no implicit symbols when a default clause is present.
460 if (defaultSymbols.empty())
461 collectSymbols(semantics::Symbol::Flag::OmpImplicit, implicitSymbols);
462 }
463
464 void DataSharingProcessor::collectPreDeterminedSymbols() {
465 if (shouldCollectPreDeterminedSymbols)
466 collectSymbols(semantics::Symbol::Flag::OmpPreDetermined,
467 preDeterminedSymbols);
468 }
469
470 void DataSharingProcessor::privatize(mlir::omp::PrivateClauseOps *clauseOps) {
471 for (const semantics::Symbol *sym : allPrivatizedSymbols) {
472 if (const auto *commonDet =
473 sym->detailsIf<semantics::CommonBlockDetails>()) {
474 for (const auto &mem : commonDet->objects())
475 doPrivatize(&*mem, clauseOps);
476 } else
477 doPrivatize(sym, clauseOps);
478 }
479 }
480
481 void DataSharingProcessor::copyLastPrivatize(mlir::Operation *op) {
482 insertLastPrivateCompare(op);
483 for (const semantics::Symbol *sym : allPrivatizedSymbols)
484 if (const auto *commonDet =
485 sym->detailsIf<semantics::CommonBlockDetails>()) {
486 for (const auto &mem : commonDet->objects()) {
487 copyLastPrivateSymbol(&*mem, &lastPrivIP);
488 }
489 } else {
490 copyLastPrivateSymbol(sym, &lastPrivIP);
491 }
492 }
493
494 void DataSharingProcessor::doPrivatize(const semantics::Symbol *sym,
495 mlir::omp::PrivateClauseOps *clauseOps) {
496 if (!useDelayedPrivatization) {
497 cloneSymbol(sym);
498 copyFirstPrivateSymbol(sym);
499 return;
500 }
501
502 lower::SymbolBox hsb = converter.lookupOneLevelUpSymbol(*sym);
503 assert(hsb && "Host symbol box not found");
504
505 mlir::Type symType = hsb.getAddr().getType();
506 mlir::Location symLoc = hsb.getAddr().getLoc();
507 std::string privatizerName = sym->name().ToString() + ".privatizer";
508 bool isFirstPrivate = sym->test(semantics::Symbol::Flag::OmpFirstPrivate);
509
510 mlir::omp::PrivateClauseOp privatizerOp = [&]() {
511 auto moduleOp = firOpBuilder.getModule();
512 auto uniquePrivatizerName = fir::getTypeAsString(
513 symType, converter.getKindMap(),
514 converter.mangleName(*sym) +
515 (isFirstPrivate ? "_firstprivate" : "_private"));
516
517 if (auto existingPrivatizer =
518 moduleOp.lookupSymbol<mlir::omp::PrivateClauseOp>(
519 uniquePrivatizerName))
520 return existingPrivatizer;
521
522 mlir::OpBuilder::InsertionGuard guard(firOpBuilder);
523 firOpBuilder.setInsertionPoint(&moduleOp.getBodyRegion().front(),
524 moduleOp.getBodyRegion().front().begin());
525 auto result = firOpBuilder.create<mlir::omp::PrivateClauseOp>(
526 symLoc, uniquePrivatizerName, symType,
527 isFirstPrivate ? mlir::omp::DataSharingClauseType::FirstPrivate
528 : mlir::omp::DataSharingClauseType::Private);
529 fir::ExtendedValue symExV = converter.getSymbolExtendedValue(*sym);
530
531 symTable->pushScope();
532
533 // Populate the `alloc` region.
534 {
535 mlir::Region &allocRegion = result.getAllocRegion();
536 mlir::Block *allocEntryBlock = firOpBuilder.createBlock(
537 &allocRegion, /*insertPt=*/{}, symType, symLoc);
538
539 firOpBuilder.setInsertionPointToEnd(allocEntryBlock);
540
541 fir::ExtendedValue localExV =
542 hlfir::translateToExtendedValue(
543 symLoc, firOpBuilder, hlfir::Entity{allocRegion.getArgument(0)},
544 /*contiguousHint=*/
545 evaluate::IsSimplyContiguous(*sym, converter.getFoldingContext()))
546 .first;
547
548 symTable->addSymbol(*sym, localExV);
549 symTable->pushScope();
550 cloneSymbol(sym);
551 firOpBuilder.create<mlir::omp::YieldOp>(
552 hsb.getAddr().getLoc(),
553 symTable->shallowLookupSymbol(*sym).getAddr());
554 symTable->popScope();
555 }
556
557 // Populate the `copy` region if this is a `firstprivate`.
558 if (isFirstPrivate) {
559 mlir::Region &copyRegion = result.getCopyRegion();
560 // First block argument corresponding to the original/host value while
561 // second block argument corresponding to the privatized value.
562 mlir::Block *copyEntryBlock = firOpBuilder.createBlock(
563 &copyRegion, /*insertPt=*/{}, {symType, symType}, {symLoc, symLoc});
564 firOpBuilder.setInsertionPointToEnd(copyEntryBlock);
565
566 auto addSymbol = [&](unsigned argIdx, bool force = false) {
567 symExV.match(
568 [&](const fir::MutableBoxValue &box) {
569 symTable->addSymbol(
570 *sym, fir::substBase(box, copyRegion.getArgument(argIdx)),
571 force);
572 },
573 [&](const auto &box) {
574 symTable->addSymbol(*sym, copyRegion.getArgument(argIdx), force);
575 });
576 };
577
578 addSymbol(0, true);
579 symTable->pushScope();
580 addSymbol(1);
581
582 auto ip = firOpBuilder.saveInsertionPoint();
583 copyFirstPrivateSymbol(sym, &ip);
584
585 firOpBuilder.create<mlir::omp::YieldOp>(
586 hsb.getAddr().getLoc(),
587 symTable->shallowLookupSymbol(*sym).getAddr());
588 symTable->popScope();
589 }
590
591 symTable->popScope();
592 return result;
593 }();
594
595 if (clauseOps) {
596 clauseOps->privatizers.push_back(mlir::SymbolRefAttr::get(privatizerOp));
597 clauseOps->privateVars.push_back(hsb.getAddr());
598 }
599
600 symToPrivatizer[sym] = privatizerOp;
601 }
602
603 } // namespace omp
604 } // namespace lower
605 } // namespace Fortran