1 //===- OpenMPToLLVMIRTranslation.cpp - Translate OpenMP dialect to LLVM IR-===// 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 // This file implements a translation between the MLIR OpenMP dialect and LLVM 10 // IR. 11 // 12 //===----------------------------------------------------------------------===// 13 #include "mlir/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.h" 14 #include "mlir/Dialect/OpenMP/OpenMPDialect.h" 15 #include "mlir/IR/BlockAndValueMapping.h" 16 #include "mlir/IR/Operation.h" 17 #include "mlir/Support/LLVM.h" 18 #include "mlir/Target/LLVMIR/ModuleTranslation.h" 19 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/ADT/TypeSwitch.h" 22 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 23 #include "llvm/IR/IRBuilder.h" 24 25 using namespace mlir; 26 27 namespace { 28 /// ModuleTranslation stack frame for OpenMP operations. This keeps track of the 29 /// insertion points for allocas. 30 class OpenMPAllocaStackFrame 31 : public LLVM::ModuleTranslation::StackFrameBase<OpenMPAllocaStackFrame> { 32 public: 33 explicit OpenMPAllocaStackFrame(llvm::OpenMPIRBuilder::InsertPointTy allocaIP) 34 : allocaInsertPoint(allocaIP) {} 35 llvm::OpenMPIRBuilder::InsertPointTy allocaInsertPoint; 36 }; 37 38 /// ModuleTranslation stack frame containing the partial mapping between MLIR 39 /// values and their LLVM IR equivalents. 40 class OpenMPVarMappingStackFrame 41 : public LLVM::ModuleTranslation::StackFrameBase< 42 OpenMPVarMappingStackFrame> { 43 public: 44 explicit OpenMPVarMappingStackFrame( 45 const DenseMap<Value, llvm::Value *> &mapping) 46 : mapping(mapping) {} 47 48 DenseMap<Value, llvm::Value *> mapping; 49 }; 50 } // namespace 51 52 /// Find the insertion point for allocas given the current insertion point for 53 /// normal operations in the builder. 54 static llvm::OpenMPIRBuilder::InsertPointTy 55 findAllocaInsertPoint(llvm::IRBuilderBase &builder, 56 const LLVM::ModuleTranslation &moduleTranslation) { 57 // If there is an alloca insertion point on stack, i.e. we are in a nested 58 // operation and a specific point was provided by some surrounding operation, 59 // use it. 60 llvm::OpenMPIRBuilder::InsertPointTy allocaInsertPoint; 61 WalkResult walkResult = moduleTranslation.stackWalk<OpenMPAllocaStackFrame>( 62 [&](const OpenMPAllocaStackFrame &frame) { 63 allocaInsertPoint = frame.allocaInsertPoint; 64 return WalkResult::interrupt(); 65 }); 66 if (walkResult.wasInterrupted()) 67 return allocaInsertPoint; 68 69 // Otherwise, insert to the entry block of the surrounding function. 70 llvm::BasicBlock &funcEntryBlock = 71 builder.GetInsertBlock()->getParent()->getEntryBlock(); 72 return llvm::OpenMPIRBuilder::InsertPointTy( 73 &funcEntryBlock, funcEntryBlock.getFirstInsertionPt()); 74 } 75 76 /// Converts the given region that appears within an OpenMP dialect operation to 77 /// LLVM IR, creating a branch from the `sourceBlock` to the entry block of the 78 /// region, and a branch from any block with an successor-less OpenMP terminator 79 /// to `continuationBlock`. Populates `continuationBlockPHIs` with the PHI nodes 80 /// of the continuation block if provided. 81 static void convertOmpOpRegions( 82 Region ®ion, StringRef blockName, llvm::BasicBlock &sourceBlock, 83 llvm::BasicBlock &continuationBlock, llvm::IRBuilderBase &builder, 84 LLVM::ModuleTranslation &moduleTranslation, LogicalResult &bodyGenStatus, 85 SmallVectorImpl<llvm::PHINode *> *continuationBlockPHIs = nullptr) { 86 llvm::LLVMContext &llvmContext = builder.getContext(); 87 for (Block &bb : region) { 88 llvm::BasicBlock *llvmBB = llvm::BasicBlock::Create( 89 llvmContext, blockName, builder.GetInsertBlock()->getParent(), 90 builder.GetInsertBlock()->getNextNode()); 91 moduleTranslation.mapBlock(&bb, llvmBB); 92 } 93 94 llvm::Instruction *sourceTerminator = sourceBlock.getTerminator(); 95 96 // Terminators (namely YieldOp) may be forwarding values to the region that 97 // need to be available in the continuation block. Collect the types of these 98 // operands in preparation of creating PHI nodes. 99 SmallVector<llvm::Type *> continuationBlockPHITypes; 100 bool operandsProcessed = false; 101 unsigned numYields = 0; 102 for (Block &bb : region.getBlocks()) { 103 if (omp::YieldOp yield = dyn_cast<omp::YieldOp>(bb.getTerminator())) { 104 if (!operandsProcessed) { 105 for (unsigned i = 0, e = yield->getNumOperands(); i < e; ++i) { 106 continuationBlockPHITypes.push_back( 107 moduleTranslation.convertType(yield->getOperand(i).getType())); 108 } 109 operandsProcessed = true; 110 } else { 111 assert(continuationBlockPHITypes.size() == yield->getNumOperands() && 112 "mismatching number of values yielded from the region"); 113 for (unsigned i = 0, e = yield->getNumOperands(); i < e; ++i) { 114 llvm::Type *operandType = 115 moduleTranslation.convertType(yield->getOperand(i).getType()); 116 (void)operandType; 117 assert(continuationBlockPHITypes[i] == operandType && 118 "values of mismatching types yielded from the region"); 119 } 120 } 121 numYields++; 122 } 123 } 124 125 // Insert PHI nodes in the continuation block for any values forwarded by the 126 // terminators in this region. 127 if (!continuationBlockPHITypes.empty()) 128 assert( 129 continuationBlockPHIs && 130 "expected continuation block PHIs if converted regions yield values"); 131 if (continuationBlockPHIs) { 132 llvm::IRBuilderBase::InsertPointGuard guard(builder); 133 continuationBlockPHIs->reserve(continuationBlockPHITypes.size()); 134 builder.SetInsertPoint(&continuationBlock, continuationBlock.begin()); 135 for (llvm::Type *ty : continuationBlockPHITypes) 136 continuationBlockPHIs->push_back(builder.CreatePHI(ty, numYields)); 137 } 138 139 // Convert blocks one by one in topological order to ensure 140 // defs are converted before uses. 141 SetVector<Block *> blocks = 142 LLVM::detail::getTopologicallySortedBlocks(region); 143 for (Block *bb : blocks) { 144 llvm::BasicBlock *llvmBB = moduleTranslation.lookupBlock(bb); 145 // Retarget the branch of the entry block to the entry block of the 146 // converted region (regions are single-entry). 147 if (bb->isEntryBlock()) { 148 assert(sourceTerminator->getNumSuccessors() == 1 && 149 "provided entry block has multiple successors"); 150 assert(sourceTerminator->getSuccessor(0) == &continuationBlock && 151 "ContinuationBlock is not the successor of the entry block"); 152 sourceTerminator->setSuccessor(0, llvmBB); 153 } 154 155 llvm::IRBuilderBase::InsertPointGuard guard(builder); 156 if (failed( 157 moduleTranslation.convertBlock(*bb, bb->isEntryBlock(), builder))) { 158 bodyGenStatus = failure(); 159 return; 160 } 161 162 // Special handling for `omp.yield` and `omp.terminator` (we may have more 163 // than one): they return the control to the parent OpenMP dialect operation 164 // so replace them with the branch to the continuation block. We handle this 165 // here to avoid relying inter-function communication through the 166 // ModuleTranslation class to set up the correct insertion point. This is 167 // also consistent with MLIR's idiom of handling special region terminators 168 // in the same code that handles the region-owning operation. 169 Operation *terminator = bb->getTerminator(); 170 if (isa<omp::TerminatorOp, omp::YieldOp>(terminator)) { 171 builder.CreateBr(&continuationBlock); 172 173 for (unsigned i = 0, e = terminator->getNumOperands(); i < e; ++i) 174 (*continuationBlockPHIs)[i]->addIncoming( 175 moduleTranslation.lookupValue(terminator->getOperand(i)), llvmBB); 176 } 177 } 178 // After all blocks have been traversed and values mapped, connect the PHI 179 // nodes to the results of preceding blocks. 180 LLVM::detail::connectPHINodes(region, moduleTranslation); 181 182 // Remove the blocks and values defined in this region from the mapping since 183 // they are not visible outside of this region. This allows the same region to 184 // be converted several times, that is cloned, without clashes, and slightly 185 // speeds up the lookups. 186 moduleTranslation.forgetMapping(region); 187 } 188 189 /// Converts the OpenMP parallel operation to LLVM IR. 190 static LogicalResult 191 convertOmpParallel(Operation &opInst, llvm::IRBuilderBase &builder, 192 LLVM::ModuleTranslation &moduleTranslation) { 193 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 194 // TODO: support error propagation in OpenMPIRBuilder and use it instead of 195 // relying on captured variables. 196 LogicalResult bodyGenStatus = success(); 197 198 auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP, 199 llvm::BasicBlock &continuationBlock) { 200 // Save the alloca insertion point on ModuleTranslation stack for use in 201 // nested regions. 202 LLVM::ModuleTranslation::SaveStack<OpenMPAllocaStackFrame> frame( 203 moduleTranslation, allocaIP); 204 205 // ParallelOp has only one region associated with it. 206 auto ®ion = cast<omp::ParallelOp>(opInst).getRegion(); 207 convertOmpOpRegions(region, "omp.par.region", *codeGenIP.getBlock(), 208 continuationBlock, builder, moduleTranslation, 209 bodyGenStatus); 210 }; 211 212 // TODO: Perform appropriate actions according to the data-sharing 213 // attribute (shared, private, firstprivate, ...) of variables. 214 // Currently defaults to shared. 215 auto privCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP, 216 llvm::Value &, llvm::Value &vPtr, 217 llvm::Value *&replacementValue) -> InsertPointTy { 218 replacementValue = &vPtr; 219 220 return codeGenIP; 221 }; 222 223 // TODO: Perform finalization actions for variables. This has to be 224 // called for variables which have destructors/finalizers. 225 auto finiCB = [&](InsertPointTy codeGenIP) {}; 226 227 llvm::Value *ifCond = nullptr; 228 if (auto ifExprVar = cast<omp::ParallelOp>(opInst).if_expr_var()) 229 ifCond = moduleTranslation.lookupValue(ifExprVar); 230 llvm::Value *numThreads = nullptr; 231 if (auto numThreadsVar = cast<omp::ParallelOp>(opInst).num_threads_var()) 232 numThreads = moduleTranslation.lookupValue(numThreadsVar); 233 llvm::omp::ProcBindKind pbKind = llvm::omp::OMP_PROC_BIND_default; 234 if (auto bind = cast<omp::ParallelOp>(opInst).proc_bind_val()) 235 pbKind = llvm::omp::getProcBindKind(bind.getValue()); 236 // TODO: Is the Parallel construct cancellable? 237 bool isCancellable = false; 238 239 llvm::OpenMPIRBuilder::LocationDescription ompLoc( 240 builder.saveIP(), builder.getCurrentDebugLocation()); 241 builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createParallel( 242 ompLoc, findAllocaInsertPoint(builder, moduleTranslation), bodyGenCB, 243 privCB, finiCB, ifCond, numThreads, pbKind, isCancellable)); 244 245 return bodyGenStatus; 246 } 247 248 /// Converts an OpenMP 'master' operation into LLVM IR using OpenMPIRBuilder. 249 static LogicalResult 250 convertOmpMaster(Operation &opInst, llvm::IRBuilderBase &builder, 251 LLVM::ModuleTranslation &moduleTranslation) { 252 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 253 // TODO: support error propagation in OpenMPIRBuilder and use it instead of 254 // relying on captured variables. 255 LogicalResult bodyGenStatus = success(); 256 257 auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP, 258 llvm::BasicBlock &continuationBlock) { 259 // MasterOp has only one region associated with it. 260 auto ®ion = cast<omp::MasterOp>(opInst).getRegion(); 261 convertOmpOpRegions(region, "omp.master.region", *codeGenIP.getBlock(), 262 continuationBlock, builder, moduleTranslation, 263 bodyGenStatus); 264 }; 265 266 // TODO: Perform finalization actions for variables. This has to be 267 // called for variables which have destructors/finalizers. 268 auto finiCB = [&](InsertPointTy codeGenIP) {}; 269 270 llvm::OpenMPIRBuilder::LocationDescription ompLoc( 271 builder.saveIP(), builder.getCurrentDebugLocation()); 272 builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createMaster( 273 ompLoc, bodyGenCB, finiCB)); 274 return success(); 275 } 276 277 /// Converts an OpenMP 'critical' operation into LLVM IR using OpenMPIRBuilder. 278 static LogicalResult 279 convertOmpCritical(Operation &opInst, llvm::IRBuilderBase &builder, 280 LLVM::ModuleTranslation &moduleTranslation) { 281 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 282 auto criticalOp = cast<omp::CriticalOp>(opInst); 283 // TODO: support error propagation in OpenMPIRBuilder and use it instead of 284 // relying on captured variables. 285 LogicalResult bodyGenStatus = success(); 286 287 auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP, 288 llvm::BasicBlock &continuationBlock) { 289 // CriticalOp has only one region associated with it. 290 auto ®ion = cast<omp::CriticalOp>(opInst).getRegion(); 291 convertOmpOpRegions(region, "omp.critical.region", *codeGenIP.getBlock(), 292 continuationBlock, builder, moduleTranslation, 293 bodyGenStatus); 294 }; 295 296 // TODO: Perform finalization actions for variables. This has to be 297 // called for variables which have destructors/finalizers. 298 auto finiCB = [&](InsertPointTy codeGenIP) {}; 299 300 llvm::OpenMPIRBuilder::LocationDescription ompLoc( 301 builder.saveIP(), builder.getCurrentDebugLocation()); 302 llvm::LLVMContext &llvmContext = moduleTranslation.getLLVMContext(); 303 llvm::Constant *hint = nullptr; 304 if (criticalOp.hint().hasValue()) { 305 hint = 306 llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvmContext), 307 static_cast<int>(criticalOp.hint().getValue())); 308 } else { 309 hint = llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvmContext), 0); 310 } 311 builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createCritical( 312 ompLoc, bodyGenCB, finiCB, criticalOp.name().getValueOr(""), hint)); 313 return success(); 314 } 315 316 /// Returns a reduction declaration that corresponds to the given reduction 317 /// operation in the given container. Currently only supports reductions inside 318 /// WsLoopOp but can be easily extended. 319 static omp::ReductionDeclareOp findReductionDecl(omp::WsLoopOp container, 320 omp::ReductionOp reduction) { 321 SymbolRefAttr reductionSymbol; 322 for (unsigned i = 0, e = container.getNumReductionVars(); i < e; ++i) { 323 if (container.reduction_vars()[i] != reduction.accumulator()) 324 continue; 325 reductionSymbol = (*container.reductions())[i].cast<SymbolRefAttr>(); 326 break; 327 } 328 assert(reductionSymbol && 329 "reduction operation must be associated with a declaration"); 330 331 return SymbolTable::lookupNearestSymbolFrom<omp::ReductionDeclareOp>( 332 container, reductionSymbol); 333 } 334 335 /// Populates `reductions` with reduction declarations used in the given loop. 336 static void 337 collectReductionDecls(omp::WsLoopOp loop, 338 SmallVectorImpl<omp::ReductionDeclareOp> &reductions) { 339 Optional<ArrayAttr> attr = loop.reductions(); 340 if (!attr) 341 return; 342 343 reductions.reserve(reductions.size() + loop.getNumReductionVars()); 344 for (auto symbolRef : attr->getAsRange<SymbolRefAttr>()) { 345 reductions.push_back( 346 SymbolTable::lookupNearestSymbolFrom<omp::ReductionDeclareOp>( 347 loop, symbolRef)); 348 } 349 } 350 351 /// Translates the blocks contained in the given region and appends them to at 352 /// the current insertion point of `builder`. The operations of the entry block 353 /// are appended to the current insertion block, which is not expected to have a 354 /// terminator. If set, `continuationBlockArgs` is populated with translated 355 /// values that correspond to the values omp.yield'ed from the region. 356 static LogicalResult inlineConvertOmpRegions( 357 Region ®ion, StringRef blockName, llvm::IRBuilderBase &builder, 358 LLVM::ModuleTranslation &moduleTranslation, 359 SmallVectorImpl<llvm::Value *> *continuationBlockArgs = nullptr) { 360 if (region.empty()) 361 return success(); 362 363 // Special case for single-block regions that don't create additional blocks: 364 // insert operations without creating additional blocks. 365 if (llvm::hasSingleElement(region)) { 366 moduleTranslation.mapBlock(®ion.front(), builder.GetInsertBlock()); 367 if (failed(moduleTranslation.convertBlock( 368 region.front(), /*ignoreArguments=*/true, builder))) 369 return failure(); 370 371 // The continuation arguments are simply the translated terminator operands. 372 if (continuationBlockArgs) 373 llvm::append_range( 374 *continuationBlockArgs, 375 moduleTranslation.lookupValues(region.front().back().getOperands())); 376 377 // Drop the mapping that is no longer necessary so that the same region can 378 // be processed multiple times. 379 moduleTranslation.forgetMapping(region); 380 return success(); 381 } 382 383 // Create the continuation block manually instead of calling splitBlock 384 // because the current insertion block may not have a terminator. 385 llvm::BasicBlock *continuationBlock = 386 llvm::BasicBlock::Create(builder.getContext(), blockName + ".cont", 387 builder.GetInsertBlock()->getParent(), 388 builder.GetInsertBlock()->getNextNode()); 389 builder.CreateBr(continuationBlock); 390 391 LogicalResult bodyGenStatus = success(); 392 SmallVector<llvm::PHINode *> phis; 393 convertOmpOpRegions(region, blockName, *builder.GetInsertBlock(), 394 *continuationBlock, builder, moduleTranslation, 395 bodyGenStatus, &phis); 396 if (failed(bodyGenStatus)) 397 return failure(); 398 if (continuationBlockArgs) 399 llvm::append_range(*continuationBlockArgs, phis); 400 builder.SetInsertPoint(continuationBlock, 401 continuationBlock->getFirstInsertionPt()); 402 return success(); 403 } 404 405 namespace { 406 /// Owning equivalents of OpenMPIRBuilder::(Atomic)ReductionGen that are used to 407 /// store lambdas with capture. 408 using OwningReductionGen = std::function<llvm::OpenMPIRBuilder::InsertPointTy( 409 llvm::OpenMPIRBuilder::InsertPointTy, llvm::Value *, llvm::Value *, 410 llvm::Value *&)>; 411 using OwningAtomicReductionGen = 412 std::function<llvm::OpenMPIRBuilder::InsertPointTy( 413 llvm::OpenMPIRBuilder::InsertPointTy, llvm::Value *, llvm::Value *)>; 414 } // namespace 415 416 /// Create an OpenMPIRBuilder-compatible reduction generator for the given 417 /// reduction declaration. The generator uses `builder` but ignores its 418 /// insertion point. 419 static OwningReductionGen 420 makeReductionGen(omp::ReductionDeclareOp decl, llvm::IRBuilderBase &builder, 421 LLVM::ModuleTranslation &moduleTranslation) { 422 // The lambda is mutable because we need access to non-const methods of decl 423 // (which aren't actually mutating it), and we must capture decl by-value to 424 // avoid the dangling reference after the parent function returns. 425 OwningReductionGen gen = 426 [&, decl](llvm::OpenMPIRBuilder::InsertPointTy insertPoint, 427 llvm::Value *lhs, llvm::Value *rhs, 428 llvm::Value *&result) mutable { 429 Region &reductionRegion = decl.reductionRegion(); 430 moduleTranslation.mapValue(reductionRegion.front().getArgument(0), lhs); 431 moduleTranslation.mapValue(reductionRegion.front().getArgument(1), rhs); 432 builder.restoreIP(insertPoint); 433 SmallVector<llvm::Value *> phis; 434 if (failed(inlineConvertOmpRegions(reductionRegion, 435 "omp.reduction.nonatomic.body", 436 builder, moduleTranslation, &phis))) 437 return llvm::OpenMPIRBuilder::InsertPointTy(); 438 assert(phis.size() == 1); 439 result = phis[0]; 440 return builder.saveIP(); 441 }; 442 return gen; 443 } 444 445 /// Create an OpenMPIRBuilder-compatible atomic reduction generator for the 446 /// given reduction declaration. The generator uses `builder` but ignores its 447 /// insertion point. Returns null if there is no atomic region available in the 448 /// reduction declaration. 449 static OwningAtomicReductionGen 450 makeAtomicReductionGen(omp::ReductionDeclareOp decl, 451 llvm::IRBuilderBase &builder, 452 LLVM::ModuleTranslation &moduleTranslation) { 453 if (decl.atomicReductionRegion().empty()) 454 return OwningAtomicReductionGen(); 455 456 // The lambda is mutable because we need access to non-const methods of decl 457 // (which aren't actually mutating it), and we must capture decl by-value to 458 // avoid the dangling reference after the parent function returns. 459 OwningAtomicReductionGen atomicGen = 460 [&, decl](llvm::OpenMPIRBuilder::InsertPointTy insertPoint, 461 llvm::Value *lhs, llvm::Value *rhs) mutable { 462 Region &atomicRegion = decl.atomicReductionRegion(); 463 moduleTranslation.mapValue(atomicRegion.front().getArgument(0), lhs); 464 moduleTranslation.mapValue(atomicRegion.front().getArgument(1), rhs); 465 builder.restoreIP(insertPoint); 466 SmallVector<llvm::Value *> phis; 467 if (failed(inlineConvertOmpRegions(atomicRegion, 468 "omp.reduction.atomic.body", builder, 469 moduleTranslation, &phis))) 470 return llvm::OpenMPIRBuilder::InsertPointTy(); 471 assert(phis.empty()); 472 return builder.saveIP(); 473 }; 474 return atomicGen; 475 } 476 477 /// Converts an OpenMP workshare loop into LLVM IR using OpenMPIRBuilder. 478 static LogicalResult 479 convertOmpWsLoop(Operation &opInst, llvm::IRBuilderBase &builder, 480 LLVM::ModuleTranslation &moduleTranslation) { 481 auto loop = cast<omp::WsLoopOp>(opInst); 482 // TODO: this should be in the op verifier instead. 483 if (loop.lowerBound().empty()) 484 return failure(); 485 486 // Static is the default. 487 omp::ClauseScheduleKind schedule = omp::ClauseScheduleKind::Static; 488 if (loop.schedule_val().hasValue()) 489 schedule = 490 *omp::symbolizeClauseScheduleKind(loop.schedule_val().getValue()); 491 492 // Find the loop configuration. 493 llvm::Value *step = moduleTranslation.lookupValue(loop.step()[0]); 494 llvm::Type *ivType = step->getType(); 495 llvm::Value *chunk = 496 loop.schedule_chunk_var() 497 ? moduleTranslation.lookupValue(loop.schedule_chunk_var()) 498 : llvm::ConstantInt::get(ivType, 1); 499 500 SmallVector<omp::ReductionDeclareOp> reductionDecls; 501 collectReductionDecls(loop, reductionDecls); 502 llvm::OpenMPIRBuilder::InsertPointTy allocaIP = 503 findAllocaInsertPoint(builder, moduleTranslation); 504 505 // Allocate space for privatized reduction variables. 506 SmallVector<llvm::Value *> privateReductionVariables; 507 DenseMap<Value, llvm::Value *> reductionVariableMap; 508 unsigned numReductions = loop.getNumReductionVars(); 509 privateReductionVariables.reserve(numReductions); 510 if (numReductions != 0) { 511 llvm::IRBuilderBase::InsertPointGuard guard(builder); 512 builder.restoreIP(allocaIP); 513 for (unsigned i = 0; i < numReductions; ++i) { 514 auto reductionType = 515 loop.reduction_vars()[i].getType().cast<LLVM::LLVMPointerType>(); 516 llvm::Value *var = builder.CreateAlloca( 517 moduleTranslation.convertType(reductionType.getElementType())); 518 privateReductionVariables.push_back(var); 519 reductionVariableMap.try_emplace(loop.reduction_vars()[i], var); 520 } 521 } 522 523 // Store the mapping between reduction variables and their private copies on 524 // ModuleTranslation stack. It can be then recovered when translating 525 // omp.reduce operations in a separate call. 526 LLVM::ModuleTranslation::SaveStack<OpenMPVarMappingStackFrame> mappingGuard( 527 moduleTranslation, reductionVariableMap); 528 529 // Before the loop, store the initial values of reductions into reduction 530 // variables. Although this could be done after allocas, we don't want to mess 531 // up with the alloca insertion point. 532 for (unsigned i = 0; i < numReductions; ++i) { 533 SmallVector<llvm::Value *> phis; 534 if (failed(inlineConvertOmpRegions(reductionDecls[i].initializerRegion(), 535 "omp.reduction.neutral", builder, 536 moduleTranslation, &phis))) 537 return failure(); 538 assert(phis.size() == 1 && "expected one value to be yielded from the " 539 "reduction neutral element declaration region"); 540 builder.CreateStore(phis[0], privateReductionVariables[i]); 541 } 542 543 // Set up the source location value for OpenMP runtime. 544 llvm::DISubprogram *subprogram = 545 builder.GetInsertBlock()->getParent()->getSubprogram(); 546 const llvm::DILocation *diLoc = 547 moduleTranslation.translateLoc(opInst.getLoc(), subprogram); 548 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder.saveIP(), 549 llvm::DebugLoc(diLoc)); 550 551 // Generator of the canonical loop body. 552 // TODO: support error propagation in OpenMPIRBuilder and use it instead of 553 // relying on captured variables. 554 SmallVector<llvm::CanonicalLoopInfo *> loopInfos; 555 SmallVector<llvm::OpenMPIRBuilder::InsertPointTy> bodyInsertPoints; 556 LogicalResult bodyGenStatus = success(); 557 auto bodyGen = [&](llvm::OpenMPIRBuilder::InsertPointTy ip, llvm::Value *iv) { 558 // Make sure further conversions know about the induction variable. 559 moduleTranslation.mapValue( 560 loop.getRegion().front().getArgument(loopInfos.size()), iv); 561 562 // Capture the body insertion point for use in nested loops. BodyIP of the 563 // CanonicalLoopInfo always points to the beginning of the entry block of 564 // the body. 565 bodyInsertPoints.push_back(ip); 566 567 if (loopInfos.size() != loop.getNumLoops() - 1) 568 return; 569 570 // Convert the body of the loop. 571 llvm::BasicBlock *entryBlock = ip.getBlock(); 572 llvm::BasicBlock *exitBlock = 573 entryBlock->splitBasicBlock(ip.getPoint(), "omp.wsloop.exit"); 574 convertOmpOpRegions(loop.region(), "omp.wsloop.region", *entryBlock, 575 *exitBlock, builder, moduleTranslation, bodyGenStatus); 576 }; 577 578 // Delegate actual loop construction to the OpenMP IRBuilder. 579 // TODO: this currently assumes WsLoop is semantically similar to SCF loop, 580 // i.e. it has a positive step, uses signed integer semantics. Reconsider 581 // this code when WsLoop clearly supports more cases. 582 llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder(); 583 for (unsigned i = 0, e = loop.getNumLoops(); i < e; ++i) { 584 llvm::Value *lowerBound = 585 moduleTranslation.lookupValue(loop.lowerBound()[i]); 586 llvm::Value *upperBound = 587 moduleTranslation.lookupValue(loop.upperBound()[i]); 588 llvm::Value *step = moduleTranslation.lookupValue(loop.step()[i]); 589 590 // Make sure loop trip count are emitted in the preheader of the outermost 591 // loop at the latest so that they are all available for the new collapsed 592 // loop will be created below. 593 llvm::OpenMPIRBuilder::LocationDescription loc = ompLoc; 594 llvm::OpenMPIRBuilder::InsertPointTy computeIP = ompLoc.IP; 595 if (i != 0) { 596 loc = llvm::OpenMPIRBuilder::LocationDescription(bodyInsertPoints.back(), 597 llvm::DebugLoc(diLoc)); 598 computeIP = loopInfos.front()->getPreheaderIP(); 599 } 600 loopInfos.push_back(ompBuilder->createCanonicalLoop( 601 loc, bodyGen, lowerBound, upperBound, step, 602 /*IsSigned=*/true, loop.inclusive(), computeIP)); 603 604 if (failed(bodyGenStatus)) 605 return failure(); 606 } 607 608 // Collapse loops. Store the insertion point because LoopInfos may get 609 // invalidated. 610 llvm::IRBuilderBase::InsertPoint afterIP = loopInfos.front()->getAfterIP(); 611 llvm::CanonicalLoopInfo *loopInfo = 612 ompBuilder->collapseLoops(diLoc, loopInfos, {}); 613 614 allocaIP = findAllocaInsertPoint(builder, moduleTranslation); 615 if (schedule == omp::ClauseScheduleKind::Static) { 616 ompBuilder->applyStaticWorkshareLoop(ompLoc.DL, loopInfo, allocaIP, 617 !loop.nowait(), chunk); 618 } else { 619 llvm::omp::OMPScheduleType schedType; 620 switch (schedule) { 621 case omp::ClauseScheduleKind::Dynamic: 622 schedType = llvm::omp::OMPScheduleType::DynamicChunked; 623 break; 624 case omp::ClauseScheduleKind::Guided: 625 schedType = llvm::omp::OMPScheduleType::GuidedChunked; 626 break; 627 case omp::ClauseScheduleKind::Auto: 628 schedType = llvm::omp::OMPScheduleType::Auto; 629 break; 630 case omp::ClauseScheduleKind::Runtime: 631 schedType = llvm::omp::OMPScheduleType::Runtime; 632 break; 633 default: 634 llvm_unreachable("Unknown schedule value"); 635 break; 636 } 637 638 ompBuilder->applyDynamicWorkshareLoop(ompLoc.DL, loopInfo, allocaIP, 639 schedType, !loop.nowait(), chunk); 640 } 641 642 // Continue building IR after the loop. Note that the LoopInfo returned by 643 // `collapseLoops` points inside the outermost loop and is intended for 644 // potential further loop transformations. Use the insertion point stored 645 // before collapsing loops instead. 646 builder.restoreIP(afterIP); 647 648 // Process the reductions if required. 649 if (numReductions == 0) 650 return success(); 651 652 // Create the reduction generators. We need to own them here because 653 // ReductionInfo only accepts references to the generators. 654 SmallVector<OwningReductionGen> owningReductionGens; 655 SmallVector<OwningAtomicReductionGen> owningAtomicReductionGens; 656 for (unsigned i = 0; i < numReductions; ++i) { 657 owningReductionGens.push_back( 658 makeReductionGen(reductionDecls[i], builder, moduleTranslation)); 659 owningAtomicReductionGens.push_back( 660 makeAtomicReductionGen(reductionDecls[i], builder, moduleTranslation)); 661 } 662 663 // Collect the reduction information. 664 SmallVector<llvm::OpenMPIRBuilder::ReductionInfo> reductionInfos; 665 reductionInfos.reserve(numReductions); 666 for (unsigned i = 0; i < numReductions; ++i) { 667 llvm::OpenMPIRBuilder::AtomicReductionGenTy atomicGen = nullptr; 668 if (owningAtomicReductionGens[i]) 669 atomicGen = owningAtomicReductionGens[i]; 670 reductionInfos.push_back( 671 {moduleTranslation.lookupValue(loop.reduction_vars()[i]), 672 privateReductionVariables[i], owningReductionGens[i], atomicGen}); 673 } 674 675 // The call to createReductions below expects the block to have a 676 // terminator. Create an unreachable instruction to serve as terminator 677 // and remove it later. 678 llvm::UnreachableInst *tempTerminator = builder.CreateUnreachable(); 679 builder.SetInsertPoint(tempTerminator); 680 llvm::OpenMPIRBuilder::InsertPointTy contInsertPoint = 681 ompBuilder->createReductions(builder.saveIP(), allocaIP, reductionInfos, 682 loop.nowait()); 683 if (!contInsertPoint.getBlock()) 684 return loop->emitOpError() << "failed to convert reductions"; 685 auto nextInsertionPoint = 686 ompBuilder->createBarrier(contInsertPoint, llvm::omp::OMPD_for); 687 tempTerminator->eraseFromParent(); 688 builder.restoreIP(nextInsertionPoint); 689 690 return success(); 691 } 692 693 /// Converts an OpenMP reduction operation using OpenMPIRBuilder. Expects the 694 /// mapping between reduction variables and their private equivalents to have 695 /// been stored on the ModuleTranslation stack. Currently only supports 696 /// reduction within WsLoopOp, but can be easily extended. 697 static LogicalResult 698 convertOmpReductionOp(omp::ReductionOp reductionOp, 699 llvm::IRBuilderBase &builder, 700 LLVM::ModuleTranslation &moduleTranslation) { 701 // Find the declaration that corresponds to the reduction op. 702 auto reductionContainer = reductionOp->getParentOfType<omp::WsLoopOp>(); 703 omp::ReductionDeclareOp declaration = 704 findReductionDecl(reductionContainer, reductionOp); 705 assert(declaration && "could not find reduction declaration"); 706 707 // Retrieve the mapping between reduction variables and their private 708 // equivalents. 709 const DenseMap<Value, llvm::Value *> *reductionVariableMap = nullptr; 710 moduleTranslation.stackWalk<OpenMPVarMappingStackFrame>( 711 [&](const OpenMPVarMappingStackFrame &frame) { 712 reductionVariableMap = &frame.mapping; 713 return WalkResult::interrupt(); 714 }); 715 assert(reductionVariableMap && "couldn't find private reduction variables"); 716 717 // Translate the reduction operation by emitting the body of the corresponding 718 // reduction declaration. 719 Region &reductionRegion = declaration.reductionRegion(); 720 llvm::Value *privateReductionVar = 721 reductionVariableMap->lookup(reductionOp.accumulator()); 722 llvm::Value *reductionVal = builder.CreateLoad( 723 moduleTranslation.convertType(reductionOp.operand().getType()), 724 privateReductionVar); 725 726 moduleTranslation.mapValue(reductionRegion.front().getArgument(0), 727 reductionVal); 728 moduleTranslation.mapValue( 729 reductionRegion.front().getArgument(1), 730 moduleTranslation.lookupValue(reductionOp.operand())); 731 732 SmallVector<llvm::Value *> phis; 733 if (failed(inlineConvertOmpRegions(reductionRegion, "omp.reduction.body", 734 builder, moduleTranslation, &phis))) 735 return failure(); 736 assert(phis.size() == 1 && "expected one value to be yielded from " 737 "the reduction body declaration region"); 738 builder.CreateStore(phis[0], privateReductionVar); 739 return success(); 740 } 741 742 namespace { 743 744 /// Implementation of the dialect interface that converts operations belonging 745 /// to the OpenMP dialect to LLVM IR. 746 class OpenMPDialectLLVMIRTranslationInterface 747 : public LLVMTranslationDialectInterface { 748 public: 749 using LLVMTranslationDialectInterface::LLVMTranslationDialectInterface; 750 751 /// Translates the given operation to LLVM IR using the provided IR builder 752 /// and saving the state in `moduleTranslation`. 753 LogicalResult 754 convertOperation(Operation *op, llvm::IRBuilderBase &builder, 755 LLVM::ModuleTranslation &moduleTranslation) const final; 756 }; 757 758 } // end namespace 759 760 /// Given an OpenMP MLIR operation, create the corresponding LLVM IR 761 /// (including OpenMP runtime calls). 762 LogicalResult OpenMPDialectLLVMIRTranslationInterface::convertOperation( 763 Operation *op, llvm::IRBuilderBase &builder, 764 LLVM::ModuleTranslation &moduleTranslation) const { 765 766 llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder(); 767 768 return llvm::TypeSwitch<Operation *, LogicalResult>(op) 769 .Case([&](omp::BarrierOp) { 770 ompBuilder->createBarrier(builder.saveIP(), llvm::omp::OMPD_barrier); 771 return success(); 772 }) 773 .Case([&](omp::TaskwaitOp) { 774 ompBuilder->createTaskwait(builder.saveIP()); 775 return success(); 776 }) 777 .Case([&](omp::TaskyieldOp) { 778 ompBuilder->createTaskyield(builder.saveIP()); 779 return success(); 780 }) 781 .Case([&](omp::FlushOp) { 782 // No support in Openmp runtime function (__kmpc_flush) to accept 783 // the argument list. 784 // OpenMP standard states the following: 785 // "An implementation may implement a flush with a list by ignoring 786 // the list, and treating it the same as a flush without a list." 787 // 788 // The argument list is discarded so that, flush with a list is treated 789 // same as a flush without a list. 790 ompBuilder->createFlush(builder.saveIP()); 791 return success(); 792 }) 793 .Case([&](omp::ParallelOp) { 794 return convertOmpParallel(*op, builder, moduleTranslation); 795 }) 796 .Case([&](omp::ReductionOp reductionOp) { 797 return convertOmpReductionOp(reductionOp, builder, moduleTranslation); 798 }) 799 .Case([&](omp::MasterOp) { 800 return convertOmpMaster(*op, builder, moduleTranslation); 801 }) 802 .Case([&](omp::CriticalOp) { 803 return convertOmpCritical(*op, builder, moduleTranslation); 804 }) 805 .Case([&](omp::WsLoopOp) { 806 return convertOmpWsLoop(*op, builder, moduleTranslation); 807 }) 808 .Case<omp::YieldOp, omp::TerminatorOp, omp::ReductionDeclareOp, 809 omp::CriticalDeclareOp>([](auto op) { 810 // `yield` and `terminator` can be just omitted. The block structure 811 // was created in the region that handles their parent operation. 812 // `reduction.declare` will be used by reductions and is not 813 // converted directly, skip it. 814 // `critical.declare` is only used to declare names of critical 815 // sections which will be used by `critical` ops and hence can be 816 // ignored for lowering. The OpenMP IRBuilder will create unique 817 // name for critical section names. 818 return success(); 819 }) 820 .Default([&](Operation *inst) { 821 return inst->emitError("unsupported OpenMP operation: ") 822 << inst->getName(); 823 }); 824 } 825 826 void mlir::registerOpenMPDialectTranslation(DialectRegistry ®istry) { 827 registry.insert<omp::OpenMPDialect>(); 828 registry.addDialectInterface<omp::OpenMPDialect, 829 OpenMPDialectLLVMIRTranslationInterface>(); 830 } 831 832 void mlir::registerOpenMPDialectTranslation(MLIRContext &context) { 833 DialectRegistry registry; 834 registerOpenMPDialectTranslation(registry); 835 context.appendDialectRegistry(registry); 836 } 837