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