clang 23.0.0git
CIRGenOpenACCRecipe.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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// Helperes to emit OpenACC clause recipes as CIR code.
10//
11//===----------------------------------------------------------------------===//
12
13#include <numeric>
14
15#include "CIRGenOpenACCRecipe.h"
16
17namespace clang::CIRGen {
18mlir::Block *OpenACCRecipeBuilderBase::createRecipeBlock(mlir::Region &region,
19 mlir::Type opTy,
20 mlir::Location loc,
21 size_t numBounds,
22 bool isInit) {
24 types.reserve(numBounds + 2);
25 types.push_back(opTy);
26 // The init section is the only one that doesn't have TWO copies of the
27 // operation-type. Copy has a to/from, and destroy has a
28 // 'reference'/'privatized' copy version.
29 if (!isInit)
30 types.push_back(opTy);
31
32 auto boundsTy = mlir::acc::DataBoundsType::get(&cgf.getMLIRContext());
33 for (size_t i = 0; i < numBounds; ++i)
34 types.push_back(boundsTy);
35
36 llvm::SmallVector<mlir::Location> locs{types.size(), loc};
37 return builder.createBlock(&region, region.end(), types, locs);
38}
39void OpenACCRecipeBuilderBase::makeAllocaCopy(mlir::Location loc,
40 mlir::Type copyType,
41 mlir::Value numEltsToCopy,
42 mlir::Value offsetPerSubarray,
43 mlir::Value destAlloca,
44 mlir::Value srcAlloca) {
45 mlir::OpBuilder::InsertionGuard guardCase(builder);
46
47 mlir::Type itrTy = cgf.cgm.convertType(cgf.getContext().UnsignedLongLongTy);
48 auto itrPtrTy = cir::PointerType::get(itrTy);
49 mlir::IntegerAttr itrAlign =
52
53 auto loopBuilder = [&]() {
54 auto itr = cir::AllocaOp::create(builder, loc, itrPtrTy, "itr", itrAlign);
55 cir::ConstantOp constZero = builder.getConstInt(loc, itrTy, 0);
56 builder.CIRBaseBuilderTy::createStore(loc, constZero, itr);
58 loc,
59 /*condBuilder=*/
60 [&](mlir::OpBuilder &b, mlir::Location loc) {
61 // itr < numEltsToCopy
62 // Enforce a trip count of 1 if there wasn't any element count, this
63 // way we can just use this loop with a constant bounds instead of a
64 // separate code path.
65 if (!numEltsToCopy)
66 numEltsToCopy = builder.getConstInt(loc, itrTy, 1);
67
68 auto loadCur = cir::LoadOp::create(builder, loc, {itr});
69 auto cmp = builder.createCompare(loc, cir::CmpOpKind::lt, loadCur,
70 numEltsToCopy);
72 },
73 /*bodyBuilder=*/
74 [&](mlir::OpBuilder &b, mlir::Location loc) {
75 // destAlloca[itr] = srcAlloca[offsetPerSubArray * itr];
76 auto loadCur = cir::LoadOp::create(builder, loc, {itr});
77 auto srcOffset = builder.createMul(loc, offsetPerSubarray, loadCur);
78
79 auto ptrToOffsetIntoSrc = cir::PtrStrideOp::create(
80 builder, loc, copyType, srcAlloca, srcOffset);
81
82 auto offsetIntoDecayDest = cir::PtrStrideOp::create(
83 builder, loc, builder.getPointerTo(copyType), destAlloca,
84 loadCur);
85
86 builder.CIRBaseBuilderTy::createStore(loc, ptrToOffsetIntoSrc,
87 offsetIntoDecayDest);
88 builder.createYield(loc);
89 },
90 /*stepBuilder=*/
91 [&](mlir::OpBuilder &b, mlir::Location loc) {
92 // Simple increment of the iterator.
93 auto load = cir::LoadOp::create(builder, loc, {itr});
94 auto inc = builder.createInc(loc, load);
95 builder.CIRBaseBuilderTy::createStore(loc, inc, itr);
96 builder.createYield(loc);
97 });
98 };
99
100 cir::ScopeOp::create(builder, loc,
101 [&](mlir::OpBuilder &b, mlir::Location loc) {
102 loopBuilder();
103 builder.createYield(loc);
104 });
105}
106
107mlir::Value OpenACCRecipeBuilderBase::makeBoundsAlloca(
108 mlir::Block *block, SourceRange exprRange, mlir::Location loc,
109 std::string_view allocaName, size_t numBounds,
110 llvm::ArrayRef<QualType> boundTypes) {
111 mlir::OpBuilder::InsertionGuard guardCase(builder);
112
113 // Get the range of bounds arguments, which are all but the 1st arg.
114 llvm::ArrayRef<mlir::BlockArgument> boundsRange =
115 block->getArguments().drop_front(1);
116
117 // boundTypes contains the before and after of each bounds, so it ends up
118 // having 1 extra. Assert this is the case to ensure we don't call this in the
119 // wrong 'block'.
120 assert(boundsRange.size() + 1 == boundTypes.size());
121
122 mlir::Type itrTy = cgf.cgm.convertType(cgf.getContext().UnsignedLongLongTy);
123 auto idxType = mlir::IndexType::get(&cgf.getMLIRContext());
124
125 auto getUpperBound = [&](mlir::Value bound) {
126 auto upperBoundVal =
127 mlir::acc::GetUpperboundOp::create(builder, loc, idxType, bound);
128 return builder.createBuiltinIntCast(loc, upperBoundVal.getResult(), itrTy);
129 };
130
131 auto isArrayTy = [&](QualType ty) {
132 if (ty->isArrayType() && !ty->isConstantArrayType())
133 cgf.cgm.errorNYI(exprRange, "OpenACC recipe init for VLAs");
134 return ty->isConstantArrayType();
135 };
136
137 mlir::Type topLevelTy = cgf.convertType(boundTypes.back());
138 cir::PointerType topLevelTyPtr = builder.getPointerTo(topLevelTy);
139 // Do an alloca for the 'top' level type without bounds.
140 mlir::Value initialAlloca = builder.createAlloca(
141 loc, topLevelTyPtr, allocaName,
142 cgf.getContext().getTypeAlignInChars(boundTypes.back()));
143
144 bool lastBoundWasArray = isArrayTy(boundTypes.back());
145
146 // Make sure we track a moving version of this so we can get our
147 // 'copying' back to correct.
148 mlir::Value lastAlloca = initialAlloca;
149
150 // Since we're iterating the types in reverse, this sets up for each index
151 // corresponding to the boundsRange to be the 'after application of the
152 // bounds.
153 llvm::ArrayRef<QualType> boundResults = boundTypes.drop_back(1);
154
155 // Collect the 'do we have any allocas needed after this type' list.
156 llvm::SmallVector<bool> allocasLeftArr;
157 llvm::ArrayRef<QualType> resultTypes = boundTypes.drop_front();
158 std::transform_inclusive_scan(
159 resultTypes.begin(), resultTypes.end(),
160 std::back_inserter(allocasLeftArr), std::plus<bool>{},
161 [](QualType ty) { return !ty->isConstantArrayType(); }, false);
162
163 // Keep track of the number of 'elements' that we're allocating. Individual
164 // allocas should multiply this by the size of its current allocation.
165 mlir::Value cumulativeElts;
166 for (auto [bound, resultType, allocasLeft] : llvm::reverse(
167 llvm::zip_equal(boundsRange, boundResults, allocasLeftArr))) {
168
169 // if there is no further 'alloca' operation we need to do, we can skip
170 // creating the UB/multiplications/etc.
171 if (!allocasLeft)
172 break;
173
174 // First: figure out the number of elements in the current 'bound' list.
175 mlir::Value eltsPerSubArray = getUpperBound(bound);
176 mlir::Value eltsToAlloca;
177
178 // IF we are in a sub-bounds, the total number of elements to alloca is
179 // the product of that one and the current 'bounds' size. That is,
180 // arr[5][5], we would need 25 elements, not just 5. Else it is just the
181 // current number of elements.
182 if (cumulativeElts)
183 eltsToAlloca = builder.createMul(loc, eltsPerSubArray, cumulativeElts);
184 else
185 eltsToAlloca = eltsPerSubArray;
186
187 if (!lastBoundWasArray) {
188 // If we have to do an allocation, figure out the size of the
189 // allocation. alloca takes the number of bytes, not elements.
190 TypeInfoChars eltInfo = cgf.getContext().getTypeInfoInChars(resultType);
191 cir::ConstantOp eltSize = builder.getConstInt(
192 loc, itrTy, eltInfo.Width.alignTo(eltInfo.Align).getQuantity());
193 mlir::Value curSize = builder.createMul(loc, eltsToAlloca, eltSize);
194
195 mlir::Type eltTy = cgf.convertType(resultType);
196 cir::PointerType ptrTy = builder.getPointerTo(eltTy);
197 mlir::Value curAlloca = builder.createAlloca(
198 loc, ptrTy, eltTy, "openacc.init.bounds",
199 cgf.getContext().getTypeAlignInChars(resultType), curSize);
200
201 makeAllocaCopy(loc, ptrTy, cumulativeElts, eltsPerSubArray, lastAlloca,
202 curAlloca);
203 lastAlloca = curAlloca;
204 } else {
205 // In the case of an array, we just need to decay the pointer, so just do
206 // a zero-offset stride on the last alloca to decay it down an array
207 // level.
208 cir::ConstantOp constZero = builder.getConstInt(loc, itrTy, 0);
209 lastAlloca = builder.getArrayElement(loc, loc, lastAlloca,
210 cgf.convertType(resultType),
211 constZero, /*shouldDecay=*/true);
212 }
213
214 cumulativeElts = eltsToAlloca;
215 lastBoundWasArray = isArrayTy(resultType);
216 }
217 return initialAlloca;
218}
219
220std::pair<mlir::Value, mlir::Value> OpenACCRecipeBuilderBase::createBoundsLoop(
221 mlir::Value subscriptedValue, mlir::Value subscriptedValue2,
222 mlir::Value bound, mlir::Location loc, bool inverse) {
223 mlir::Operation *bodyInsertLoc;
224
225 mlir::Type itrTy = cgf.cgm.convertType(cgf.getContext().UnsignedLongLongTy);
226 auto itrPtrTy = cir::PointerType::get(itrTy);
227 mlir::IntegerAttr itrAlign =
228 cgf.cgm.getSize(cgf.getContext().getTypeAlignInChars(
229 cgf.getContext().UnsignedLongLongTy));
230 auto idxType = mlir::IndexType::get(&cgf.getMLIRContext());
231
232 auto doSubscriptOp = [&](mlir::Value subVal,
233 cir::LoadOp idxLoad) -> mlir::Value {
234 auto eltTy = cast<cir::PointerType>(subVal.getType()).getPointee();
235
236 if (auto arrayTy = dyn_cast<cir::ArrayType>(eltTy))
237 return builder.getArrayElement(loc, loc, subVal, arrayTy.getElementType(),
238 idxLoad,
239 /*shouldDecay=*/true);
240
241 assert(isa<cir::PointerType>(eltTy));
242
243 auto eltLoad = cir::LoadOp::create(builder, loc, {subVal});
244
245 return cir::PtrStrideOp::create(builder, loc, eltLoad.getType(), eltLoad,
246 idxLoad);
247 };
248
249 auto forStmtBuilder = [&]() {
250 // get the lower and upper bound for iterating over.
251 auto lowerBoundVal =
252 mlir::acc::GetLowerboundOp::create(builder, loc, idxType, bound);
253 mlir::Value lbConversion =
254 builder.createBuiltinIntCast(loc, lowerBoundVal.getResult(), itrTy);
255 auto upperBoundVal =
256 mlir::acc::GetUpperboundOp::create(builder, loc, idxType, bound);
257 mlir::Value ubConversion =
258 builder.createBuiltinIntCast(loc, upperBoundVal.getResult(), itrTy);
259
260 // Create a memory location for the iterator.
261 auto itr = cir::AllocaOp::create(builder, loc, itrPtrTy, "iter", itrAlign);
262 // Store to the iterator: either lower bound, or if inverse loop, upper
263 // bound.
264 if (inverse) {
265 cir::ConstantOp constOne = builder.getConstInt(loc, itrTy, 1);
266
267 auto sub = cir::SubOp::create(builder, loc, ubConversion, constOne);
268
269 // Upperbound is exclusive, so subtract 1.
270 builder.CIRBaseBuilderTy::createStore(loc, sub, itr);
271 } else {
272 // Lowerbound is inclusive, so we can include it.
273 builder.CIRBaseBuilderTy::createStore(loc, lbConversion, itr);
274 }
275 // Save the 'end' iterator based on whether we are inverted or not. This
276 // end iterator never changes, so we can just get it and convert it, so no
277 // need to store/load/etc.
278 mlir::Value endItr = inverse ? lbConversion : ubConversion;
279
280 builder.createFor(
281 loc,
282 /*condBuilder=*/
283 [&](mlir::OpBuilder &b, mlir::Location loc) {
284 auto loadCur = cir::LoadOp::create(builder, loc, {itr});
285 // Use 'not equal' since we are just doing an increment/decrement.
286 auto cmp = builder.createCompare(
287 loc, inverse ? cir::CmpOpKind::ge : cir::CmpOpKind::lt, loadCur,
288 endItr);
289 builder.createCondition(cmp);
290 },
291 /*bodyBuilder=*/
292 [&](mlir::OpBuilder &b, mlir::Location loc) {
293 auto load = cir::LoadOp::create(builder, loc, {itr});
294
295 if (subscriptedValue)
296 subscriptedValue = doSubscriptOp(subscriptedValue, load);
297 if (subscriptedValue2)
298 subscriptedValue2 = doSubscriptOp(subscriptedValue2, load);
299 bodyInsertLoc = builder.createYield(loc);
300 },
301 /*stepBuilder=*/
302 [&](mlir::OpBuilder &b, mlir::Location loc) {
303 auto load = cir::LoadOp::create(builder, loc, {itr});
304 auto unary = inverse ? builder.createDec(loc, load)
305 : builder.createInc(loc, load);
306 builder.CIRBaseBuilderTy::createStore(loc, unary, itr);
307 builder.createYield(loc);
308 });
309 };
310
311 cir::ScopeOp::create(builder, loc,
312 [&](mlir::OpBuilder &b, mlir::Location loc) {
313 forStmtBuilder();
314 builder.createYield(loc);
315 });
316
317 // Leave the insertion point to be inside the body, so we can loop over
318 // these things.
319 builder.setInsertionPoint(bodyInsertLoc);
320 return {subscriptedValue, subscriptedValue2};
321}
322
323mlir::acc::ReductionOperator
325 switch (op) {
327 return mlir::acc::ReductionOperator::AccAdd;
329 return mlir::acc::ReductionOperator::AccMul;
331 return mlir::acc::ReductionOperator::AccMax;
333 return mlir::acc::ReductionOperator::AccMin;
335 return mlir::acc::ReductionOperator::AccIand;
337 return mlir::acc::ReductionOperator::AccIor;
339 return mlir::acc::ReductionOperator::AccXor;
341 return mlir::acc::ReductionOperator::AccLand;
343 return mlir::acc::ReductionOperator::AccLor;
345 llvm_unreachable("invalid reduction operator");
346 }
347
348 llvm_unreachable("invalid reduction operator");
349}
350
351// This function generates the 'destroy' section for a recipe. Note
352// that this function is not 'insertion point' clean, in that it alters the
353// insertion point to be inside of the 'destroy' section of the recipe, but
354// doesn't restore it aftewards.
356 mlir::Location loc, mlir::Location locEnd, mlir::Value mainOp,
357 CharUnits alignment, QualType origType, size_t numBounds, QualType baseType,
358 mlir::Region &destroyRegion) {
359 mlir::Block *block = createRecipeBlock(destroyRegion, mainOp.getType(), loc,
360 numBounds, /*isInit=*/false);
361 builder.setInsertionPointToEnd(&destroyRegion.back());
362 CIRGenFunction::LexicalScope ls(cgf, loc, block);
363
364 mlir::Type elementTy =
365 mlir::cast<cir::PointerType>(mainOp.getType()).getPointee();
366 auto emitDestroy = [&](mlir::Value var, mlir::Type ty) {
367 Address addr{var, ty, alignment};
368 cgf.emitDestroy(addr, origType,
369 cgf.getDestroyer(QualType::DK_cxx_destructor));
370 };
371
372 if (numBounds) {
373 mlir::OpBuilder::InsertionGuard guardCase(builder);
374 // Get the range of bounds arguments, which are all but the 1st 2. 1st is
375 // a 'reference', 2nd is the 'private' variant we need to destroy from.
377 block->getArguments().drop_front(2);
378
379 mlir::Value subscriptedValue = block->getArgument(1);
380 for (mlir::BlockArgument boundArg : llvm::reverse(boundsRange))
381 subscriptedValue = createBoundsLoop(subscriptedValue, boundArg, loc,
382 /*inverse=*/true);
383
384 emitDestroy(subscriptedValue, cgf.cgm.convertType(origType));
385 } else {
386 // If we don't have any bounds, we can just destroy the variable directly.
387 // The destroy region has a signature of "original item, privatized item".
388 // So the 2nd item is the one that needs destroying, the former is just
389 // for reference and we don't really have a need for it at the moment.
390 emitDestroy(block->getArgument(1), elementTy);
391 }
392
393 ls.forceCleanup();
394 mlir::acc::YieldOp::create(builder, locEnd);
395}
396void OpenACCRecipeBuilderBase::makeBoundsInit(
397 mlir::Value alloca, mlir::Location loc, mlir::Block *block,
398 const VarDecl *allocaDecl, QualType origType, bool isInitSection) {
399 mlir::OpBuilder::InsertionGuard guardCase(builder);
400 builder.setInsertionPointToEnd(block);
401 CIRGenFunction::LexicalScope ls(cgf, loc, block);
402
403 CIRGenFunction::AutoVarEmission tempDeclEmission{*allocaDecl};
404 tempDeclEmission.emittedAsOffload = true;
405
406 // The init section is the only one of the handful that only has a single
407 // argument for the 'type', so we have to drop 1 for init, and future calls
408 // to this will need to drop 2.
410 block->getArguments().drop_front(isInitSection ? 1 : 2);
411
412 mlir::Value subscriptedValue = alloca;
413 for (mlir::BlockArgument boundArg : llvm::reverse(boundsRange))
414 subscriptedValue = createBoundsLoop(subscriptedValue, boundArg, loc,
415 /*inverse=*/false);
416
417 tempDeclEmission.setAllocatedAddress(
418 Address{subscriptedValue, cgf.convertType(origType),
419 cgf.getContext().getDeclAlign(allocaDecl)});
420 cgf.emitAutoVarInit(tempDeclEmission);
421}
422
423// TODO: OpenACC: when we start doing firstprivate for array/vlas/etc, we
424// probably need to do a little work about the 'init' calls to put it in 'copy'
425// region instead.
427 mlir::Location loc, mlir::Location locEnd, SourceRange exprRange,
428 mlir::Value mainOp, mlir::Region &recipeInitRegion, size_t numBounds,
429 llvm::ArrayRef<QualType> boundTypes, const VarDecl *allocaDecl,
430 QualType origType, bool emitInitExpr) {
431 assert(allocaDecl && "Required recipe variable not set?");
432 CIRGenFunction::DeclMapRevertingRAII declMapRAII{cgf, allocaDecl};
433
434 mlir::Block *block = createRecipeBlock(recipeInitRegion, mainOp.getType(),
435 loc, numBounds, /*isInit=*/true);
436 builder.setInsertionPointToEnd(&recipeInitRegion.back());
437 CIRGenFunction::LexicalScope ls(cgf, loc, block);
438
439 const Type *allocaPointeeType =
440 allocaDecl->getType()->getPointeeOrArrayElementType();
441 // We are OK with no init for builtins, arrays of builtins, or pointers,
442 // else we should NYI so we know to go look for these.
443 if (cgf.getContext().getLangOpts().CPlusPlus && !allocaDecl->getInit() &&
444 !allocaDecl->getType()->isPointerType() &&
445 !allocaPointeeType->isBuiltinType() &&
446 !allocaPointeeType->isPointerType()) {
447 // If we don't have any initialization recipe, we failed during Sema to
448 // initialize this correctly. If we disable the
449 // Sema::TentativeAnalysisScopes in SemaOpenACC::CreateInitRecipe, it'll
450 // emit an error to tell us. However, emitting those errors during
451 // production is a violation of the standard, so we cannot do them.
452 cgf.cgm.errorNYI(exprRange, "private/reduction default-init recipe");
453 }
454
455 if (!numBounds) {
456 // This is an 'easy' case, we just have to use the builtin init stuff to
457 // initialize this variable correctly.
458 CIRGenFunction::AutoVarEmission tempDeclEmission =
459 cgf.emitAutoVarAlloca(*allocaDecl, builder.saveInsertionPoint());
460 if (emitInitExpr)
461 cgf.emitAutoVarInit(tempDeclEmission);
462 } else {
463 mlir::Value alloca = makeBoundsAlloca(
464 block, exprRange, loc, allocaDecl->getName(), numBounds, boundTypes);
465
466 // If the initializer is trivial, there is nothing to do here, so save
467 // ourselves some effort.
468 if (emitInitExpr && allocaDecl->getInit() &&
469 (!cgf.isTrivialInitializer(allocaDecl->getInit()) ||
470 cgf.getContext().getLangOpts().getTrivialAutoVarInit() !=
472 makeBoundsInit(alloca, loc, block, allocaDecl, origType,
473 /*isInitSection=*/true);
474 }
475
476 ls.forceCleanup();
477 mlir::acc::YieldOp::create(builder, locEnd);
478}
479
481 mlir::Location loc, mlir::Location locEnd, mlir::Value mainOp,
482 const VarDecl *allocaDecl, const VarDecl *temporary,
483 mlir::Region &copyRegion, size_t numBounds) {
484 mlir::Block *block = createRecipeBlock(copyRegion, mainOp.getType(), loc,
485 numBounds, /*isInit=*/false);
486 builder.setInsertionPointToEnd(&copyRegion.back());
487 CIRGenFunction::LexicalScope ls(cgf, loc, block);
488
489 mlir::Value fromArg = block->getArgument(0);
490 mlir::Value toArg = block->getArgument(1);
491
493 block->getArguments().drop_front(2);
494
495 for (mlir::BlockArgument boundArg : llvm::reverse(boundsRange))
496 std::tie(fromArg, toArg) =
497 createBoundsLoop(fromArg, toArg, boundArg, loc, /*inverse=*/false);
498
499 // Set up the 'to' address.
500 mlir::Type elementTy =
501 mlir::cast<cir::PointerType>(toArg.getType()).getPointee();
502 CIRGenFunction::AutoVarEmission tempDeclEmission(*allocaDecl);
503 tempDeclEmission.emittedAsOffload = true;
504 tempDeclEmission.setAllocatedAddress(
505 Address{toArg, elementTy, cgf.getContext().getDeclAlign(allocaDecl)});
506
507 // Set up the 'from' address from the temporary.
508 CIRGenFunction::DeclMapRevertingRAII declMapRAII{cgf, temporary};
509 cgf.setAddrOfLocalVar(
510 temporary,
511 Address{fromArg, elementTy, cgf.getContext().getDeclAlign(allocaDecl)});
512 cgf.emitAutoVarInit(tempDeclEmission);
513
514 builder.setInsertionPointToEnd(&copyRegion.back());
515 ls.forceCleanup();
516 mlir::acc::YieldOp::create(builder, locEnd);
517}
518
519// This function generates the 'combiner' section for a reduction recipe. Note
520// that this function is not 'insertion point' clean, in that it alters the
521// insertion point to be inside of the 'combiner' section of the recipe, but
522// doesn't restore it aftewards.
524 mlir::Location loc, mlir::Location locEnd, mlir::Value mainOp,
525 mlir::acc::ReductionRecipeOp recipe, size_t numBounds, QualType origType,
527 mlir::Block *block =
528 createRecipeBlock(recipe.getCombinerRegion(), mainOp.getType(), loc,
529 numBounds, /*isInit=*/false);
530 builder.setInsertionPointToEnd(&recipe.getCombinerRegion().back());
531 CIRGenFunction::LexicalScope ls(cgf, loc, block);
532
533 mlir::Value lhsArg = block->getArgument(0);
534 mlir::Value rhsArg = block->getArgument(1);
536 block->getArguments().drop_front(2);
537
538 if (llvm::any_of(combinerRecipes, [](auto &r) { return r.Op == nullptr; })) {
539 cgf.cgm.errorNYI(loc, "OpenACC Reduction combiner not generated");
540 mlir::acc::YieldOp::create(builder, locEnd, block->getArgument(0));
541 return;
542 }
543
544 // apply the bounds so that we can get our bounds emitted correctly.
545 for (mlir::BlockArgument boundArg : llvm::reverse(boundsRange))
546 std::tie(lhsArg, rhsArg) =
547 createBoundsLoop(lhsArg, rhsArg, boundArg, loc, /*inverse=*/false);
548
549 // Emitter for when we know this isn't a struct or array we have to loop
550 // through. This should work for the 'field' once the get-element call has
551 // been made.
552 auto emitSingleCombiner =
553 [&](mlir::Value lhsArg, mlir::Value rhsArg,
555 mlir::Type elementTy =
556 mlir::cast<cir::PointerType>(lhsArg.getType()).getPointee();
557 CIRGenFunction::DeclMapRevertingRAII declMapRAIILhs{cgf, combiner.LHS};
558 cgf.setAddrOfLocalVar(
559 combiner.LHS, Address{lhsArg, elementTy,
560 cgf.getContext().getDeclAlign(combiner.LHS)});
561 CIRGenFunction::DeclMapRevertingRAII declMapRAIIRhs{cgf, combiner.RHS};
562 cgf.setAddrOfLocalVar(
563 combiner.RHS, Address{rhsArg, elementTy,
564 cgf.getContext().getDeclAlign(combiner.RHS)});
565
566 [[maybe_unused]] mlir::LogicalResult stmtRes =
567 cgf.emitStmt(combiner.Op, /*useCurrentScope=*/true);
568 };
569
570 // Emitter for when we know this is either a non-array or element of an array
571 // (which also shouldn't be an array type?). This function should generate the
572 // initialization code for an entire 'array-element'/non-array, including
573 // diving into each element of a struct (if necessary).
574 auto emitCombiner = [&](mlir::Value lhsArg, mlir::Value rhsArg, QualType ty) {
575 assert(!ty->isArrayType() && "Array type shouldn't get here");
576 if (const auto *rd = ty->getAsRecordDecl()) {
577 if (combinerRecipes.size() == 1 &&
578 cgf.getContext().hasSameType(ty, combinerRecipes[0].LHS->getType())) {
579 // If this is a 'top level' operator on the type we can just emit this
580 // as a simple one.
581 emitSingleCombiner(lhsArg, rhsArg, combinerRecipes[0]);
582 } else {
583 // else we have to handle each individual field after after a
584 // get-element.
585 const CIRGenRecordLayout &layout =
586 cgf.cgm.getTypes().getCIRGenRecordLayout(rd);
587 for (const auto &[field, combiner] :
588 llvm::zip_equal(rd->fields(), combinerRecipes)) {
589 mlir::Type fieldType = cgf.convertType(field->getType());
590 auto fieldPtr = cir::PointerType::get(fieldType);
591 unsigned fieldIndex = layout.getCIRFieldNo(field);
592
593 mlir::Value lhsField = builder.createGetMember(
594 loc, fieldPtr, lhsArg, field->getName(), fieldIndex);
595 mlir::Value rhsField = builder.createGetMember(
596 loc, fieldPtr, rhsArg, field->getName(), fieldIndex);
597
598 emitSingleCombiner(lhsField, rhsField, combiner);
599 }
600 }
601
602 } else {
603 // if this is a single-thing (because we should know this isn't an array,
604 // as Sema wouldn't let us get here), we can just do a normal emit call.
605 emitSingleCombiner(lhsArg, rhsArg, combinerRecipes[0]);
606 }
607 };
608
609 if (const auto *cat = cgf.getContext().getAsConstantArrayType(origType)) {
610 // If we're in an array, we have to emit the combiner for each element of
611 // the array.
612 auto itrTy = mlir::cast<cir::IntType>(cgf.ptrDiffTy);
613 auto itrPtrTy = cir::PointerType::get(itrTy);
614
615 mlir::Value zero =
616 builder.getConstInt(loc, mlir::cast<cir::IntType>(cgf.ptrDiffTy), 0);
617 mlir::Value itr = cir::AllocaOp::create(
618 builder, loc, itrPtrTy, "itr", cgf.cgm.getSize(cgf.getPointerAlign()));
619 builder.CIRBaseBuilderTy::createStore(loc, zero, itr);
620
621 builder.setInsertionPointAfter(builder.createFor(
622 loc,
623 /*condBuilder=*/
624 [&](mlir::OpBuilder &b, mlir::Location loc) {
625 auto loadItr = cir::LoadOp::create(builder, loc, {itr});
626 mlir::Value arraySize = builder.getConstInt(
627 loc, mlir::cast<cir::IntType>(cgf.ptrDiffTy), cat->getZExtSize());
628 auto cmp = builder.createCompare(loc, cir::CmpOpKind::lt, loadItr,
629 arraySize);
630 builder.createCondition(cmp);
631 },
632 /*bodyBuilder=*/
633 [&](mlir::OpBuilder &b, mlir::Location loc) {
634 auto loadItr = cir::LoadOp::create(builder, loc, {itr});
635 auto lhsElt = builder.getArrayElement(
636 loc, loc, lhsArg, cgf.convertType(cat->getElementType()), loadItr,
637 /*shouldDecay=*/true);
638 auto rhsElt = builder.getArrayElement(
639 loc, loc, rhsArg, cgf.convertType(cat->getElementType()), loadItr,
640 /*shouldDecay=*/true);
641
642 emitCombiner(lhsElt, rhsElt, cat->getElementType());
643 builder.createYield(loc);
644 },
645 /*stepBuilder=*/
646 [&](mlir::OpBuilder &b, mlir::Location loc) {
647 auto loadItr = cir::LoadOp::create(builder, loc, {itr});
648 auto inc = builder.createInc(loc, loadItr);
649 builder.CIRBaseBuilderTy::createStore(loc, inc, itr);
650 builder.createYield(loc);
651 }));
652
653 } else if (origType->isArrayType()) {
654 cgf.cgm.errorNYI(loc,
655 "OpenACC Reduction combiner non-constant array recipe");
656 } else {
657 emitCombiner(lhsArg, rhsArg, origType);
658 }
659
660 builder.setInsertionPointToEnd(&recipe.getCombinerRegion().back());
661 ls.forceCleanup();
662 mlir::acc::YieldOp::create(builder, locEnd, block->getArgument(0));
663}
664
665} // namespace clang::CIRGen
cir::ConditionOp createCondition(mlir::Value condition)
Create a loop condition.
cir::ForOp createFor(mlir::Location loc, llvm::function_ref< void(mlir::OpBuilder &, mlir::Location)> condBuilder, llvm::function_ref< void(mlir::OpBuilder &, mlir::Location)> bodyBuilder, llvm::function_ref< void(mlir::OpBuilder &, mlir::Location)> stepBuilder)
Create a for operation.
cir::CmpOp createCompare(mlir::Location loc, cir::CmpOpKind kind, mlir::Value lhs, mlir::Value rhs)
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
CanQualType UnsignedLongLongTy
cir::ConstantOp getConstInt(mlir::Location loc, llvm::APSInt intVal)
void forceCleanup(ArrayRef< mlir::Value * > valuesToReload={})
Force the emission of cleanups now, instead of waiting until this object is destroyed.
mlir::Type convertType(clang::QualType t)
void emitAutoVarInit(const AutoVarEmission &emission)
Emit the initializer for an allocated variable.
clang::ASTContext & getContext() const
mlir::Type convertType(clang::QualType type)
mlir::IntegerAttr getSize(CharUnits size)
This class handles record and union layout info while lowering AST types to CIR types.
unsigned getCIRFieldNo(const clang::FieldDecl *fd) const
Return cir::RecordType element number that corresponds to the field FD.
void createReductionRecipeCombiner(mlir::Location loc, mlir::Location locEnd, mlir::Value mainOp, mlir::acc::ReductionRecipeOp recipe, size_t numBounds, QualType origType, llvm::ArrayRef< OpenACCReductionRecipe::CombinerRecipe > combinerRecipes)
void createInitRecipe(mlir::Location loc, mlir::Location locEnd, SourceRange exprRange, mlir::Value mainOp, mlir::Region &recipeInitRegion, size_t numBounds, llvm::ArrayRef< QualType > boundTypes, const VarDecl *allocaDecl, QualType origType, bool emitInitExpr)
void createFirstprivateRecipeCopy(mlir::Location loc, mlir::Location locEnd, mlir::Value mainOp, const VarDecl *allocaDecl, const VarDecl *temporary, mlir::Region &copyRegion, size_t numBounds)
mlir::acc::ReductionOperator convertReductionOp(OpenACCReductionOperator op)
std::pair< mlir::Value, mlir::Value > createBoundsLoop(mlir::Value subscriptedValue, mlir::Value subscriptedValue2, mlir::Value bound, mlir::Location loc, bool inverse)
void createRecipeDestroySection(mlir::Location loc, mlir::Location locEnd, mlir::Value mainOp, CharUnits alignment, QualType origType, size_t numBounds, QualType baseType, mlir::Region &destroyRegion)
mlir::Block * createRecipeBlock(mlir::Region &region, mlir::Type opTy, mlir::Location loc, size_t numBounds, bool isInit)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
A (possibly-)qualified type.
Definition TypeBase.h:937
A trivial tuple used to represent a source range.
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9237
bool isArrayType() const
Definition TypeBase.h:8783
bool isPointerType() const
Definition TypeBase.h:8684
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8807
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:932
const Expr * getInit() const
Definition Decl.h:1391
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
OpenACCReductionOperator
@ Invalid
Invalid Reduction Clause Kind.
bool isa(CodeGen::Address addr)
Definition Address.h:330
U cast(CodeGen::Address addr)
Definition Address.h:327
bool emittedAsOffload
True if the variable was emitted as an offload recipe, and thus doesn't have the same sort of alloca ...
Represents a scope, including function bodies, compound statements, and the substatements of if/while...