1 //===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This contains code to emit OpenMP nodes as LLVM code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CGOpenMPRuntime.h" 15 #include "CodeGenFunction.h" 16 #include "CodeGenModule.h" 17 #include "TargetInfo.h" 18 #include "clang/AST/Stmt.h" 19 #include "clang/AST/StmtOpenMP.h" 20 using namespace clang; 21 using namespace CodeGen; 22 23 //===----------------------------------------------------------------------===// 24 // OpenMP Directive Emission 25 //===----------------------------------------------------------------------===// 26 void CodeGenFunction::EmitOMPAggregateAssign( 27 llvm::Value *DestAddr, llvm::Value *SrcAddr, QualType OriginalType, 28 const llvm::function_ref<void(llvm::Value *, llvm::Value *)> &CopyGen) { 29 // Perform element-by-element initialization. 30 QualType ElementTy; 31 auto SrcBegin = SrcAddr; 32 auto DestBegin = DestAddr; 33 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe(); 34 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestBegin); 35 // Cast from pointer to array type to pointer to single element. 36 SrcBegin = Builder.CreatePointerBitCastOrAddrSpaceCast(SrcBegin, 37 DestBegin->getType()); 38 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements); 39 // The basic structure here is a while-do loop. 40 auto BodyBB = createBasicBlock("omp.arraycpy.body"); 41 auto DoneBB = createBasicBlock("omp.arraycpy.done"); 42 auto IsEmpty = 43 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty"); 44 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB); 45 46 // Enter the loop body, making that address the current address. 47 auto EntryBB = Builder.GetInsertBlock(); 48 EmitBlock(BodyBB); 49 auto SrcElementCurrent = 50 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast"); 51 SrcElementCurrent->addIncoming(SrcBegin, EntryBB); 52 auto DestElementCurrent = Builder.CreatePHI(DestBegin->getType(), 2, 53 "omp.arraycpy.destElementPast"); 54 DestElementCurrent->addIncoming(DestBegin, EntryBB); 55 56 // Emit copy. 57 CopyGen(DestElementCurrent, SrcElementCurrent); 58 59 // Shift the address forward by one element. 60 auto DestElementNext = Builder.CreateConstGEP1_32( 61 DestElementCurrent, /*Idx0=*/1, "omp.arraycpy.dest.element"); 62 auto SrcElementNext = Builder.CreateConstGEP1_32( 63 SrcElementCurrent, /*Idx0=*/1, "omp.arraycpy.src.element"); 64 // Check whether we've reached the end. 65 auto Done = 66 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done"); 67 Builder.CreateCondBr(Done, DoneBB, BodyBB); 68 DestElementCurrent->addIncoming(DestElementNext, Builder.GetInsertBlock()); 69 SrcElementCurrent->addIncoming(SrcElementNext, Builder.GetInsertBlock()); 70 71 // Done. 72 EmitBlock(DoneBB, /*IsFinished=*/true); 73 } 74 75 void CodeGenFunction::EmitOMPCopy(CodeGenFunction &CGF, 76 QualType OriginalType, llvm::Value *DestAddr, 77 llvm::Value *SrcAddr, const VarDecl *DestVD, 78 const VarDecl *SrcVD, const Expr *Copy) { 79 if (OriginalType->isArrayType()) { 80 auto *BO = dyn_cast<BinaryOperator>(Copy); 81 if (BO && BO->getOpcode() == BO_Assign) { 82 // Perform simple memcpy for simple copying. 83 CGF.EmitAggregateAssign(DestAddr, SrcAddr, OriginalType); 84 } else { 85 // For arrays with complex element types perform element by element 86 // copying. 87 CGF.EmitOMPAggregateAssign( 88 DestAddr, SrcAddr, OriginalType, 89 [&CGF, Copy, SrcVD, DestVD](llvm::Value *DestElement, 90 llvm::Value *SrcElement) { 91 // Working with the single array element, so have to remap 92 // destination and source variables to corresponding array 93 // elements. 94 CodeGenFunction::OMPPrivateScope Remap(CGF); 95 Remap.addPrivate(DestVD, [DestElement]() -> llvm::Value *{ 96 return DestElement; 97 }); 98 Remap.addPrivate( 99 SrcVD, [SrcElement]() -> llvm::Value *{ return SrcElement; }); 100 (void)Remap.Privatize(); 101 CGF.EmitIgnoredExpr(Copy); 102 }); 103 } 104 } else { 105 // Remap pseudo source variable to private copy. 106 CodeGenFunction::OMPPrivateScope Remap(CGF); 107 Remap.addPrivate(SrcVD, [SrcAddr]() -> llvm::Value *{ return SrcAddr; }); 108 Remap.addPrivate(DestVD, [DestAddr]() -> llvm::Value *{ return DestAddr; }); 109 (void)Remap.Privatize(); 110 // Emit copying of the whole variable. 111 CGF.EmitIgnoredExpr(Copy); 112 } 113 } 114 115 bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D, 116 OMPPrivateScope &PrivateScope) { 117 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate; 118 for (auto &&I = D.getClausesOfKind(OMPC_firstprivate); I; ++I) { 119 auto *C = cast<OMPFirstprivateClause>(*I); 120 auto IRef = C->varlist_begin(); 121 auto InitsRef = C->inits().begin(); 122 for (auto IInit : C->private_copies()) { 123 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 124 if (EmittedAsFirstprivate.count(OrigVD) == 0) { 125 EmittedAsFirstprivate.insert(OrigVD); 126 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl()); 127 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl()); 128 bool IsRegistered; 129 DeclRefExpr DRE( 130 const_cast<VarDecl *>(OrigVD), 131 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup( 132 OrigVD) != nullptr, 133 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc()); 134 auto *OriginalAddr = EmitLValue(&DRE).getAddress(); 135 QualType Type = OrigVD->getType(); 136 if (Type->isArrayType()) { 137 // Emit VarDecl with copy init for arrays. 138 // Get the address of the original variable captured in current 139 // captured region. 140 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{ 141 auto Emission = EmitAutoVarAlloca(*VD); 142 auto *Init = VD->getInit(); 143 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) { 144 // Perform simple memcpy. 145 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr, 146 Type); 147 } else { 148 EmitOMPAggregateAssign( 149 Emission.getAllocatedAddress(), OriginalAddr, Type, 150 [this, VDInit, Init](llvm::Value *DestElement, 151 llvm::Value *SrcElement) { 152 // Clean up any temporaries needed by the initialization. 153 RunCleanupsScope InitScope(*this); 154 // Emit initialization for single element. 155 LocalDeclMap[VDInit] = SrcElement; 156 EmitAnyExprToMem(Init, DestElement, 157 Init->getType().getQualifiers(), 158 /*IsInitializer*/ false); 159 LocalDeclMap.erase(VDInit); 160 }); 161 } 162 EmitAutoVarCleanups(Emission); 163 return Emission.getAllocatedAddress(); 164 }); 165 } else { 166 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{ 167 // Emit private VarDecl with copy init. 168 // Remap temp VDInit variable to the address of the original 169 // variable 170 // (for proper handling of captured global variables). 171 LocalDeclMap[VDInit] = OriginalAddr; 172 EmitDecl(*VD); 173 LocalDeclMap.erase(VDInit); 174 return GetAddrOfLocalVar(VD); 175 }); 176 } 177 assert(IsRegistered && 178 "firstprivate var already registered as private"); 179 // Silence the warning about unused variable. 180 (void)IsRegistered; 181 } 182 ++IRef, ++InitsRef; 183 } 184 } 185 return !EmittedAsFirstprivate.empty(); 186 } 187 188 void CodeGenFunction::EmitOMPPrivateClause( 189 const OMPExecutableDirective &D, 190 CodeGenFunction::OMPPrivateScope &PrivateScope) { 191 llvm::DenseSet<const VarDecl *> EmittedAsPrivate; 192 for (auto &&I = D.getClausesOfKind(OMPC_private); I; ++I) { 193 auto *C = cast<OMPPrivateClause>(*I); 194 auto IRef = C->varlist_begin(); 195 for (auto IInit : C->private_copies()) { 196 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 197 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 198 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl()); 199 bool IsRegistered = 200 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{ 201 // Emit private VarDecl with copy init. 202 EmitDecl(*VD); 203 return GetAddrOfLocalVar(VD); 204 }); 205 assert(IsRegistered && "private var already registered as private"); 206 // Silence the warning about unused variable. 207 (void)IsRegistered; 208 } 209 ++IRef; 210 } 211 } 212 } 213 214 bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) { 215 // threadprivate_var1 = master_threadprivate_var1; 216 // operator=(threadprivate_var2, master_threadprivate_var2); 217 // ... 218 // __kmpc_barrier(&loc, global_tid); 219 llvm::DenseSet<const VarDecl *> CopiedVars; 220 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr; 221 for (auto &&I = D.getClausesOfKind(OMPC_copyin); I; ++I) { 222 auto *C = cast<OMPCopyinClause>(*I); 223 auto IRef = C->varlist_begin(); 224 auto ISrcRef = C->source_exprs().begin(); 225 auto IDestRef = C->destination_exprs().begin(); 226 for (auto *AssignOp : C->assignment_ops()) { 227 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 228 QualType Type = VD->getType(); 229 if (CopiedVars.insert(VD->getCanonicalDecl()).second) { 230 // Get the address of the master variable. 231 auto *MasterAddr = VD->isStaticLocal() 232 ? CGM.getStaticLocalDeclAddress(VD) 233 : CGM.GetAddrOfGlobal(VD); 234 // Get the address of the threadprivate variable. 235 auto *PrivateAddr = EmitLValue(*IRef).getAddress(); 236 if (CopiedVars.size() == 1) { 237 // At first check if current thread is a master thread. If it is, no 238 // need to copy data. 239 CopyBegin = createBasicBlock("copyin.not.master"); 240 CopyEnd = createBasicBlock("copyin.not.master.end"); 241 Builder.CreateCondBr( 242 Builder.CreateICmpNE( 243 Builder.CreatePtrToInt(MasterAddr, CGM.IntPtrTy), 244 Builder.CreatePtrToInt(PrivateAddr, CGM.IntPtrTy)), 245 CopyBegin, CopyEnd); 246 EmitBlock(CopyBegin); 247 } 248 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl()); 249 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl()); 250 EmitOMPCopy(*this, Type, PrivateAddr, MasterAddr, DestVD, SrcVD, 251 AssignOp); 252 } 253 ++IRef; 254 ++ISrcRef; 255 ++IDestRef; 256 } 257 } 258 if (CopyEnd) { 259 // Exit out of copying procedure for non-master thread. 260 EmitBlock(CopyEnd, /*IsFinished=*/true); 261 return true; 262 } 263 return false; 264 } 265 266 bool CodeGenFunction::EmitOMPLastprivateClauseInit( 267 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) { 268 bool HasAtLeastOneLastprivate = false; 269 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars; 270 for (auto &&I = D.getClausesOfKind(OMPC_lastprivate); I; ++I) { 271 HasAtLeastOneLastprivate = true; 272 auto *C = cast<OMPLastprivateClause>(*I); 273 auto IRef = C->varlist_begin(); 274 auto IDestRef = C->destination_exprs().begin(); 275 for (auto *IInit : C->private_copies()) { 276 // Keep the address of the original variable for future update at the end 277 // of the loop. 278 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 279 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) { 280 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl()); 281 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> llvm::Value *{ 282 DeclRefExpr DRE( 283 const_cast<VarDecl *>(OrigVD), 284 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup( 285 OrigVD) != nullptr, 286 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc()); 287 return EmitLValue(&DRE).getAddress(); 288 }); 289 // Check if the variable is also a firstprivate: in this case IInit is 290 // not generated. Initialization of this variable will happen in codegen 291 // for 'firstprivate' clause. 292 if (IInit) { 293 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl()); 294 bool IsRegistered = 295 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{ 296 // Emit private VarDecl with copy init. 297 EmitDecl(*VD); 298 return GetAddrOfLocalVar(VD); 299 }); 300 assert(IsRegistered && 301 "lastprivate var already registered as private"); 302 (void)IsRegistered; 303 } 304 } 305 ++IRef, ++IDestRef; 306 } 307 } 308 return HasAtLeastOneLastprivate; 309 } 310 311 void CodeGenFunction::EmitOMPLastprivateClauseFinal( 312 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) { 313 // Emit following code: 314 // if (<IsLastIterCond>) { 315 // orig_var1 = private_orig_var1; 316 // ... 317 // orig_varn = private_orig_varn; 318 // } 319 auto *ThenBB = createBasicBlock(".omp.lastprivate.then"); 320 auto *DoneBB = createBasicBlock(".omp.lastprivate.done"); 321 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB); 322 EmitBlock(ThenBB); 323 llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates; 324 const Expr *LastIterVal = nullptr; 325 const Expr *IVExpr = nullptr; 326 const Expr *IncExpr = nullptr; 327 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) { 328 LastIterVal = 329 cast<VarDecl>(cast<DeclRefExpr>(LoopDirective->getUpperBoundVariable()) 330 ->getDecl()) 331 ->getAnyInitializer(); 332 IVExpr = LoopDirective->getIterationVariable(); 333 IncExpr = LoopDirective->getInc(); 334 auto IUpdate = LoopDirective->updates().begin(); 335 for (auto *E : LoopDirective->counters()) { 336 auto *D = cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl(); 337 LoopCountersAndUpdates[D] = *IUpdate; 338 ++IUpdate; 339 } 340 } 341 { 342 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars; 343 bool FirstLCV = true; 344 for (auto &&I = D.getClausesOfKind(OMPC_lastprivate); I; ++I) { 345 auto *C = cast<OMPLastprivateClause>(*I); 346 auto IRef = C->varlist_begin(); 347 auto ISrcRef = C->source_exprs().begin(); 348 auto IDestRef = C->destination_exprs().begin(); 349 for (auto *AssignOp : C->assignment_ops()) { 350 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 351 QualType Type = PrivateVD->getType(); 352 auto *CanonicalVD = PrivateVD->getCanonicalDecl(); 353 if (AlreadyEmittedVars.insert(CanonicalVD).second) { 354 // If lastprivate variable is a loop control variable for loop-based 355 // directive, update its value before copyin back to original 356 // variable. 357 if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD)) { 358 if (FirstLCV) { 359 EmitAnyExprToMem(LastIterVal, EmitLValue(IVExpr).getAddress(), 360 IVExpr->getType().getQualifiers(), 361 /*IsInitializer=*/false); 362 EmitIgnoredExpr(IncExpr); 363 FirstLCV = false; 364 } 365 EmitIgnoredExpr(UpExpr); 366 } 367 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl()); 368 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl()); 369 // Get the address of the original variable. 370 auto *OriginalAddr = GetAddrOfLocalVar(DestVD); 371 // Get the address of the private variable. 372 auto *PrivateAddr = GetAddrOfLocalVar(PrivateVD); 373 EmitOMPCopy(*this, Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, 374 AssignOp); 375 } 376 ++IRef; 377 ++ISrcRef; 378 ++IDestRef; 379 } 380 } 381 } 382 EmitBlock(DoneBB, /*IsFinished=*/true); 383 } 384 385 void CodeGenFunction::EmitOMPReductionClauseInit( 386 const OMPExecutableDirective &D, 387 CodeGenFunction::OMPPrivateScope &PrivateScope) { 388 for (auto &&I = D.getClausesOfKind(OMPC_reduction); I; ++I) { 389 auto *C = cast<OMPReductionClause>(*I); 390 auto ILHS = C->lhs_exprs().begin(); 391 auto IRHS = C->rhs_exprs().begin(); 392 for (auto IRef : C->varlists()) { 393 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl()); 394 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl()); 395 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl()); 396 // Store the address of the original variable associated with the LHS 397 // implicit variable. 398 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> llvm::Value *{ 399 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), 400 CapturedStmtInfo->lookup(OrigVD) != nullptr, 401 IRef->getType(), VK_LValue, IRef->getExprLoc()); 402 return EmitLValue(&DRE).getAddress(); 403 }); 404 // Emit reduction copy. 405 bool IsRegistered = 406 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> llvm::Value *{ 407 // Emit private VarDecl with reduction init. 408 EmitDecl(*PrivateVD); 409 return GetAddrOfLocalVar(PrivateVD); 410 }); 411 assert(IsRegistered && "private var already registered as private"); 412 // Silence the warning about unused variable. 413 (void)IsRegistered; 414 ++ILHS, ++IRHS; 415 } 416 } 417 } 418 419 void CodeGenFunction::EmitOMPReductionClauseFinal( 420 const OMPExecutableDirective &D) { 421 llvm::SmallVector<const Expr *, 8> LHSExprs; 422 llvm::SmallVector<const Expr *, 8> RHSExprs; 423 llvm::SmallVector<const Expr *, 8> ReductionOps; 424 bool HasAtLeastOneReduction = false; 425 for (auto &&I = D.getClausesOfKind(OMPC_reduction); I; ++I) { 426 HasAtLeastOneReduction = true; 427 auto *C = cast<OMPReductionClause>(*I); 428 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 429 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 430 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end()); 431 } 432 if (HasAtLeastOneReduction) { 433 // Emit nowait reduction if nowait clause is present or directive is a 434 // parallel directive (it always has implicit barrier). 435 CGM.getOpenMPRuntime().emitReduction( 436 *this, D.getLocEnd(), LHSExprs, RHSExprs, ReductionOps, 437 D.getSingleClause(OMPC_nowait) || 438 isOpenMPParallelDirective(D.getDirectiveKind())); 439 } 440 } 441 442 static void emitCommonOMPParallelDirective(CodeGenFunction &CGF, 443 const OMPExecutableDirective &S, 444 const RegionCodeGenTy &CodeGen) { 445 auto CS = cast<CapturedStmt>(S.getAssociatedStmt()); 446 auto CapturedStruct = CGF.GenerateCapturedStmtArgument(*CS); 447 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction( 448 S, *CS->getCapturedDecl()->param_begin(), CodeGen); 449 if (auto C = S.getSingleClause(OMPC_num_threads)) { 450 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF); 451 auto NumThreadsClause = cast<OMPNumThreadsClause>(C); 452 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(), 453 /*IgnoreResultAssign*/ true); 454 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause( 455 CGF, NumThreads, NumThreadsClause->getLocStart()); 456 } 457 const Expr *IfCond = nullptr; 458 if (auto C = S.getSingleClause(OMPC_if)) { 459 IfCond = cast<OMPIfClause>(C)->getCondition(); 460 } 461 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn, 462 CapturedStruct, IfCond); 463 } 464 465 void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) { 466 LexicalScope Scope(*this, S.getSourceRange()); 467 // Emit parallel region as a standalone region. 468 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 469 OMPPrivateScope PrivateScope(CGF); 470 bool Copyins = CGF.EmitOMPCopyinClause(S); 471 bool Firstprivates = CGF.EmitOMPFirstprivateClause(S, PrivateScope); 472 if (Copyins || Firstprivates) { 473 // Emit implicit barrier to synchronize threads and avoid data races on 474 // initialization of firstprivate variables or propagation master's thread 475 // values of threadprivate variables to local instances of that variables 476 // of all other implicit threads. 477 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(), 478 OMPD_unknown); 479 } 480 CGF.EmitOMPPrivateClause(S, PrivateScope); 481 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 482 (void)PrivateScope.Privatize(); 483 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 484 CGF.EmitOMPReductionClauseFinal(S); 485 // Emit implicit barrier at the end of the 'parallel' directive. 486 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(), 487 OMPD_unknown); 488 }; 489 emitCommonOMPParallelDirective(*this, S, CodeGen); 490 } 491 492 void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &S, 493 bool SeparateIter) { 494 RunCleanupsScope BodyScope(*this); 495 // Update counters values on current iteration. 496 for (auto I : S.updates()) { 497 EmitIgnoredExpr(I); 498 } 499 // Update the linear variables. 500 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) { 501 auto *C = cast<OMPLinearClause>(*I); 502 for (auto U : C->updates()) { 503 EmitIgnoredExpr(U); 504 } 505 } 506 507 // On a continue in the body, jump to the end. 508 auto Continue = getJumpDestInCurrentScope("omp.body.continue"); 509 BreakContinueStack.push_back(BreakContinue(JumpDest(), Continue)); 510 // Emit loop body. 511 EmitStmt(S.getBody()); 512 // The end (updates/cleanups). 513 EmitBlock(Continue.getBlock()); 514 BreakContinueStack.pop_back(); 515 if (SeparateIter) { 516 // TODO: Update lastprivates if the SeparateIter flag is true. 517 // This will be implemented in a follow-up OMPLastprivateClause patch, but 518 // result should be still correct without it, as we do not make these 519 // variables private yet. 520 } 521 } 522 523 void CodeGenFunction::EmitOMPInnerLoop( 524 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond, 525 const Expr *IncExpr, 526 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen, 527 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) { 528 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end"); 529 530 // Start the loop with a block that tests the condition. 531 auto CondBlock = createBasicBlock("omp.inner.for.cond"); 532 EmitBlock(CondBlock); 533 LoopStack.push(CondBlock); 534 535 // If there are any cleanups between here and the loop-exit scope, 536 // create a block to stage a loop exit along. 537 auto ExitBlock = LoopExit.getBlock(); 538 if (RequiresCleanup) 539 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup"); 540 541 auto LoopBody = createBasicBlock("omp.inner.for.body"); 542 543 // Emit condition. 544 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S)); 545 if (ExitBlock != LoopExit.getBlock()) { 546 EmitBlock(ExitBlock); 547 EmitBranchThroughCleanup(LoopExit); 548 } 549 550 EmitBlock(LoopBody); 551 incrementProfileCounter(&S); 552 553 // Create a block for the increment. 554 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc"); 555 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 556 557 BodyGen(*this); 558 559 // Emit "IV = IV + 1" and a back-edge to the condition block. 560 EmitBlock(Continue.getBlock()); 561 EmitIgnoredExpr(IncExpr); 562 PostIncGen(*this); 563 BreakContinueStack.pop_back(); 564 EmitBranch(CondBlock); 565 LoopStack.pop(); 566 // Emit the fall-through block. 567 EmitBlock(LoopExit.getBlock()); 568 } 569 570 void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &S) { 571 auto IC = S.counters().begin(); 572 for (auto F : S.finals()) { 573 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl()); 574 if (LocalDeclMap.lookup(OrigVD)) { 575 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), 576 CapturedStmtInfo->lookup(OrigVD) != nullptr, 577 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc()); 578 auto *OrigAddr = EmitLValue(&DRE).getAddress(); 579 OMPPrivateScope VarScope(*this); 580 VarScope.addPrivate(OrigVD, 581 [OrigAddr]() -> llvm::Value *{ return OrigAddr; }); 582 (void)VarScope.Privatize(); 583 EmitIgnoredExpr(F); 584 } 585 ++IC; 586 } 587 // Emit the final values of the linear variables. 588 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) { 589 auto *C = cast<OMPLinearClause>(*I); 590 auto IC = C->varlist_begin(); 591 for (auto F : C->finals()) { 592 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl()); 593 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), 594 CapturedStmtInfo->lookup(OrigVD) != nullptr, 595 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc()); 596 auto *OrigAddr = EmitLValue(&DRE).getAddress(); 597 OMPPrivateScope VarScope(*this); 598 VarScope.addPrivate(OrigVD, 599 [OrigAddr]() -> llvm::Value *{ return OrigAddr; }); 600 (void)VarScope.Privatize(); 601 EmitIgnoredExpr(F); 602 ++IC; 603 } 604 } 605 } 606 607 static void EmitOMPAlignedClause(CodeGenFunction &CGF, CodeGenModule &CGM, 608 const OMPAlignedClause &Clause) { 609 unsigned ClauseAlignment = 0; 610 if (auto AlignmentExpr = Clause.getAlignment()) { 611 auto AlignmentCI = 612 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr)); 613 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue()); 614 } 615 for (auto E : Clause.varlists()) { 616 unsigned Alignment = ClauseAlignment; 617 if (Alignment == 0) { 618 // OpenMP [2.8.1, Description] 619 // If no optional parameter is specified, implementation-defined default 620 // alignments for SIMD instructions on the target platforms are assumed. 621 Alignment = CGM.getTargetCodeGenInfo().getOpenMPSimdDefaultAlignment( 622 E->getType()); 623 } 624 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) && 625 "alignment is not power of 2"); 626 if (Alignment != 0) { 627 llvm::Value *PtrValue = CGF.EmitScalarExpr(E); 628 CGF.EmitAlignmentAssumption(PtrValue, Alignment); 629 } 630 } 631 } 632 633 static void EmitPrivateLoopCounters(CodeGenFunction &CGF, 634 CodeGenFunction::OMPPrivateScope &LoopScope, 635 ArrayRef<Expr *> Counters) { 636 for (auto *E : Counters) { 637 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 638 (void)LoopScope.addPrivate(VD, [&]() -> llvm::Value *{ 639 // Emit var without initialization. 640 auto VarEmission = CGF.EmitAutoVarAlloca(*VD); 641 CGF.EmitAutoVarCleanups(VarEmission); 642 return VarEmission.getAllocatedAddress(); 643 }); 644 } 645 } 646 647 static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S, 648 const Expr *Cond, llvm::BasicBlock *TrueBlock, 649 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) { 650 { 651 CodeGenFunction::OMPPrivateScope PreCondScope(CGF); 652 EmitPrivateLoopCounters(CGF, PreCondScope, S.counters()); 653 const VarDecl *IVDecl = 654 cast<VarDecl>(cast<DeclRefExpr>(S.getIterationVariable())->getDecl()); 655 bool IsRegistered = PreCondScope.addPrivate(IVDecl, [&]() -> llvm::Value *{ 656 // Emit var without initialization. 657 auto VarEmission = CGF.EmitAutoVarAlloca(*IVDecl); 658 CGF.EmitAutoVarCleanups(VarEmission); 659 return VarEmission.getAllocatedAddress(); 660 }); 661 assert(IsRegistered && "counter already registered as private"); 662 // Silence the warning about unused variable. 663 (void)IsRegistered; 664 (void)PreCondScope.Privatize(); 665 // Initialize internal counter to 0 to calculate initial values of real 666 // counters. 667 LValue IV = CGF.EmitLValue(S.getIterationVariable()); 668 CGF.EmitStoreOfScalar( 669 llvm::ConstantInt::getNullValue( 670 IV.getAddress()->getType()->getPointerElementType()), 671 CGF.EmitLValue(S.getIterationVariable()), /*isInit=*/true); 672 // Get initial values of real counters. 673 for (auto I : S.updates()) { 674 CGF.EmitIgnoredExpr(I); 675 } 676 } 677 // Check that loop is executed at least one time. 678 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount); 679 } 680 681 static void 682 EmitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D, 683 CodeGenFunction::OMPPrivateScope &PrivateScope) { 684 for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) { 685 auto *C = cast<OMPLinearClause>(*I); 686 for (auto *E : C->varlists()) { 687 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 688 bool IsRegistered = PrivateScope.addPrivate(VD, [&]()->llvm::Value * { 689 // Emit var without initialization. 690 auto VarEmission = CGF.EmitAutoVarAlloca(*VD); 691 CGF.EmitAutoVarCleanups(VarEmission); 692 return VarEmission.getAllocatedAddress(); 693 }); 694 assert(IsRegistered && "linear var already registered as private"); 695 // Silence the warning about unused variable. 696 (void)IsRegistered; 697 } 698 } 699 } 700 701 void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) { 702 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 703 // Pragma 'simd' code depends on presence of 'lastprivate'. 704 // If present, we have to separate last iteration of the loop: 705 // 706 // if (PreCond) { 707 // for (IV in 0..LastIteration-1) BODY; 708 // BODY with updates of lastprivate vars; 709 // <Final counter/linear vars updates>; 710 // } 711 // 712 // otherwise (when there's no lastprivate): 713 // 714 // if (PreCond) { 715 // for (IV in 0..LastIteration) BODY; 716 // <Final counter/linear vars updates>; 717 // } 718 // 719 720 // Emit: if (PreCond) - begin. 721 // If the condition constant folds and can be elided, avoid emitting the 722 // whole loop. 723 bool CondConstant; 724 llvm::BasicBlock *ContBlock = nullptr; 725 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 726 if (!CondConstant) 727 return; 728 } else { 729 auto *ThenBlock = CGF.createBasicBlock("simd.if.then"); 730 ContBlock = CGF.createBasicBlock("simd.if.end"); 731 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock, 732 CGF.getProfileCount(&S)); 733 CGF.EmitBlock(ThenBlock); 734 CGF.incrementProfileCounter(&S); 735 } 736 // Walk clauses and process safelen/lastprivate. 737 bool SeparateIter = false; 738 CGF.LoopStack.setParallel(); 739 CGF.LoopStack.setVectorizerEnable(true); 740 for (auto C : S.clauses()) { 741 switch (C->getClauseKind()) { 742 case OMPC_safelen: { 743 RValue Len = CGF.EmitAnyExpr(cast<OMPSafelenClause>(C)->getSafelen(), 744 AggValueSlot::ignored(), true); 745 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal()); 746 CGF.LoopStack.setVectorizerWidth(Val->getZExtValue()); 747 // In presence of finite 'safelen', it may be unsafe to mark all 748 // the memory instructions parallel, because loop-carried 749 // dependences of 'safelen' iterations are possible. 750 CGF.LoopStack.setParallel(false); 751 break; 752 } 753 case OMPC_aligned: 754 EmitOMPAlignedClause(CGF, CGF.CGM, cast<OMPAlignedClause>(*C)); 755 break; 756 case OMPC_lastprivate: 757 SeparateIter = true; 758 break; 759 default: 760 // Not handled yet 761 ; 762 } 763 } 764 765 // Emit inits for the linear variables. 766 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) { 767 auto *C = cast<OMPLinearClause>(*I); 768 for (auto Init : C->inits()) { 769 auto *D = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl()); 770 CGF.EmitVarDecl(*D); 771 } 772 } 773 774 // Emit the loop iteration variable. 775 const Expr *IVExpr = S.getIterationVariable(); 776 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl()); 777 CGF.EmitVarDecl(*IVDecl); 778 CGF.EmitIgnoredExpr(S.getInit()); 779 780 // Emit the iterations count variable. 781 // If it is not a variable, Sema decided to calculate iterations count on 782 // each iteration (e.g., it is foldable into a constant). 783 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 784 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 785 // Emit calculation of the iterations count. 786 CGF.EmitIgnoredExpr(S.getCalcLastIteration()); 787 } 788 789 // Emit the linear steps for the linear clauses. 790 // If a step is not constant, it is pre-calculated before the loop. 791 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) { 792 auto *C = cast<OMPLinearClause>(*I); 793 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep())) 794 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) { 795 CGF.EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl())); 796 // Emit calculation of the linear step. 797 CGF.EmitIgnoredExpr(CS); 798 } 799 } 800 801 { 802 OMPPrivateScope LoopScope(CGF); 803 EmitPrivateLoopCounters(CGF, LoopScope, S.counters()); 804 EmitPrivateLinearVars(CGF, S, LoopScope); 805 CGF.EmitOMPPrivateClause(S, LoopScope); 806 (void)LoopScope.Privatize(); 807 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), 808 S.getCond(SeparateIter), S.getInc(), 809 [&S](CodeGenFunction &CGF) { 810 CGF.EmitOMPLoopBody(S); 811 CGF.EmitStopPoint(&S); 812 }, 813 [](CodeGenFunction &) {}); 814 if (SeparateIter) { 815 CGF.EmitOMPLoopBody(S, /*SeparateIter=*/true); 816 } 817 } 818 CGF.EmitOMPSimdFinal(S); 819 // Emit: if (PreCond) - end. 820 if (ContBlock) { 821 CGF.EmitBranch(ContBlock); 822 CGF.EmitBlock(ContBlock, true); 823 } 824 }; 825 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen); 826 } 827 828 void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind, 829 const OMPLoopDirective &S, 830 OMPPrivateScope &LoopScope, 831 bool Ordered, llvm::Value *LB, 832 llvm::Value *UB, llvm::Value *ST, 833 llvm::Value *IL, llvm::Value *Chunk) { 834 auto &RT = CGM.getOpenMPRuntime(); 835 836 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime). 837 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind); 838 839 assert((Ordered || 840 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) && 841 "static non-chunked schedule does not need outer loop"); 842 843 // Emit outer loop. 844 // 845 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 846 // When schedule(dynamic,chunk_size) is specified, the iterations are 847 // distributed to threads in the team in chunks as the threads request them. 848 // Each thread executes a chunk of iterations, then requests another chunk, 849 // until no chunks remain to be distributed. Each chunk contains chunk_size 850 // iterations, except for the last chunk to be distributed, which may have 851 // fewer iterations. When no chunk_size is specified, it defaults to 1. 852 // 853 // When schedule(guided,chunk_size) is specified, the iterations are assigned 854 // to threads in the team in chunks as the executing threads request them. 855 // Each thread executes a chunk of iterations, then requests another chunk, 856 // until no chunks remain to be assigned. For a chunk_size of 1, the size of 857 // each chunk is proportional to the number of unassigned iterations divided 858 // by the number of threads in the team, decreasing to 1. For a chunk_size 859 // with value k (greater than 1), the size of each chunk is determined in the 860 // same way, with the restriction that the chunks do not contain fewer than k 861 // iterations (except for the last chunk to be assigned, which may have fewer 862 // than k iterations). 863 // 864 // When schedule(auto) is specified, the decision regarding scheduling is 865 // delegated to the compiler and/or runtime system. The programmer gives the 866 // implementation the freedom to choose any possible mapping of iterations to 867 // threads in the team. 868 // 869 // When schedule(runtime) is specified, the decision regarding scheduling is 870 // deferred until run time, and the schedule and chunk size are taken from the 871 // run-sched-var ICV. If the ICV is set to auto, the schedule is 872 // implementation defined 873 // 874 // while(__kmpc_dispatch_next(&LB, &UB)) { 875 // idx = LB; 876 // while (idx <= UB) { BODY; ++idx; 877 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only. 878 // } // inner loop 879 // } 880 // 881 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 882 // When schedule(static, chunk_size) is specified, iterations are divided into 883 // chunks of size chunk_size, and the chunks are assigned to the threads in 884 // the team in a round-robin fashion in the order of the thread number. 885 // 886 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) { 887 // while (idx <= UB) { BODY; ++idx; } // inner loop 888 // LB = LB + ST; 889 // UB = UB + ST; 890 // } 891 // 892 893 const Expr *IVExpr = S.getIterationVariable(); 894 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 895 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 896 897 RT.emitForInit( 898 *this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, Ordered, IL, LB, 899 (DynamicOrOrdered ? EmitAnyExpr(S.getLastIteration()).getScalarVal() 900 : UB), 901 ST, Chunk); 902 903 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end"); 904 905 // Start the loop with a block that tests the condition. 906 auto CondBlock = createBasicBlock("omp.dispatch.cond"); 907 EmitBlock(CondBlock); 908 LoopStack.push(CondBlock); 909 910 llvm::Value *BoolCondVal = nullptr; 911 if (!DynamicOrOrdered) { 912 // UB = min(UB, GlobalUB) 913 EmitIgnoredExpr(S.getEnsureUpperBound()); 914 // IV = LB 915 EmitIgnoredExpr(S.getInit()); 916 // IV < UB 917 BoolCondVal = EvaluateExprAsBool(S.getCond(false)); 918 } else { 919 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, 920 IL, LB, UB, ST); 921 } 922 923 // If there are any cleanups between here and the loop-exit scope, 924 // create a block to stage a loop exit along. 925 auto ExitBlock = LoopExit.getBlock(); 926 if (LoopScope.requiresCleanups()) 927 ExitBlock = createBasicBlock("omp.dispatch.cleanup"); 928 929 auto LoopBody = createBasicBlock("omp.dispatch.body"); 930 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock); 931 if (ExitBlock != LoopExit.getBlock()) { 932 EmitBlock(ExitBlock); 933 EmitBranchThroughCleanup(LoopExit); 934 } 935 EmitBlock(LoopBody); 936 937 // Emit "IV = LB" (in case of static schedule, we have already calculated new 938 // LB for loop condition and emitted it above). 939 if (DynamicOrOrdered) 940 EmitIgnoredExpr(S.getInit()); 941 942 // Create a block for the increment. 943 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc"); 944 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 945 946 SourceLocation Loc = S.getLocStart(); 947 // Generate !llvm.loop.parallel metadata for loads and stores for loops with 948 // dynamic/guided scheduling and without ordered clause. 949 LoopStack.setParallel((ScheduleKind == OMPC_SCHEDULE_dynamic || 950 ScheduleKind == OMPC_SCHEDULE_guided) && 951 !Ordered); 952 EmitOMPInnerLoop( 953 S, LoopScope.requiresCleanups(), S.getCond(/*SeparateIter=*/false), 954 S.getInc(), 955 [&S](CodeGenFunction &CGF) { 956 CGF.EmitOMPLoopBody(S); 957 CGF.EmitStopPoint(&S); 958 }, 959 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) { 960 if (Ordered) { 961 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd( 962 CGF, Loc, IVSize, IVSigned); 963 } 964 }); 965 966 EmitBlock(Continue.getBlock()); 967 BreakContinueStack.pop_back(); 968 if (!DynamicOrOrdered) { 969 // Emit "LB = LB + Stride", "UB = UB + Stride". 970 EmitIgnoredExpr(S.getNextLowerBound()); 971 EmitIgnoredExpr(S.getNextUpperBound()); 972 } 973 974 EmitBranch(CondBlock); 975 LoopStack.pop(); 976 // Emit the fall-through block. 977 EmitBlock(LoopExit.getBlock()); 978 979 // Tell the runtime we are done. 980 if (!DynamicOrOrdered) 981 RT.emitForStaticFinish(*this, S.getLocEnd()); 982 } 983 984 /// \brief Emit a helper variable and return corresponding lvalue. 985 static LValue EmitOMPHelperVar(CodeGenFunction &CGF, 986 const DeclRefExpr *Helper) { 987 auto VDecl = cast<VarDecl>(Helper->getDecl()); 988 CGF.EmitVarDecl(*VDecl); 989 return CGF.EmitLValue(Helper); 990 } 991 992 static std::pair<llvm::Value * /*Chunk*/, OpenMPScheduleClauseKind> 993 emitScheduleClause(CodeGenFunction &CGF, const OMPLoopDirective &S, 994 bool OuterRegion) { 995 // Detect the loop schedule kind and chunk. 996 auto ScheduleKind = OMPC_SCHEDULE_unknown; 997 llvm::Value *Chunk = nullptr; 998 if (auto *C = 999 cast_or_null<OMPScheduleClause>(S.getSingleClause(OMPC_schedule))) { 1000 ScheduleKind = C->getScheduleKind(); 1001 if (const auto *Ch = C->getChunkSize()) { 1002 if (auto *ImpRef = cast_or_null<DeclRefExpr>(C->getHelperChunkSize())) { 1003 if (OuterRegion) { 1004 const VarDecl *ImpVar = cast<VarDecl>(ImpRef->getDecl()); 1005 CGF.EmitVarDecl(*ImpVar); 1006 CGF.EmitStoreThroughLValue( 1007 CGF.EmitAnyExpr(Ch), 1008 CGF.MakeNaturalAlignAddrLValue(CGF.GetAddrOfLocalVar(ImpVar), 1009 ImpVar->getType())); 1010 } else { 1011 Ch = ImpRef; 1012 } 1013 } 1014 if (!C->getHelperChunkSize() || !OuterRegion) { 1015 Chunk = CGF.EmitScalarExpr(Ch); 1016 Chunk = CGF.EmitScalarConversion(Chunk, Ch->getType(), 1017 S.getIterationVariable()->getType()); 1018 } 1019 } 1020 } 1021 return std::make_pair(Chunk, ScheduleKind); 1022 } 1023 1024 bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) { 1025 // Emit the loop iteration variable. 1026 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable()); 1027 auto IVDecl = cast<VarDecl>(IVExpr->getDecl()); 1028 EmitVarDecl(*IVDecl); 1029 1030 // Emit the iterations count variable. 1031 // If it is not a variable, Sema decided to calculate iterations count on each 1032 // iteration (e.g., it is foldable into a constant). 1033 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 1034 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 1035 // Emit calculation of the iterations count. 1036 EmitIgnoredExpr(S.getCalcLastIteration()); 1037 } 1038 1039 auto &RT = CGM.getOpenMPRuntime(); 1040 1041 bool HasLastprivateClause; 1042 // Check pre-condition. 1043 { 1044 // Skip the entire loop if we don't meet the precondition. 1045 // If the condition constant folds and can be elided, avoid emitting the 1046 // whole loop. 1047 bool CondConstant; 1048 llvm::BasicBlock *ContBlock = nullptr; 1049 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 1050 if (!CondConstant) 1051 return false; 1052 } else { 1053 auto *ThenBlock = createBasicBlock("omp.precond.then"); 1054 ContBlock = createBasicBlock("omp.precond.end"); 1055 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock, 1056 getProfileCount(&S)); 1057 EmitBlock(ThenBlock); 1058 incrementProfileCounter(&S); 1059 } 1060 // Emit 'then' code. 1061 { 1062 // Emit helper vars inits. 1063 LValue LB = 1064 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable())); 1065 LValue UB = 1066 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable())); 1067 LValue ST = 1068 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable())); 1069 LValue IL = 1070 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable())); 1071 1072 OMPPrivateScope LoopScope(*this); 1073 if (EmitOMPFirstprivateClause(S, LoopScope)) { 1074 // Emit implicit barrier to synchronize threads and avoid data races on 1075 // initialization of firstprivate variables. 1076 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), 1077 OMPD_unknown); 1078 } 1079 EmitOMPPrivateClause(S, LoopScope); 1080 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope); 1081 EmitOMPReductionClauseInit(S, LoopScope); 1082 EmitPrivateLoopCounters(*this, LoopScope, S.counters()); 1083 (void)LoopScope.Privatize(); 1084 1085 // Detect the loop schedule kind and chunk. 1086 llvm::Value *Chunk; 1087 OpenMPScheduleClauseKind ScheduleKind; 1088 auto ScheduleInfo = 1089 emitScheduleClause(*this, S, /*OuterRegion=*/false); 1090 Chunk = ScheduleInfo.first; 1091 ScheduleKind = ScheduleInfo.second; 1092 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 1093 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 1094 const bool Ordered = S.getSingleClause(OMPC_ordered) != nullptr; 1095 if (RT.isStaticNonchunked(ScheduleKind, 1096 /* Chunked */ Chunk != nullptr) && 1097 !Ordered) { 1098 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 1099 // When no chunk_size is specified, the iteration space is divided into 1100 // chunks that are approximately equal in size, and at most one chunk is 1101 // distributed to each thread. Note that the size of the chunks is 1102 // unspecified in this case. 1103 RT.emitForInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, 1104 Ordered, IL.getAddress(), LB.getAddress(), 1105 UB.getAddress(), ST.getAddress()); 1106 // UB = min(UB, GlobalUB); 1107 EmitIgnoredExpr(S.getEnsureUpperBound()); 1108 // IV = LB; 1109 EmitIgnoredExpr(S.getInit()); 1110 // while (idx <= UB) { BODY; ++idx; } 1111 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), 1112 S.getCond(/*SeparateIter=*/false), S.getInc(), 1113 [&S](CodeGenFunction &CGF) { 1114 CGF.EmitOMPLoopBody(S); 1115 CGF.EmitStopPoint(&S); 1116 }, 1117 [](CodeGenFunction &) {}); 1118 // Tell the runtime we are done. 1119 RT.emitForStaticFinish(*this, S.getLocStart()); 1120 } else { 1121 // Emit the outer loop, which requests its work chunk [LB..UB] from 1122 // runtime and runs the inner loop to process it. 1123 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, Ordered, 1124 LB.getAddress(), UB.getAddress(), ST.getAddress(), 1125 IL.getAddress(), Chunk); 1126 } 1127 EmitOMPReductionClauseFinal(S); 1128 // Emit final copy of the lastprivate variables if IsLastIter != 0. 1129 if (HasLastprivateClause) 1130 EmitOMPLastprivateClauseFinal( 1131 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart()))); 1132 } 1133 // We're now done with the loop, so jump to the continuation block. 1134 if (ContBlock) { 1135 EmitBranch(ContBlock); 1136 EmitBlock(ContBlock, true); 1137 } 1138 } 1139 return HasLastprivateClause; 1140 } 1141 1142 void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) { 1143 LexicalScope Scope(*this, S.getSourceRange()); 1144 bool HasLastprivates = false; 1145 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) { 1146 HasLastprivates = CGF.EmitOMPWorksharingLoop(S); 1147 }; 1148 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen); 1149 1150 // Emit an implicit barrier at the end. 1151 if (!S.getSingleClause(OMPC_nowait) || HasLastprivates) { 1152 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for); 1153 } 1154 } 1155 1156 void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &) { 1157 llvm_unreachable("CodeGen for 'omp for simd' is not supported yet."); 1158 } 1159 1160 static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty, 1161 const Twine &Name, 1162 llvm::Value *Init = nullptr) { 1163 auto LVal = CGF.MakeNaturalAlignAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty); 1164 if (Init) 1165 CGF.EmitScalarInit(Init, LVal); 1166 return LVal; 1167 } 1168 1169 static OpenMPDirectiveKind emitSections(CodeGenFunction &CGF, 1170 const OMPExecutableDirective &S) { 1171 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt(); 1172 auto *CS = dyn_cast<CompoundStmt>(Stmt); 1173 if (CS && CS->size() > 1) { 1174 bool HasLastprivates = false; 1175 auto &&CodeGen = [&S, CS, &HasLastprivates](CodeGenFunction &CGF) { 1176 auto &C = CGF.CGM.getContext(); 1177 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 1178 // Emit helper vars inits. 1179 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.", 1180 CGF.Builder.getInt32(0)); 1181 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1); 1182 LValue UB = 1183 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal); 1184 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.", 1185 CGF.Builder.getInt32(1)); 1186 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.", 1187 CGF.Builder.getInt32(0)); 1188 // Loop counter. 1189 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv."); 1190 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue); 1191 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV); 1192 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue); 1193 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB); 1194 // Generate condition for loop. 1195 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue, 1196 OK_Ordinary, S.getLocStart(), 1197 /*fpContractable=*/false); 1198 // Increment for loop counter. 1199 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, 1200 OK_Ordinary, S.getLocStart()); 1201 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) { 1202 // Iterate through all sections and emit a switch construct: 1203 // switch (IV) { 1204 // case 0: 1205 // <SectionStmt[0]>; 1206 // break; 1207 // ... 1208 // case <NumSection> - 1: 1209 // <SectionStmt[<NumSection> - 1]>; 1210 // break; 1211 // } 1212 // .omp.sections.exit: 1213 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit"); 1214 auto *SwitchStmt = CGF.Builder.CreateSwitch( 1215 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB, 1216 CS->size()); 1217 unsigned CaseNumber = 0; 1218 for (auto C = CS->children(); C; ++C, ++CaseNumber) { 1219 auto CaseBB = CGF.createBasicBlock(".omp.sections.case"); 1220 CGF.EmitBlock(CaseBB); 1221 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB); 1222 CGF.EmitStmt(*C); 1223 CGF.EmitBranch(ExitBB); 1224 } 1225 CGF.EmitBlock(ExitBB, /*IsFinished=*/true); 1226 }; 1227 1228 CodeGenFunction::OMPPrivateScope LoopScope(CGF); 1229 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) { 1230 // Emit implicit barrier to synchronize threads and avoid data races on 1231 // initialization of firstprivate variables. 1232 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(), 1233 OMPD_unknown); 1234 } 1235 CGF.EmitOMPPrivateClause(S, LoopScope); 1236 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 1237 CGF.EmitOMPReductionClauseInit(S, LoopScope); 1238 (void)LoopScope.Privatize(); 1239 1240 // Emit static non-chunked loop. 1241 CGF.CGM.getOpenMPRuntime().emitForInit( 1242 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32, 1243 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), 1244 LB.getAddress(), UB.getAddress(), ST.getAddress()); 1245 // UB = min(UB, GlobalUB); 1246 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart()); 1247 auto *MinUBGlobalUB = CGF.Builder.CreateSelect( 1248 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal); 1249 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB); 1250 // IV = LB; 1251 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV); 1252 // while (idx <= UB) { BODY; ++idx; } 1253 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen, 1254 [](CodeGenFunction &) {}); 1255 // Tell the runtime we are done. 1256 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart()); 1257 CGF.EmitOMPReductionClauseFinal(S); 1258 1259 // Emit final copy of the lastprivate variables if IsLastIter != 0. 1260 if (HasLastprivates) 1261 CGF.EmitOMPLastprivateClauseFinal( 1262 S, CGF.Builder.CreateIsNotNull( 1263 CGF.EmitLoadOfScalar(IL, S.getLocStart()))); 1264 }; 1265 1266 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, CodeGen); 1267 // Emit barrier for lastprivates only if 'sections' directive has 'nowait' 1268 // clause. Otherwise the barrier will be generated by the codegen for the 1269 // directive. 1270 if (HasLastprivates && S.getSingleClause(OMPC_nowait)) { 1271 // Emit implicit barrier to synchronize threads and avoid data races on 1272 // initialization of firstprivate variables. 1273 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(), 1274 OMPD_unknown); 1275 } 1276 return OMPD_sections; 1277 } 1278 // If only one section is found - no need to generate loop, emit as a single 1279 // region. 1280 bool HasFirstprivates; 1281 // No need to generate reductions for sections with single section region, we 1282 // can use original shared variables for all operations. 1283 bool HasReductions = !S.getClausesOfKind(OMPC_reduction).empty(); 1284 // No need to generate lastprivates for sections with single section region, 1285 // we can use original shared variable for all calculations with barrier at 1286 // the end of the sections. 1287 bool HasLastprivates = !S.getClausesOfKind(OMPC_lastprivate).empty(); 1288 auto &&CodeGen = [Stmt, &S, &HasFirstprivates](CodeGenFunction &CGF) { 1289 CodeGenFunction::OMPPrivateScope SingleScope(CGF); 1290 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope); 1291 CGF.EmitOMPPrivateClause(S, SingleScope); 1292 (void)SingleScope.Privatize(); 1293 1294 CGF.EmitStmt(Stmt); 1295 CGF.EnsureInsertPoint(); 1296 }; 1297 CGF.CGM.getOpenMPRuntime().emitSingleRegion(CGF, CodeGen, S.getLocStart(), 1298 llvm::None, llvm::None, 1299 llvm::None, llvm::None); 1300 // Emit barrier for firstprivates, lastprivates or reductions only if 1301 // 'sections' directive has 'nowait' clause. Otherwise the barrier will be 1302 // generated by the codegen for the directive. 1303 if ((HasFirstprivates || HasLastprivates || HasReductions) && 1304 S.getSingleClause(OMPC_nowait)) { 1305 // Emit implicit barrier to synchronize threads and avoid data races on 1306 // initialization of firstprivate variables. 1307 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(), 1308 OMPD_unknown); 1309 } 1310 return OMPD_single; 1311 } 1312 1313 void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) { 1314 LexicalScope Scope(*this, S.getSourceRange()); 1315 OpenMPDirectiveKind EmittedAs = emitSections(*this, S); 1316 // Emit an implicit barrier at the end. 1317 if (!S.getSingleClause(OMPC_nowait)) { 1318 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs); 1319 } 1320 } 1321 1322 void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) { 1323 LexicalScope Scope(*this, S.getSourceRange()); 1324 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 1325 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1326 CGF.EnsureInsertPoint(); 1327 }; 1328 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen); 1329 } 1330 1331 void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) { 1332 llvm::SmallVector<const Expr *, 8> CopyprivateVars; 1333 llvm::SmallVector<const Expr *, 8> DestExprs; 1334 llvm::SmallVector<const Expr *, 8> SrcExprs; 1335 llvm::SmallVector<const Expr *, 8> AssignmentOps; 1336 // Check if there are any 'copyprivate' clauses associated with this 1337 // 'single' 1338 // construct. 1339 // Build a list of copyprivate variables along with helper expressions 1340 // (<source>, <destination>, <destination>=<source> expressions) 1341 for (auto &&I = S.getClausesOfKind(OMPC_copyprivate); I; ++I) { 1342 auto *C = cast<OMPCopyprivateClause>(*I); 1343 CopyprivateVars.append(C->varlists().begin(), C->varlists().end()); 1344 DestExprs.append(C->destination_exprs().begin(), 1345 C->destination_exprs().end()); 1346 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end()); 1347 AssignmentOps.append(C->assignment_ops().begin(), 1348 C->assignment_ops().end()); 1349 } 1350 LexicalScope Scope(*this, S.getSourceRange()); 1351 // Emit code for 'single' region along with 'copyprivate' clauses 1352 bool HasFirstprivates; 1353 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) { 1354 CodeGenFunction::OMPPrivateScope SingleScope(CGF); 1355 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope); 1356 CGF.EmitOMPPrivateClause(S, SingleScope); 1357 (void)SingleScope.Privatize(); 1358 1359 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1360 CGF.EnsureInsertPoint(); 1361 }; 1362 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(), 1363 CopyprivateVars, DestExprs, SrcExprs, 1364 AssignmentOps); 1365 // Emit an implicit barrier at the end (to avoid data race on firstprivate 1366 // init or if no 'nowait' clause was specified and no 'copyprivate' clause). 1367 if ((!S.getSingleClause(OMPC_nowait) || HasFirstprivates) && 1368 CopyprivateVars.empty()) { 1369 CGM.getOpenMPRuntime().emitBarrierCall( 1370 *this, S.getLocStart(), 1371 S.getSingleClause(OMPC_nowait) ? OMPD_unknown : OMPD_single); 1372 } 1373 } 1374 1375 void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) { 1376 LexicalScope Scope(*this, S.getSourceRange()); 1377 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 1378 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1379 CGF.EnsureInsertPoint(); 1380 }; 1381 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart()); 1382 } 1383 1384 void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) { 1385 LexicalScope Scope(*this, S.getSourceRange()); 1386 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 1387 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1388 CGF.EnsureInsertPoint(); 1389 }; 1390 CGM.getOpenMPRuntime().emitCriticalRegion( 1391 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart()); 1392 } 1393 1394 void CodeGenFunction::EmitOMPParallelForDirective( 1395 const OMPParallelForDirective &S) { 1396 // Emit directive as a combined directive that consists of two implicit 1397 // directives: 'parallel' with 'for' directive. 1398 LexicalScope Scope(*this, S.getSourceRange()); 1399 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true); 1400 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 1401 CGF.EmitOMPWorksharingLoop(S); 1402 // Emit implicit barrier at the end of parallel region, but this barrier 1403 // is at the end of 'for' directive, so emit it as the implicit barrier for 1404 // this 'for' directive. 1405 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(), 1406 OMPD_parallel); 1407 }; 1408 emitCommonOMPParallelDirective(*this, S, CodeGen); 1409 } 1410 1411 void CodeGenFunction::EmitOMPParallelForSimdDirective( 1412 const OMPParallelForSimdDirective &) { 1413 llvm_unreachable("CodeGen for 'omp parallel for simd' is not supported yet."); 1414 } 1415 1416 void CodeGenFunction::EmitOMPParallelSectionsDirective( 1417 const OMPParallelSectionsDirective &S) { 1418 // Emit directive as a combined directive that consists of two implicit 1419 // directives: 'parallel' with 'sections' directive. 1420 LexicalScope Scope(*this, S.getSourceRange()); 1421 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 1422 (void)emitSections(CGF, S); 1423 // Emit implicit barrier at the end of parallel region. 1424 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(), 1425 OMPD_parallel); 1426 }; 1427 emitCommonOMPParallelDirective(*this, S, CodeGen); 1428 } 1429 1430 void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) { 1431 // Emit outlined function for task construct. 1432 LexicalScope Scope(*this, S.getSourceRange()); 1433 auto CS = cast<CapturedStmt>(S.getAssociatedStmt()); 1434 auto CapturedStruct = GenerateCapturedStmtArgument(*CS); 1435 auto *I = CS->getCapturedDecl()->param_begin(); 1436 auto *PartId = std::next(I); 1437 // The first function argument for tasks is a thread id, the second one is a 1438 // part id (0 for tied tasks, >=0 for untied task). 1439 llvm::DenseSet<const VarDecl *> EmittedAsPrivate; 1440 // Get list of private variables. 1441 llvm::SmallVector<const Expr *, 8> PrivateVars; 1442 llvm::SmallVector<const Expr *, 8> PrivateCopies; 1443 for (auto &&I = S.getClausesOfKind(OMPC_private); I; ++I) { 1444 auto *C = cast<OMPPrivateClause>(*I); 1445 auto IRef = C->varlist_begin(); 1446 for (auto *IInit : C->private_copies()) { 1447 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 1448 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 1449 PrivateVars.push_back(*IRef); 1450 PrivateCopies.push_back(IInit); 1451 } 1452 ++IRef; 1453 } 1454 } 1455 EmittedAsPrivate.clear(); 1456 // Get list of firstprivate variables. 1457 llvm::SmallVector<const Expr *, 8> FirstprivateVars; 1458 llvm::SmallVector<const Expr *, 8> FirstprivateCopies; 1459 llvm::SmallVector<const Expr *, 8> FirstprivateInits; 1460 for (auto &&I = S.getClausesOfKind(OMPC_firstprivate); I; ++I) { 1461 auto *C = cast<OMPFirstprivateClause>(*I); 1462 auto IRef = C->varlist_begin(); 1463 auto IElemInitRef = C->inits().begin(); 1464 for (auto *IInit : C->private_copies()) { 1465 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 1466 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 1467 FirstprivateVars.push_back(*IRef); 1468 FirstprivateCopies.push_back(IInit); 1469 FirstprivateInits.push_back(*IElemInitRef); 1470 } 1471 ++IRef, ++IElemInitRef; 1472 } 1473 } 1474 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars]( 1475 CodeGenFunction &CGF) { 1476 // Set proper addresses for generated private copies. 1477 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt()); 1478 OMPPrivateScope Scope(CGF); 1479 if (!PrivateVars.empty() || !FirstprivateVars.empty()) { 1480 auto *CopyFn = CGF.Builder.CreateAlignedLoad( 1481 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)), 1482 CGF.PointerAlignInBytes); 1483 auto *PrivatesPtr = CGF.Builder.CreateAlignedLoad( 1484 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)), 1485 CGF.PointerAlignInBytes); 1486 // Map privates. 1487 llvm::SmallVector<std::pair<const VarDecl *, llvm::Value *>, 16> 1488 PrivatePtrs; 1489 llvm::SmallVector<llvm::Value *, 16> CallArgs; 1490 CallArgs.push_back(PrivatesPtr); 1491 for (auto *E : PrivateVars) { 1492 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 1493 auto *PrivatePtr = 1494 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType())); 1495 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr)); 1496 CallArgs.push_back(PrivatePtr); 1497 } 1498 for (auto *E : FirstprivateVars) { 1499 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 1500 auto *PrivatePtr = 1501 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType())); 1502 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr)); 1503 CallArgs.push_back(PrivatePtr); 1504 } 1505 CGF.EmitRuntimeCall(CopyFn, CallArgs); 1506 for (auto &&Pair : PrivatePtrs) { 1507 auto *Replacement = 1508 CGF.Builder.CreateAlignedLoad(Pair.second, CGF.PointerAlignInBytes); 1509 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; }); 1510 } 1511 } 1512 (void)Scope.Privatize(); 1513 if (*PartId) { 1514 // TODO: emit code for untied tasks. 1515 } 1516 CGF.EmitStmt(CS->getCapturedStmt()); 1517 }; 1518 auto OutlinedFn = 1519 CGM.getOpenMPRuntime().emitTaskOutlinedFunction(S, *I, CodeGen); 1520 // Check if we should emit tied or untied task. 1521 bool Tied = !S.getSingleClause(OMPC_untied); 1522 // Check if the task is final 1523 llvm::PointerIntPair<llvm::Value *, 1, bool> Final; 1524 if (auto *Clause = S.getSingleClause(OMPC_final)) { 1525 // If the condition constant folds and can be elided, try to avoid emitting 1526 // the condition and the dead arm of the if/else. 1527 auto *Cond = cast<OMPFinalClause>(Clause)->getCondition(); 1528 bool CondConstant; 1529 if (ConstantFoldsToSimpleInteger(Cond, CondConstant)) 1530 Final.setInt(CondConstant); 1531 else 1532 Final.setPointer(EvaluateExprAsBool(Cond)); 1533 } else { 1534 // By default the task is not final. 1535 Final.setInt(/*IntVal=*/false); 1536 } 1537 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 1538 const Expr *IfCond = nullptr; 1539 if (auto C = S.getSingleClause(OMPC_if)) { 1540 IfCond = cast<OMPIfClause>(C)->getCondition(); 1541 } 1542 CGM.getOpenMPRuntime().emitTaskCall( 1543 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy, 1544 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars, 1545 FirstprivateCopies, FirstprivateInits); 1546 } 1547 1548 void CodeGenFunction::EmitOMPTaskyieldDirective( 1549 const OMPTaskyieldDirective &S) { 1550 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart()); 1551 } 1552 1553 void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) { 1554 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier); 1555 } 1556 1557 void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) { 1558 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart()); 1559 } 1560 1561 void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) { 1562 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> { 1563 if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) { 1564 auto FlushClause = cast<OMPFlushClause>(C); 1565 return llvm::makeArrayRef(FlushClause->varlist_begin(), 1566 FlushClause->varlist_end()); 1567 } 1568 return llvm::None; 1569 }(), S.getLocStart()); 1570 } 1571 1572 void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) { 1573 LexicalScope Scope(*this, S.getSourceRange()); 1574 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 1575 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1576 CGF.EnsureInsertPoint(); 1577 }; 1578 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart()); 1579 } 1580 1581 static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val, 1582 QualType SrcType, QualType DestType) { 1583 assert(CGF.hasScalarEvaluationKind(DestType) && 1584 "DestType must have scalar evaluation kind."); 1585 assert(!Val.isAggregate() && "Must be a scalar or complex."); 1586 return Val.isScalar() 1587 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType) 1588 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType, 1589 DestType); 1590 } 1591 1592 static CodeGenFunction::ComplexPairTy 1593 convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType, 1594 QualType DestType) { 1595 assert(CGF.getEvaluationKind(DestType) == TEK_Complex && 1596 "DestType must have complex evaluation kind."); 1597 CodeGenFunction::ComplexPairTy ComplexVal; 1598 if (Val.isScalar()) { 1599 // Convert the input element to the element type of the complex. 1600 auto DestElementType = DestType->castAs<ComplexType>()->getElementType(); 1601 auto ScalarVal = 1602 CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestElementType); 1603 ComplexVal = CodeGenFunction::ComplexPairTy( 1604 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType())); 1605 } else { 1606 assert(Val.isComplex() && "Must be a scalar or complex."); 1607 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType(); 1608 auto DestElementType = DestType->castAs<ComplexType>()->getElementType(); 1609 ComplexVal.first = CGF.EmitScalarConversion( 1610 Val.getComplexVal().first, SrcElementType, DestElementType); 1611 ComplexVal.second = CGF.EmitScalarConversion( 1612 Val.getComplexVal().second, SrcElementType, DestElementType); 1613 } 1614 return ComplexVal; 1615 } 1616 1617 static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst, 1618 LValue LVal, RValue RVal) { 1619 if (LVal.isGlobalReg()) { 1620 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal); 1621 } else { 1622 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent 1623 : llvm::Monotonic, 1624 LVal.isVolatile(), /*IsInit=*/false); 1625 } 1626 } 1627 1628 static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal, 1629 QualType RValTy) { 1630 switch (CGF.getEvaluationKind(LVal.getType())) { 1631 case TEK_Scalar: 1632 CGF.EmitStoreThroughLValue( 1633 RValue::get(convertToScalarValue(CGF, RVal, RValTy, LVal.getType())), 1634 LVal); 1635 break; 1636 case TEK_Complex: 1637 CGF.EmitStoreOfComplex( 1638 convertToComplexValue(CGF, RVal, RValTy, LVal.getType()), LVal, 1639 /*isInit=*/false); 1640 break; 1641 case TEK_Aggregate: 1642 llvm_unreachable("Must be a scalar or complex."); 1643 } 1644 } 1645 1646 static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst, 1647 const Expr *X, const Expr *V, 1648 SourceLocation Loc) { 1649 // v = x; 1650 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue"); 1651 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue"); 1652 LValue XLValue = CGF.EmitLValue(X); 1653 LValue VLValue = CGF.EmitLValue(V); 1654 RValue Res = XLValue.isGlobalReg() 1655 ? CGF.EmitLoadOfLValue(XLValue, Loc) 1656 : CGF.EmitAtomicLoad(XLValue, Loc, 1657 IsSeqCst ? llvm::SequentiallyConsistent 1658 : llvm::Monotonic, 1659 XLValue.isVolatile()); 1660 // OpenMP, 2.12.6, atomic Construct 1661 // Any atomic construct with a seq_cst clause forces the atomically 1662 // performed operation to include an implicit flush operation without a 1663 // list. 1664 if (IsSeqCst) 1665 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc); 1666 emitSimpleStore(CGF,VLValue, Res, X->getType().getNonReferenceType()); 1667 } 1668 1669 static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst, 1670 const Expr *X, const Expr *E, 1671 SourceLocation Loc) { 1672 // x = expr; 1673 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue"); 1674 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E)); 1675 // OpenMP, 2.12.6, atomic Construct 1676 // Any atomic construct with a seq_cst clause forces the atomically 1677 // performed operation to include an implicit flush operation without a 1678 // list. 1679 if (IsSeqCst) 1680 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc); 1681 } 1682 1683 static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X, 1684 RValue Update, 1685 BinaryOperatorKind BO, 1686 llvm::AtomicOrdering AO, 1687 bool IsXLHSInRHSPart) { 1688 auto &Context = CGF.CGM.getContext(); 1689 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x' 1690 // expression is simple and atomic is allowed for the given type for the 1691 // target platform. 1692 if (BO == BO_Comma || !Update.isScalar() || 1693 !Update.getScalarVal()->getType()->isIntegerTy() || 1694 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) && 1695 (Update.getScalarVal()->getType() != 1696 X.getAddress()->getType()->getPointerElementType())) || 1697 !X.getAddress()->getType()->getPointerElementType()->isIntegerTy() || 1698 !Context.getTargetInfo().hasBuiltinAtomic( 1699 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment()))) 1700 return std::make_pair(false, RValue::get(nullptr)); 1701 1702 llvm::AtomicRMWInst::BinOp RMWOp; 1703 switch (BO) { 1704 case BO_Add: 1705 RMWOp = llvm::AtomicRMWInst::Add; 1706 break; 1707 case BO_Sub: 1708 if (!IsXLHSInRHSPart) 1709 return std::make_pair(false, RValue::get(nullptr)); 1710 RMWOp = llvm::AtomicRMWInst::Sub; 1711 break; 1712 case BO_And: 1713 RMWOp = llvm::AtomicRMWInst::And; 1714 break; 1715 case BO_Or: 1716 RMWOp = llvm::AtomicRMWInst::Or; 1717 break; 1718 case BO_Xor: 1719 RMWOp = llvm::AtomicRMWInst::Xor; 1720 break; 1721 case BO_LT: 1722 RMWOp = X.getType()->hasSignedIntegerRepresentation() 1723 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min 1724 : llvm::AtomicRMWInst::Max) 1725 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin 1726 : llvm::AtomicRMWInst::UMax); 1727 break; 1728 case BO_GT: 1729 RMWOp = X.getType()->hasSignedIntegerRepresentation() 1730 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max 1731 : llvm::AtomicRMWInst::Min) 1732 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax 1733 : llvm::AtomicRMWInst::UMin); 1734 break; 1735 case BO_Assign: 1736 RMWOp = llvm::AtomicRMWInst::Xchg; 1737 break; 1738 case BO_Mul: 1739 case BO_Div: 1740 case BO_Rem: 1741 case BO_Shl: 1742 case BO_Shr: 1743 case BO_LAnd: 1744 case BO_LOr: 1745 return std::make_pair(false, RValue::get(nullptr)); 1746 case BO_PtrMemD: 1747 case BO_PtrMemI: 1748 case BO_LE: 1749 case BO_GE: 1750 case BO_EQ: 1751 case BO_NE: 1752 case BO_AddAssign: 1753 case BO_SubAssign: 1754 case BO_AndAssign: 1755 case BO_OrAssign: 1756 case BO_XorAssign: 1757 case BO_MulAssign: 1758 case BO_DivAssign: 1759 case BO_RemAssign: 1760 case BO_ShlAssign: 1761 case BO_ShrAssign: 1762 case BO_Comma: 1763 llvm_unreachable("Unsupported atomic update operation"); 1764 } 1765 auto *UpdateVal = Update.getScalarVal(); 1766 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) { 1767 UpdateVal = CGF.Builder.CreateIntCast( 1768 IC, X.getAddress()->getType()->getPointerElementType(), 1769 X.getType()->hasSignedIntegerRepresentation()); 1770 } 1771 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getAddress(), UpdateVal, AO); 1772 return std::make_pair(true, RValue::get(Res)); 1773 } 1774 1775 std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr( 1776 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart, 1777 llvm::AtomicOrdering AO, SourceLocation Loc, 1778 const llvm::function_ref<RValue(RValue)> &CommonGen) { 1779 // Update expressions are allowed to have the following forms: 1780 // x binop= expr; -> xrval + expr; 1781 // x++, ++x -> xrval + 1; 1782 // x--, --x -> xrval - 1; 1783 // x = x binop expr; -> xrval binop expr 1784 // x = expr Op x; - > expr binop xrval; 1785 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart); 1786 if (!Res.first) { 1787 if (X.isGlobalReg()) { 1788 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop 1789 // 'xrval'. 1790 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X); 1791 } else { 1792 // Perform compare-and-swap procedure. 1793 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified()); 1794 } 1795 } 1796 return Res; 1797 } 1798 1799 static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst, 1800 const Expr *X, const Expr *E, 1801 const Expr *UE, bool IsXLHSInRHSPart, 1802 SourceLocation Loc) { 1803 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) && 1804 "Update expr in 'atomic update' must be a binary operator."); 1805 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts()); 1806 // Update expressions are allowed to have the following forms: 1807 // x binop= expr; -> xrval + expr; 1808 // x++, ++x -> xrval + 1; 1809 // x--, --x -> xrval - 1; 1810 // x = x binop expr; -> xrval binop expr 1811 // x = expr Op x; - > expr binop xrval; 1812 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue"); 1813 LValue XLValue = CGF.EmitLValue(X); 1814 RValue ExprRValue = CGF.EmitAnyExpr(E); 1815 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic; 1816 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts()); 1817 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts()); 1818 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS; 1819 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS; 1820 auto Gen = 1821 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue { 1822 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 1823 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue); 1824 return CGF.EmitAnyExpr(UE); 1825 }; 1826 (void)CGF.EmitOMPAtomicSimpleUpdateExpr( 1827 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen); 1828 // OpenMP, 2.12.6, atomic Construct 1829 // Any atomic construct with a seq_cst clause forces the atomically 1830 // performed operation to include an implicit flush operation without a 1831 // list. 1832 if (IsSeqCst) 1833 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc); 1834 } 1835 1836 static RValue convertToType(CodeGenFunction &CGF, RValue Value, 1837 QualType SourceType, QualType ResType) { 1838 switch (CGF.getEvaluationKind(ResType)) { 1839 case TEK_Scalar: 1840 return RValue::get(convertToScalarValue(CGF, Value, SourceType, ResType)); 1841 case TEK_Complex: { 1842 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType); 1843 return RValue::getComplex(Res.first, Res.second); 1844 } 1845 case TEK_Aggregate: 1846 break; 1847 } 1848 llvm_unreachable("Must be a scalar or complex."); 1849 } 1850 1851 static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst, 1852 bool IsPostfixUpdate, const Expr *V, 1853 const Expr *X, const Expr *E, 1854 const Expr *UE, bool IsXLHSInRHSPart, 1855 SourceLocation Loc) { 1856 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue"); 1857 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue"); 1858 RValue NewVVal; 1859 LValue VLValue = CGF.EmitLValue(V); 1860 LValue XLValue = CGF.EmitLValue(X); 1861 RValue ExprRValue = CGF.EmitAnyExpr(E); 1862 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic; 1863 QualType NewVValType; 1864 if (UE) { 1865 // 'x' is updated with some additional value. 1866 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) && 1867 "Update expr in 'atomic capture' must be a binary operator."); 1868 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts()); 1869 // Update expressions are allowed to have the following forms: 1870 // x binop= expr; -> xrval + expr; 1871 // x++, ++x -> xrval + 1; 1872 // x--, --x -> xrval - 1; 1873 // x = x binop expr; -> xrval binop expr 1874 // x = expr Op x; - > expr binop xrval; 1875 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts()); 1876 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts()); 1877 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS; 1878 NewVValType = XRValExpr->getType(); 1879 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS; 1880 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr, 1881 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue { 1882 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 1883 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue); 1884 RValue Res = CGF.EmitAnyExpr(UE); 1885 NewVVal = IsPostfixUpdate ? XRValue : Res; 1886 return Res; 1887 }; 1888 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr( 1889 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen); 1890 if (Res.first) { 1891 // 'atomicrmw' instruction was generated. 1892 if (IsPostfixUpdate) { 1893 // Use old value from 'atomicrmw'. 1894 NewVVal = Res.second; 1895 } else { 1896 // 'atomicrmw' does not provide new value, so evaluate it using old 1897 // value of 'x'. 1898 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 1899 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second); 1900 NewVVal = CGF.EmitAnyExpr(UE); 1901 } 1902 } 1903 } else { 1904 // 'x' is simply rewritten with some 'expr'. 1905 NewVValType = X->getType().getNonReferenceType(); 1906 ExprRValue = convertToType(CGF, ExprRValue, E->getType(), 1907 X->getType().getNonReferenceType()); 1908 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue { 1909 NewVVal = XRValue; 1910 return ExprRValue; 1911 }; 1912 // Try to perform atomicrmw xchg, otherwise simple exchange. 1913 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr( 1914 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO, 1915 Loc, Gen); 1916 if (Res.first) { 1917 // 'atomicrmw' instruction was generated. 1918 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue; 1919 } 1920 } 1921 // Emit post-update store to 'v' of old/new 'x' value. 1922 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType); 1923 // OpenMP, 2.12.6, atomic Construct 1924 // Any atomic construct with a seq_cst clause forces the atomically 1925 // performed operation to include an implicit flush operation without a 1926 // list. 1927 if (IsSeqCst) 1928 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc); 1929 } 1930 1931 static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind, 1932 bool IsSeqCst, bool IsPostfixUpdate, 1933 const Expr *X, const Expr *V, const Expr *E, 1934 const Expr *UE, bool IsXLHSInRHSPart, 1935 SourceLocation Loc) { 1936 switch (Kind) { 1937 case OMPC_read: 1938 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc); 1939 break; 1940 case OMPC_write: 1941 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc); 1942 break; 1943 case OMPC_unknown: 1944 case OMPC_update: 1945 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc); 1946 break; 1947 case OMPC_capture: 1948 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE, 1949 IsXLHSInRHSPart, Loc); 1950 break; 1951 case OMPC_if: 1952 case OMPC_final: 1953 case OMPC_num_threads: 1954 case OMPC_private: 1955 case OMPC_firstprivate: 1956 case OMPC_lastprivate: 1957 case OMPC_reduction: 1958 case OMPC_safelen: 1959 case OMPC_collapse: 1960 case OMPC_default: 1961 case OMPC_seq_cst: 1962 case OMPC_shared: 1963 case OMPC_linear: 1964 case OMPC_aligned: 1965 case OMPC_copyin: 1966 case OMPC_copyprivate: 1967 case OMPC_flush: 1968 case OMPC_proc_bind: 1969 case OMPC_schedule: 1970 case OMPC_ordered: 1971 case OMPC_nowait: 1972 case OMPC_untied: 1973 case OMPC_threadprivate: 1974 case OMPC_mergeable: 1975 llvm_unreachable("Clause is not allowed in 'omp atomic'."); 1976 } 1977 } 1978 1979 void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) { 1980 bool IsSeqCst = S.getSingleClause(/*K=*/OMPC_seq_cst); 1981 OpenMPClauseKind Kind = OMPC_unknown; 1982 for (auto *C : S.clauses()) { 1983 // Find first clause (skip seq_cst clause, if it is first). 1984 if (C->getClauseKind() != OMPC_seq_cst) { 1985 Kind = C->getClauseKind(); 1986 break; 1987 } 1988 } 1989 1990 const auto *CS = 1991 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true); 1992 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) { 1993 enterFullExpression(EWC); 1994 } 1995 // Processing for statements under 'atomic capture'. 1996 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) { 1997 for (const auto *C : Compound->body()) { 1998 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) { 1999 enterFullExpression(EWC); 2000 } 2001 } 2002 } 2003 2004 LexicalScope Scope(*this, S.getSourceRange()); 2005 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) { 2006 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(), 2007 S.getV(), S.getExpr(), S.getUpdateExpr(), 2008 S.isXLHSInRHSPart(), S.getLocStart()); 2009 }; 2010 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen); 2011 } 2012 2013 void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) { 2014 llvm_unreachable("CodeGen for 'omp target' is not supported yet."); 2015 } 2016 2017 void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) { 2018 llvm_unreachable("CodeGen for 'omp teams' is not supported yet."); 2019 } 2020