1 //===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===// 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 contains code to emit OpenMP nodes as LLVM code. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CGCleanup.h" 14 #include "CGOpenMPRuntime.h" 15 #include "CodeGenFunction.h" 16 #include "CodeGenModule.h" 17 #include "TargetInfo.h" 18 #include "clang/AST/ASTContext.h" 19 #include "clang/AST/Attr.h" 20 #include "clang/AST/DeclOpenMP.h" 21 #include "clang/AST/OpenMPClause.h" 22 #include "clang/AST/Stmt.h" 23 #include "clang/AST/StmtOpenMP.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/Basic/OpenMPKinds.h" 26 #include "clang/Basic/PrettyStackTrace.h" 27 #include "llvm/Frontend/OpenMP/OMPConstants.h" 28 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 29 #include "llvm/IR/Constants.h" 30 #include "llvm/IR/Instructions.h" 31 #include "llvm/Support/AtomicOrdering.h" 32 using namespace clang; 33 using namespace CodeGen; 34 using namespace llvm::omp; 35 36 static const VarDecl *getBaseDecl(const Expr *Ref); 37 38 namespace { 39 /// Lexical scope for OpenMP executable constructs, that handles correct codegen 40 /// for captured expressions. 41 class OMPLexicalScope : public CodeGenFunction::LexicalScope { 42 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) { 43 for (const auto *C : S.clauses()) { 44 if (const auto *CPI = OMPClauseWithPreInit::get(C)) { 45 if (const auto *PreInit = 46 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) { 47 for (const auto *I : PreInit->decls()) { 48 if (!I->hasAttr<OMPCaptureNoInitAttr>()) { 49 CGF.EmitVarDecl(cast<VarDecl>(*I)); 50 } else { 51 CodeGenFunction::AutoVarEmission Emission = 52 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I)); 53 CGF.EmitAutoVarCleanups(Emission); 54 } 55 } 56 } 57 } 58 } 59 } 60 CodeGenFunction::OMPPrivateScope InlinedShareds; 61 62 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) { 63 return CGF.LambdaCaptureFields.lookup(VD) || 64 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) || 65 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) && 66 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD)); 67 } 68 69 public: 70 OMPLexicalScope( 71 CodeGenFunction &CGF, const OMPExecutableDirective &S, 72 const llvm::Optional<OpenMPDirectiveKind> CapturedRegion = llvm::None, 73 const bool EmitPreInitStmt = true) 74 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()), 75 InlinedShareds(CGF) { 76 if (EmitPreInitStmt) 77 emitPreInitStmt(CGF, S); 78 if (!CapturedRegion.hasValue()) 79 return; 80 assert(S.hasAssociatedStmt() && 81 "Expected associated statement for inlined directive."); 82 const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion); 83 for (const auto &C : CS->captures()) { 84 if (C.capturesVariable() || C.capturesVariableByCopy()) { 85 auto *VD = C.getCapturedVar(); 86 assert(VD == VD->getCanonicalDecl() && 87 "Canonical decl must be captured."); 88 DeclRefExpr DRE( 89 CGF.getContext(), const_cast<VarDecl *>(VD), 90 isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo && 91 InlinedShareds.isGlobalVarCaptured(VD)), 92 VD->getType().getNonReferenceType(), VK_LValue, C.getLocation()); 93 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address { 94 return CGF.EmitLValue(&DRE).getAddress(CGF); 95 }); 96 } 97 } 98 (void)InlinedShareds.Privatize(); 99 } 100 }; 101 102 /// Lexical scope for OpenMP parallel construct, that handles correct codegen 103 /// for captured expressions. 104 class OMPParallelScope final : public OMPLexicalScope { 105 bool EmitPreInitStmt(const OMPExecutableDirective &S) { 106 OpenMPDirectiveKind Kind = S.getDirectiveKind(); 107 return !(isOpenMPTargetExecutionDirective(Kind) || 108 isOpenMPLoopBoundSharingDirective(Kind)) && 109 isOpenMPParallelDirective(Kind); 110 } 111 112 public: 113 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S) 114 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None, 115 EmitPreInitStmt(S)) {} 116 }; 117 118 /// Lexical scope for OpenMP teams construct, that handles correct codegen 119 /// for captured expressions. 120 class OMPTeamsScope final : public OMPLexicalScope { 121 bool EmitPreInitStmt(const OMPExecutableDirective &S) { 122 OpenMPDirectiveKind Kind = S.getDirectiveKind(); 123 return !isOpenMPTargetExecutionDirective(Kind) && 124 isOpenMPTeamsDirective(Kind); 125 } 126 127 public: 128 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S) 129 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None, 130 EmitPreInitStmt(S)) {} 131 }; 132 133 /// Private scope for OpenMP loop-based directives, that supports capturing 134 /// of used expression from loop statement. 135 class OMPLoopScope : public CodeGenFunction::RunCleanupsScope { 136 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopBasedDirective &S) { 137 const DeclStmt *PreInits; 138 CodeGenFunction::OMPMapVars PreCondVars; 139 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) { 140 llvm::DenseSet<const VarDecl *> EmittedAsPrivate; 141 for (const auto *E : LD->counters()) { 142 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 143 EmittedAsPrivate.insert(VD->getCanonicalDecl()); 144 (void)PreCondVars.setVarAddr( 145 CGF, VD, CGF.CreateMemTemp(VD->getType().getNonReferenceType())); 146 } 147 // Mark private vars as undefs. 148 for (const auto *C : LD->getClausesOfKind<OMPPrivateClause>()) { 149 for (const Expr *IRef : C->varlists()) { 150 const auto *OrigVD = 151 cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl()); 152 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 153 (void)PreCondVars.setVarAddr( 154 CGF, OrigVD, 155 Address(llvm::UndefValue::get(CGF.ConvertTypeForMem( 156 CGF.getContext().getPointerType( 157 OrigVD->getType().getNonReferenceType()))), 158 CGF.getContext().getDeclAlign(OrigVD))); 159 } 160 } 161 } 162 (void)PreCondVars.apply(CGF); 163 // Emit init, __range and __end variables for C++ range loops. 164 (void)OMPLoopBasedDirective::doForAllLoops( 165 LD->getInnermostCapturedStmt()->getCapturedStmt(), 166 /*TryImperfectlyNestedLoops=*/true, LD->getLoopsNumber(), 167 [&CGF](unsigned Cnt, const Stmt *CurStmt) { 168 if (const auto *CXXFor = dyn_cast<CXXForRangeStmt>(CurStmt)) { 169 if (const Stmt *Init = CXXFor->getInit()) 170 CGF.EmitStmt(Init); 171 CGF.EmitStmt(CXXFor->getRangeStmt()); 172 CGF.EmitStmt(CXXFor->getEndStmt()); 173 } 174 return false; 175 }); 176 PreInits = cast_or_null<DeclStmt>(LD->getPreInits()); 177 } else if (const auto *Tile = dyn_cast<OMPTileDirective>(&S)) { 178 PreInits = cast_or_null<DeclStmt>(Tile->getPreInits()); 179 } else { 180 llvm_unreachable("Unknown loop-based directive kind."); 181 } 182 if (PreInits) { 183 for (const auto *I : PreInits->decls()) 184 CGF.EmitVarDecl(cast<VarDecl>(*I)); 185 } 186 PreCondVars.restore(CGF); 187 } 188 189 public: 190 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopBasedDirective &S) 191 : CodeGenFunction::RunCleanupsScope(CGF) { 192 emitPreInitStmt(CGF, S); 193 } 194 }; 195 196 class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope { 197 CodeGenFunction::OMPPrivateScope InlinedShareds; 198 199 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) { 200 return CGF.LambdaCaptureFields.lookup(VD) || 201 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) || 202 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) && 203 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD)); 204 } 205 206 public: 207 OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S) 208 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()), 209 InlinedShareds(CGF) { 210 for (const auto *C : S.clauses()) { 211 if (const auto *CPI = OMPClauseWithPreInit::get(C)) { 212 if (const auto *PreInit = 213 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) { 214 for (const auto *I : PreInit->decls()) { 215 if (!I->hasAttr<OMPCaptureNoInitAttr>()) { 216 CGF.EmitVarDecl(cast<VarDecl>(*I)); 217 } else { 218 CodeGenFunction::AutoVarEmission Emission = 219 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I)); 220 CGF.EmitAutoVarCleanups(Emission); 221 } 222 } 223 } 224 } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) { 225 for (const Expr *E : UDP->varlists()) { 226 const Decl *D = cast<DeclRefExpr>(E)->getDecl(); 227 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D)) 228 CGF.EmitVarDecl(*OED); 229 } 230 } else if (const auto *UDP = dyn_cast<OMPUseDeviceAddrClause>(C)) { 231 for (const Expr *E : UDP->varlists()) { 232 const Decl *D = getBaseDecl(E); 233 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D)) 234 CGF.EmitVarDecl(*OED); 235 } 236 } 237 } 238 if (!isOpenMPSimdDirective(S.getDirectiveKind())) 239 CGF.EmitOMPPrivateClause(S, InlinedShareds); 240 if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) { 241 if (const Expr *E = TG->getReductionRef()) 242 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())); 243 } 244 const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt()); 245 while (CS) { 246 for (auto &C : CS->captures()) { 247 if (C.capturesVariable() || C.capturesVariableByCopy()) { 248 auto *VD = C.getCapturedVar(); 249 assert(VD == VD->getCanonicalDecl() && 250 "Canonical decl must be captured."); 251 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD), 252 isCapturedVar(CGF, VD) || 253 (CGF.CapturedStmtInfo && 254 InlinedShareds.isGlobalVarCaptured(VD)), 255 VD->getType().getNonReferenceType(), VK_LValue, 256 C.getLocation()); 257 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address { 258 return CGF.EmitLValue(&DRE).getAddress(CGF); 259 }); 260 } 261 } 262 CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt()); 263 } 264 (void)InlinedShareds.Privatize(); 265 } 266 }; 267 268 } // namespace 269 270 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF, 271 const OMPExecutableDirective &S, 272 const RegionCodeGenTy &CodeGen); 273 274 LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) { 275 if (const auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) { 276 if (const auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) { 277 OrigVD = OrigVD->getCanonicalDecl(); 278 bool IsCaptured = 279 LambdaCaptureFields.lookup(OrigVD) || 280 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) || 281 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl)); 282 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), IsCaptured, 283 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc()); 284 return EmitLValue(&DRE); 285 } 286 } 287 return EmitLValue(E); 288 } 289 290 llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) { 291 ASTContext &C = getContext(); 292 llvm::Value *Size = nullptr; 293 auto SizeInChars = C.getTypeSizeInChars(Ty); 294 if (SizeInChars.isZero()) { 295 // getTypeSizeInChars() returns 0 for a VLA. 296 while (const VariableArrayType *VAT = C.getAsVariableArrayType(Ty)) { 297 VlaSizePair VlaSize = getVLASize(VAT); 298 Ty = VlaSize.Type; 299 Size = Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts) 300 : VlaSize.NumElts; 301 } 302 SizeInChars = C.getTypeSizeInChars(Ty); 303 if (SizeInChars.isZero()) 304 return llvm::ConstantInt::get(SizeTy, /*V=*/0); 305 return Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars)); 306 } 307 return CGM.getSize(SizeInChars); 308 } 309 310 void CodeGenFunction::GenerateOpenMPCapturedVars( 311 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) { 312 const RecordDecl *RD = S.getCapturedRecordDecl(); 313 auto CurField = RD->field_begin(); 314 auto CurCap = S.captures().begin(); 315 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(), 316 E = S.capture_init_end(); 317 I != E; ++I, ++CurField, ++CurCap) { 318 if (CurField->hasCapturedVLAType()) { 319 const VariableArrayType *VAT = CurField->getCapturedVLAType(); 320 llvm::Value *Val = VLASizeMap[VAT->getSizeExpr()]; 321 CapturedVars.push_back(Val); 322 } else if (CurCap->capturesThis()) { 323 CapturedVars.push_back(CXXThisValue); 324 } else if (CurCap->capturesVariableByCopy()) { 325 llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation()); 326 327 // If the field is not a pointer, we need to save the actual value 328 // and load it as a void pointer. 329 if (!CurField->getType()->isAnyPointerType()) { 330 ASTContext &Ctx = getContext(); 331 Address DstAddr = CreateMemTemp( 332 Ctx.getUIntPtrType(), 333 Twine(CurCap->getCapturedVar()->getName(), ".casted")); 334 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType()); 335 336 llvm::Value *SrcAddrVal = EmitScalarConversion( 337 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()), 338 Ctx.getPointerType(CurField->getType()), CurCap->getLocation()); 339 LValue SrcLV = 340 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType()); 341 342 // Store the value using the source type pointer. 343 EmitStoreThroughLValue(RValue::get(CV), SrcLV); 344 345 // Load the value using the destination type pointer. 346 CV = EmitLoadOfScalar(DstLV, CurCap->getLocation()); 347 } 348 CapturedVars.push_back(CV); 349 } else { 350 assert(CurCap->capturesVariable() && "Expected capture by reference."); 351 CapturedVars.push_back(EmitLValue(*I).getAddress(*this).getPointer()); 352 } 353 } 354 } 355 356 static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc, 357 QualType DstType, StringRef Name, 358 LValue AddrLV) { 359 ASTContext &Ctx = CGF.getContext(); 360 361 llvm::Value *CastedPtr = CGF.EmitScalarConversion( 362 AddrLV.getAddress(CGF).getPointer(), Ctx.getUIntPtrType(), 363 Ctx.getPointerType(DstType), Loc); 364 Address TmpAddr = 365 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType)) 366 .getAddress(CGF); 367 return TmpAddr; 368 } 369 370 static QualType getCanonicalParamType(ASTContext &C, QualType T) { 371 if (T->isLValueReferenceType()) 372 return C.getLValueReferenceType( 373 getCanonicalParamType(C, T.getNonReferenceType()), 374 /*SpelledAsLValue=*/false); 375 if (T->isPointerType()) 376 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType())); 377 if (const ArrayType *A = T->getAsArrayTypeUnsafe()) { 378 if (const auto *VLA = dyn_cast<VariableArrayType>(A)) 379 return getCanonicalParamType(C, VLA->getElementType()); 380 if (!A->isVariablyModifiedType()) 381 return C.getCanonicalType(T); 382 } 383 return C.getCanonicalParamType(T); 384 } 385 386 namespace { 387 /// Contains required data for proper outlined function codegen. 388 struct FunctionOptions { 389 /// Captured statement for which the function is generated. 390 const CapturedStmt *S = nullptr; 391 /// true if cast to/from UIntPtr is required for variables captured by 392 /// value. 393 const bool UIntPtrCastRequired = true; 394 /// true if only casted arguments must be registered as local args or VLA 395 /// sizes. 396 const bool RegisterCastedArgsOnly = false; 397 /// Name of the generated function. 398 const StringRef FunctionName; 399 /// Location of the non-debug version of the outlined function. 400 SourceLocation Loc; 401 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired, 402 bool RegisterCastedArgsOnly, StringRef FunctionName, 403 SourceLocation Loc) 404 : S(S), UIntPtrCastRequired(UIntPtrCastRequired), 405 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly), 406 FunctionName(FunctionName), Loc(Loc) {} 407 }; 408 } // namespace 409 410 static llvm::Function *emitOutlinedFunctionPrologue( 411 CodeGenFunction &CGF, FunctionArgList &Args, 412 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> 413 &LocalAddrs, 414 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> 415 &VLASizes, 416 llvm::Value *&CXXThisValue, const FunctionOptions &FO) { 417 const CapturedDecl *CD = FO.S->getCapturedDecl(); 418 const RecordDecl *RD = FO.S->getCapturedRecordDecl(); 419 assert(CD->hasBody() && "missing CapturedDecl body"); 420 421 CXXThisValue = nullptr; 422 // Build the argument list. 423 CodeGenModule &CGM = CGF.CGM; 424 ASTContext &Ctx = CGM.getContext(); 425 FunctionArgList TargetArgs; 426 Args.append(CD->param_begin(), 427 std::next(CD->param_begin(), CD->getContextParamPosition())); 428 TargetArgs.append( 429 CD->param_begin(), 430 std::next(CD->param_begin(), CD->getContextParamPosition())); 431 auto I = FO.S->captures().begin(); 432 FunctionDecl *DebugFunctionDecl = nullptr; 433 if (!FO.UIntPtrCastRequired) { 434 FunctionProtoType::ExtProtoInfo EPI; 435 QualType FunctionTy = Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI); 436 DebugFunctionDecl = FunctionDecl::Create( 437 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getBeginLoc(), 438 SourceLocation(), DeclarationName(), FunctionTy, 439 Ctx.getTrivialTypeSourceInfo(FunctionTy), SC_Static, 440 /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false); 441 } 442 for (const FieldDecl *FD : RD->fields()) { 443 QualType ArgType = FD->getType(); 444 IdentifierInfo *II = nullptr; 445 VarDecl *CapVar = nullptr; 446 447 // If this is a capture by copy and the type is not a pointer, the outlined 448 // function argument type should be uintptr and the value properly casted to 449 // uintptr. This is necessary given that the runtime library is only able to 450 // deal with pointers. We can pass in the same way the VLA type sizes to the 451 // outlined function. 452 if (FO.UIntPtrCastRequired && 453 ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) || 454 I->capturesVariableArrayType())) 455 ArgType = Ctx.getUIntPtrType(); 456 457 if (I->capturesVariable() || I->capturesVariableByCopy()) { 458 CapVar = I->getCapturedVar(); 459 II = CapVar->getIdentifier(); 460 } else if (I->capturesThis()) { 461 II = &Ctx.Idents.get("this"); 462 } else { 463 assert(I->capturesVariableArrayType()); 464 II = &Ctx.Idents.get("vla"); 465 } 466 if (ArgType->isVariablyModifiedType()) 467 ArgType = getCanonicalParamType(Ctx, ArgType); 468 VarDecl *Arg; 469 if (DebugFunctionDecl && (CapVar || I->capturesThis())) { 470 Arg = ParmVarDecl::Create( 471 Ctx, DebugFunctionDecl, 472 CapVar ? CapVar->getBeginLoc() : FD->getBeginLoc(), 473 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType, 474 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr); 475 } else { 476 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(), 477 II, ArgType, ImplicitParamDecl::Other); 478 } 479 Args.emplace_back(Arg); 480 // Do not cast arguments if we emit function with non-original types. 481 TargetArgs.emplace_back( 482 FO.UIntPtrCastRequired 483 ? Arg 484 : CGM.getOpenMPRuntime().translateParameter(FD, Arg)); 485 ++I; 486 } 487 Args.append( 488 std::next(CD->param_begin(), CD->getContextParamPosition() + 1), 489 CD->param_end()); 490 TargetArgs.append( 491 std::next(CD->param_begin(), CD->getContextParamPosition() + 1), 492 CD->param_end()); 493 494 // Create the function declaration. 495 const CGFunctionInfo &FuncInfo = 496 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs); 497 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo); 498 499 auto *F = 500 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage, 501 FO.FunctionName, &CGM.getModule()); 502 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo); 503 if (CD->isNothrow()) 504 F->setDoesNotThrow(); 505 F->setDoesNotRecurse(); 506 507 // Generate the function. 508 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs, 509 FO.UIntPtrCastRequired ? FO.Loc : FO.S->getBeginLoc(), 510 FO.UIntPtrCastRequired ? FO.Loc 511 : CD->getBody()->getBeginLoc()); 512 unsigned Cnt = CD->getContextParamPosition(); 513 I = FO.S->captures().begin(); 514 for (const FieldDecl *FD : RD->fields()) { 515 // Do not map arguments if we emit function with non-original types. 516 Address LocalAddr(Address::invalid()); 517 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) { 518 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt], 519 TargetArgs[Cnt]); 520 } else { 521 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]); 522 } 523 // If we are capturing a pointer by copy we don't need to do anything, just 524 // use the value that we get from the arguments. 525 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) { 526 const VarDecl *CurVD = I->getCapturedVar(); 527 if (!FO.RegisterCastedArgsOnly) 528 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}}); 529 ++Cnt; 530 ++I; 531 continue; 532 } 533 534 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(), 535 AlignmentSource::Decl); 536 if (FD->hasCapturedVLAType()) { 537 if (FO.UIntPtrCastRequired) { 538 ArgLVal = CGF.MakeAddrLValue( 539 castValueFromUintptr(CGF, I->getLocation(), FD->getType(), 540 Args[Cnt]->getName(), ArgLVal), 541 FD->getType(), AlignmentSource::Decl); 542 } 543 llvm::Value *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation()); 544 const VariableArrayType *VAT = FD->getCapturedVLAType(); 545 VLASizes.try_emplace(Args[Cnt], VAT->getSizeExpr(), ExprArg); 546 } else if (I->capturesVariable()) { 547 const VarDecl *Var = I->getCapturedVar(); 548 QualType VarTy = Var->getType(); 549 Address ArgAddr = ArgLVal.getAddress(CGF); 550 if (ArgLVal.getType()->isLValueReferenceType()) { 551 ArgAddr = CGF.EmitLoadOfReference(ArgLVal); 552 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) { 553 assert(ArgLVal.getType()->isPointerType()); 554 ArgAddr = CGF.EmitLoadOfPointer( 555 ArgAddr, ArgLVal.getType()->castAs<PointerType>()); 556 } 557 if (!FO.RegisterCastedArgsOnly) { 558 LocalAddrs.insert( 559 {Args[Cnt], 560 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}}); 561 } 562 } else if (I->capturesVariableByCopy()) { 563 assert(!FD->getType()->isAnyPointerType() && 564 "Not expecting a captured pointer."); 565 const VarDecl *Var = I->getCapturedVar(); 566 LocalAddrs.insert({Args[Cnt], 567 {Var, FO.UIntPtrCastRequired 568 ? castValueFromUintptr( 569 CGF, I->getLocation(), FD->getType(), 570 Args[Cnt]->getName(), ArgLVal) 571 : ArgLVal.getAddress(CGF)}}); 572 } else { 573 // If 'this' is captured, load it into CXXThisValue. 574 assert(I->capturesThis()); 575 CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation()); 576 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress(CGF)}}); 577 } 578 ++Cnt; 579 ++I; 580 } 581 582 return F; 583 } 584 585 llvm::Function * 586 CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S, 587 SourceLocation Loc) { 588 assert( 589 CapturedStmtInfo && 590 "CapturedStmtInfo should be set when generating the captured function"); 591 const CapturedDecl *CD = S.getCapturedDecl(); 592 // Build the argument list. 593 bool NeedWrapperFunction = 594 getDebugInfo() && CGM.getCodeGenOpts().hasReducedDebugInfo(); 595 FunctionArgList Args; 596 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs; 597 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes; 598 SmallString<256> Buffer; 599 llvm::raw_svector_ostream Out(Buffer); 600 Out << CapturedStmtInfo->getHelperName(); 601 if (NeedWrapperFunction) 602 Out << "_debug__"; 603 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false, 604 Out.str(), Loc); 605 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs, 606 VLASizes, CXXThisValue, FO); 607 CodeGenFunction::OMPPrivateScope LocalScope(*this); 608 for (const auto &LocalAddrPair : LocalAddrs) { 609 if (LocalAddrPair.second.first) { 610 LocalScope.addPrivate(LocalAddrPair.second.first, [&LocalAddrPair]() { 611 return LocalAddrPair.second.second; 612 }); 613 } 614 } 615 (void)LocalScope.Privatize(); 616 for (const auto &VLASizePair : VLASizes) 617 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second; 618 PGO.assignRegionCounters(GlobalDecl(CD), F); 619 CapturedStmtInfo->EmitBody(*this, CD->getBody()); 620 (void)LocalScope.ForceCleanup(); 621 FinishFunction(CD->getBodyRBrace()); 622 if (!NeedWrapperFunction) 623 return F; 624 625 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true, 626 /*RegisterCastedArgsOnly=*/true, 627 CapturedStmtInfo->getHelperName(), Loc); 628 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true); 629 WrapperCGF.CapturedStmtInfo = CapturedStmtInfo; 630 Args.clear(); 631 LocalAddrs.clear(); 632 VLASizes.clear(); 633 llvm::Function *WrapperF = 634 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes, 635 WrapperCGF.CXXThisValue, WrapperFO); 636 llvm::SmallVector<llvm::Value *, 4> CallArgs; 637 for (const auto *Arg : Args) { 638 llvm::Value *CallArg; 639 auto I = LocalAddrs.find(Arg); 640 if (I != LocalAddrs.end()) { 641 LValue LV = WrapperCGF.MakeAddrLValue( 642 I->second.second, 643 I->second.first ? I->second.first->getType() : Arg->getType(), 644 AlignmentSource::Decl); 645 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc()); 646 } else { 647 auto EI = VLASizes.find(Arg); 648 if (EI != VLASizes.end()) { 649 CallArg = EI->second.second; 650 } else { 651 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg), 652 Arg->getType(), 653 AlignmentSource::Decl); 654 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc()); 655 } 656 } 657 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType())); 658 } 659 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, Loc, F, CallArgs); 660 WrapperCGF.FinishFunction(); 661 return WrapperF; 662 } 663 664 //===----------------------------------------------------------------------===// 665 // OpenMP Directive Emission 666 //===----------------------------------------------------------------------===// 667 void CodeGenFunction::EmitOMPAggregateAssign( 668 Address DestAddr, Address SrcAddr, QualType OriginalType, 669 const llvm::function_ref<void(Address, Address)> CopyGen) { 670 // Perform element-by-element initialization. 671 QualType ElementTy; 672 673 // Drill down to the base element type on both arrays. 674 const ArrayType *ArrayTy = OriginalType->getAsArrayTypeUnsafe(); 675 llvm::Value *NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr); 676 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType()); 677 678 llvm::Value *SrcBegin = SrcAddr.getPointer(); 679 llvm::Value *DestBegin = DestAddr.getPointer(); 680 // Cast from pointer to array type to pointer to single element. 681 llvm::Value *DestEnd = Builder.CreateGEP(DestBegin, NumElements); 682 // The basic structure here is a while-do loop. 683 llvm::BasicBlock *BodyBB = createBasicBlock("omp.arraycpy.body"); 684 llvm::BasicBlock *DoneBB = createBasicBlock("omp.arraycpy.done"); 685 llvm::Value *IsEmpty = 686 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty"); 687 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB); 688 689 // Enter the loop body, making that address the current address. 690 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock(); 691 EmitBlock(BodyBB); 692 693 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy); 694 695 llvm::PHINode *SrcElementPHI = 696 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast"); 697 SrcElementPHI->addIncoming(SrcBegin, EntryBB); 698 Address SrcElementCurrent = 699 Address(SrcElementPHI, 700 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize)); 701 702 llvm::PHINode *DestElementPHI = 703 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast"); 704 DestElementPHI->addIncoming(DestBegin, EntryBB); 705 Address DestElementCurrent = 706 Address(DestElementPHI, 707 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize)); 708 709 // Emit copy. 710 CopyGen(DestElementCurrent, SrcElementCurrent); 711 712 // Shift the address forward by one element. 713 llvm::Value *DestElementNext = Builder.CreateConstGEP1_32( 714 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element"); 715 llvm::Value *SrcElementNext = Builder.CreateConstGEP1_32( 716 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element"); 717 // Check whether we've reached the end. 718 llvm::Value *Done = 719 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done"); 720 Builder.CreateCondBr(Done, DoneBB, BodyBB); 721 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock()); 722 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock()); 723 724 // Done. 725 EmitBlock(DoneBB, /*IsFinished=*/true); 726 } 727 728 void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr, 729 Address SrcAddr, const VarDecl *DestVD, 730 const VarDecl *SrcVD, const Expr *Copy) { 731 if (OriginalType->isArrayType()) { 732 const auto *BO = dyn_cast<BinaryOperator>(Copy); 733 if (BO && BO->getOpcode() == BO_Assign) { 734 // Perform simple memcpy for simple copying. 735 LValue Dest = MakeAddrLValue(DestAddr, OriginalType); 736 LValue Src = MakeAddrLValue(SrcAddr, OriginalType); 737 EmitAggregateAssign(Dest, Src, OriginalType); 738 } else { 739 // For arrays with complex element types perform element by element 740 // copying. 741 EmitOMPAggregateAssign( 742 DestAddr, SrcAddr, OriginalType, 743 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) { 744 // Working with the single array element, so have to remap 745 // destination and source variables to corresponding array 746 // elements. 747 CodeGenFunction::OMPPrivateScope Remap(*this); 748 Remap.addPrivate(DestVD, [DestElement]() { return DestElement; }); 749 Remap.addPrivate(SrcVD, [SrcElement]() { return SrcElement; }); 750 (void)Remap.Privatize(); 751 EmitIgnoredExpr(Copy); 752 }); 753 } 754 } else { 755 // Remap pseudo source variable to private copy. 756 CodeGenFunction::OMPPrivateScope Remap(*this); 757 Remap.addPrivate(SrcVD, [SrcAddr]() { return SrcAddr; }); 758 Remap.addPrivate(DestVD, [DestAddr]() { return DestAddr; }); 759 (void)Remap.Privatize(); 760 // Emit copying of the whole variable. 761 EmitIgnoredExpr(Copy); 762 } 763 } 764 765 bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D, 766 OMPPrivateScope &PrivateScope) { 767 if (!HaveInsertPoint()) 768 return false; 769 bool DeviceConstTarget = 770 getLangOpts().OpenMPIsDevice && 771 isOpenMPTargetExecutionDirective(D.getDirectiveKind()); 772 bool FirstprivateIsLastprivate = false; 773 llvm::DenseMap<const VarDecl *, OpenMPLastprivateModifier> Lastprivates; 774 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) { 775 for (const auto *D : C->varlists()) 776 Lastprivates.try_emplace( 777 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl(), 778 C->getKind()); 779 } 780 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate; 781 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 782 getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind()); 783 // Force emission of the firstprivate copy if the directive does not emit 784 // outlined function, like omp for, omp simd, omp distribute etc. 785 bool MustEmitFirstprivateCopy = 786 CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown; 787 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) { 788 const auto *IRef = C->varlist_begin(); 789 const auto *InitsRef = C->inits().begin(); 790 for (const Expr *IInit : C->private_copies()) { 791 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 792 bool ThisFirstprivateIsLastprivate = 793 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0; 794 const FieldDecl *FD = CapturedStmtInfo->lookup(OrigVD); 795 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl()); 796 if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD && 797 !FD->getType()->isReferenceType() && 798 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) { 799 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()); 800 ++IRef; 801 ++InitsRef; 802 continue; 803 } 804 // Do not emit copy for firstprivate constant variables in target regions, 805 // captured by reference. 806 if (DeviceConstTarget && OrigVD->getType().isConstant(getContext()) && 807 FD && FD->getType()->isReferenceType() && 808 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) { 809 (void)CGM.getOpenMPRuntime().registerTargetFirstprivateCopy(*this, 810 OrigVD); 811 ++IRef; 812 ++InitsRef; 813 continue; 814 } 815 FirstprivateIsLastprivate = 816 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate; 817 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) { 818 const auto *VDInit = 819 cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl()); 820 bool IsRegistered; 821 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), 822 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr, 823 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc()); 824 LValue OriginalLVal; 825 if (!FD) { 826 // Check if the firstprivate variable is just a constant value. 827 ConstantEmission CE = tryEmitAsConstant(&DRE); 828 if (CE && !CE.isReference()) { 829 // Constant value, no need to create a copy. 830 ++IRef; 831 ++InitsRef; 832 continue; 833 } 834 if (CE && CE.isReference()) { 835 OriginalLVal = CE.getReferenceLValue(*this, &DRE); 836 } else { 837 assert(!CE && "Expected non-constant firstprivate."); 838 OriginalLVal = EmitLValue(&DRE); 839 } 840 } else { 841 OriginalLVal = EmitLValue(&DRE); 842 } 843 QualType Type = VD->getType(); 844 if (Type->isArrayType()) { 845 // Emit VarDecl with copy init for arrays. 846 // Get the address of the original variable captured in current 847 // captured region. 848 IsRegistered = PrivateScope.addPrivate( 849 OrigVD, [this, VD, Type, OriginalLVal, VDInit]() { 850 AutoVarEmission Emission = EmitAutoVarAlloca(*VD); 851 const Expr *Init = VD->getInit(); 852 if (!isa<CXXConstructExpr>(Init) || 853 isTrivialInitializer(Init)) { 854 // Perform simple memcpy. 855 LValue Dest = 856 MakeAddrLValue(Emission.getAllocatedAddress(), Type); 857 EmitAggregateAssign(Dest, OriginalLVal, Type); 858 } else { 859 EmitOMPAggregateAssign( 860 Emission.getAllocatedAddress(), 861 OriginalLVal.getAddress(*this), Type, 862 [this, VDInit, Init](Address DestElement, 863 Address SrcElement) { 864 // Clean up any temporaries needed by the 865 // initialization. 866 RunCleanupsScope InitScope(*this); 867 // Emit initialization for single element. 868 setAddrOfLocalVar(VDInit, SrcElement); 869 EmitAnyExprToMem(Init, DestElement, 870 Init->getType().getQualifiers(), 871 /*IsInitializer*/ false); 872 LocalDeclMap.erase(VDInit); 873 }); 874 } 875 EmitAutoVarCleanups(Emission); 876 return Emission.getAllocatedAddress(); 877 }); 878 } else { 879 Address OriginalAddr = OriginalLVal.getAddress(*this); 880 IsRegistered = 881 PrivateScope.addPrivate(OrigVD, [this, VDInit, OriginalAddr, VD, 882 ThisFirstprivateIsLastprivate, 883 OrigVD, &Lastprivates, IRef]() { 884 // Emit private VarDecl with copy init. 885 // Remap temp VDInit variable to the address of the original 886 // variable (for proper handling of captured global variables). 887 setAddrOfLocalVar(VDInit, OriginalAddr); 888 EmitDecl(*VD); 889 LocalDeclMap.erase(VDInit); 890 if (ThisFirstprivateIsLastprivate && 891 Lastprivates[OrigVD->getCanonicalDecl()] == 892 OMPC_LASTPRIVATE_conditional) { 893 // Create/init special variable for lastprivate conditionals. 894 Address VDAddr = 895 CGM.getOpenMPRuntime().emitLastprivateConditionalInit( 896 *this, OrigVD); 897 llvm::Value *V = EmitLoadOfScalar( 898 MakeAddrLValue(GetAddrOfLocalVar(VD), (*IRef)->getType(), 899 AlignmentSource::Decl), 900 (*IRef)->getExprLoc()); 901 EmitStoreOfScalar(V, 902 MakeAddrLValue(VDAddr, (*IRef)->getType(), 903 AlignmentSource::Decl)); 904 LocalDeclMap.erase(VD); 905 setAddrOfLocalVar(VD, VDAddr); 906 return VDAddr; 907 } 908 return GetAddrOfLocalVar(VD); 909 }); 910 } 911 assert(IsRegistered && 912 "firstprivate var already registered as private"); 913 // Silence the warning about unused variable. 914 (void)IsRegistered; 915 } 916 ++IRef; 917 ++InitsRef; 918 } 919 } 920 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty(); 921 } 922 923 void CodeGenFunction::EmitOMPPrivateClause( 924 const OMPExecutableDirective &D, 925 CodeGenFunction::OMPPrivateScope &PrivateScope) { 926 if (!HaveInsertPoint()) 927 return; 928 llvm::DenseSet<const VarDecl *> EmittedAsPrivate; 929 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) { 930 auto IRef = C->varlist_begin(); 931 for (const Expr *IInit : C->private_copies()) { 932 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 933 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 934 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl()); 935 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() { 936 // Emit private VarDecl with copy init. 937 EmitDecl(*VD); 938 return GetAddrOfLocalVar(VD); 939 }); 940 assert(IsRegistered && "private var already registered as private"); 941 // Silence the warning about unused variable. 942 (void)IsRegistered; 943 } 944 ++IRef; 945 } 946 } 947 } 948 949 bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) { 950 if (!HaveInsertPoint()) 951 return false; 952 // threadprivate_var1 = master_threadprivate_var1; 953 // operator=(threadprivate_var2, master_threadprivate_var2); 954 // ... 955 // __kmpc_barrier(&loc, global_tid); 956 llvm::DenseSet<const VarDecl *> CopiedVars; 957 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr; 958 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) { 959 auto IRef = C->varlist_begin(); 960 auto ISrcRef = C->source_exprs().begin(); 961 auto IDestRef = C->destination_exprs().begin(); 962 for (const Expr *AssignOp : C->assignment_ops()) { 963 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 964 QualType Type = VD->getType(); 965 if (CopiedVars.insert(VD->getCanonicalDecl()).second) { 966 // Get the address of the master variable. If we are emitting code with 967 // TLS support, the address is passed from the master as field in the 968 // captured declaration. 969 Address MasterAddr = Address::invalid(); 970 if (getLangOpts().OpenMPUseTLS && 971 getContext().getTargetInfo().isTLSSupported()) { 972 assert(CapturedStmtInfo->lookup(VD) && 973 "Copyin threadprivates should have been captured!"); 974 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), true, 975 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc()); 976 MasterAddr = EmitLValue(&DRE).getAddress(*this); 977 LocalDeclMap.erase(VD); 978 } else { 979 MasterAddr = 980 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD) 981 : CGM.GetAddrOfGlobal(VD), 982 getContext().getDeclAlign(VD)); 983 } 984 // Get the address of the threadprivate variable. 985 Address PrivateAddr = EmitLValue(*IRef).getAddress(*this); 986 if (CopiedVars.size() == 1) { 987 // At first check if current thread is a master thread. If it is, no 988 // need to copy data. 989 CopyBegin = createBasicBlock("copyin.not.master"); 990 CopyEnd = createBasicBlock("copyin.not.master.end"); 991 Builder.CreateCondBr( 992 Builder.CreateICmpNE( 993 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy), 994 Builder.CreatePtrToInt(PrivateAddr.getPointer(), 995 CGM.IntPtrTy)), 996 CopyBegin, CopyEnd); 997 EmitBlock(CopyBegin); 998 } 999 const auto *SrcVD = 1000 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl()); 1001 const auto *DestVD = 1002 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl()); 1003 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp); 1004 } 1005 ++IRef; 1006 ++ISrcRef; 1007 ++IDestRef; 1008 } 1009 } 1010 if (CopyEnd) { 1011 // Exit out of copying procedure for non-master thread. 1012 EmitBlock(CopyEnd, /*IsFinished=*/true); 1013 return true; 1014 } 1015 return false; 1016 } 1017 1018 bool CodeGenFunction::EmitOMPLastprivateClauseInit( 1019 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) { 1020 if (!HaveInsertPoint()) 1021 return false; 1022 bool HasAtLeastOneLastprivate = false; 1023 llvm::DenseSet<const VarDecl *> SIMDLCVs; 1024 if (isOpenMPSimdDirective(D.getDirectiveKind())) { 1025 const auto *LoopDirective = cast<OMPLoopDirective>(&D); 1026 for (const Expr *C : LoopDirective->counters()) { 1027 SIMDLCVs.insert( 1028 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl()); 1029 } 1030 } 1031 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars; 1032 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) { 1033 HasAtLeastOneLastprivate = true; 1034 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) && 1035 !getLangOpts().OpenMPSimd) 1036 break; 1037 const auto *IRef = C->varlist_begin(); 1038 const auto *IDestRef = C->destination_exprs().begin(); 1039 for (const Expr *IInit : C->private_copies()) { 1040 // Keep the address of the original variable for future update at the end 1041 // of the loop. 1042 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 1043 // Taskloops do not require additional initialization, it is done in 1044 // runtime support library. 1045 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) { 1046 const auto *DestVD = 1047 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl()); 1048 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() { 1049 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), 1050 /*RefersToEnclosingVariableOrCapture=*/ 1051 CapturedStmtInfo->lookup(OrigVD) != nullptr, 1052 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc()); 1053 return EmitLValue(&DRE).getAddress(*this); 1054 }); 1055 // Check if the variable is also a firstprivate: in this case IInit is 1056 // not generated. Initialization of this variable will happen in codegen 1057 // for 'firstprivate' clause. 1058 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) { 1059 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl()); 1060 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD, C, 1061 OrigVD]() { 1062 if (C->getKind() == OMPC_LASTPRIVATE_conditional) { 1063 Address VDAddr = 1064 CGM.getOpenMPRuntime().emitLastprivateConditionalInit(*this, 1065 OrigVD); 1066 setAddrOfLocalVar(VD, VDAddr); 1067 return VDAddr; 1068 } 1069 // Emit private VarDecl with copy init. 1070 EmitDecl(*VD); 1071 return GetAddrOfLocalVar(VD); 1072 }); 1073 assert(IsRegistered && 1074 "lastprivate var already registered as private"); 1075 (void)IsRegistered; 1076 } 1077 } 1078 ++IRef; 1079 ++IDestRef; 1080 } 1081 } 1082 return HasAtLeastOneLastprivate; 1083 } 1084 1085 void CodeGenFunction::EmitOMPLastprivateClauseFinal( 1086 const OMPExecutableDirective &D, bool NoFinals, 1087 llvm::Value *IsLastIterCond) { 1088 if (!HaveInsertPoint()) 1089 return; 1090 // Emit following code: 1091 // if (<IsLastIterCond>) { 1092 // orig_var1 = private_orig_var1; 1093 // ... 1094 // orig_varn = private_orig_varn; 1095 // } 1096 llvm::BasicBlock *ThenBB = nullptr; 1097 llvm::BasicBlock *DoneBB = nullptr; 1098 if (IsLastIterCond) { 1099 // Emit implicit barrier if at least one lastprivate conditional is found 1100 // and this is not a simd mode. 1101 if (!getLangOpts().OpenMPSimd && 1102 llvm::any_of(D.getClausesOfKind<OMPLastprivateClause>(), 1103 [](const OMPLastprivateClause *C) { 1104 return C->getKind() == OMPC_LASTPRIVATE_conditional; 1105 })) { 1106 CGM.getOpenMPRuntime().emitBarrierCall(*this, D.getBeginLoc(), 1107 OMPD_unknown, 1108 /*EmitChecks=*/false, 1109 /*ForceSimpleCall=*/true); 1110 } 1111 ThenBB = createBasicBlock(".omp.lastprivate.then"); 1112 DoneBB = createBasicBlock(".omp.lastprivate.done"); 1113 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB); 1114 EmitBlock(ThenBB); 1115 } 1116 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars; 1117 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates; 1118 if (const auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) { 1119 auto IC = LoopDirective->counters().begin(); 1120 for (const Expr *F : LoopDirective->finals()) { 1121 const auto *D = 1122 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl(); 1123 if (NoFinals) 1124 AlreadyEmittedVars.insert(D); 1125 else 1126 LoopCountersAndUpdates[D] = F; 1127 ++IC; 1128 } 1129 } 1130 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) { 1131 auto IRef = C->varlist_begin(); 1132 auto ISrcRef = C->source_exprs().begin(); 1133 auto IDestRef = C->destination_exprs().begin(); 1134 for (const Expr *AssignOp : C->assignment_ops()) { 1135 const auto *PrivateVD = 1136 cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 1137 QualType Type = PrivateVD->getType(); 1138 const auto *CanonicalVD = PrivateVD->getCanonicalDecl(); 1139 if (AlreadyEmittedVars.insert(CanonicalVD).second) { 1140 // If lastprivate variable is a loop control variable for loop-based 1141 // directive, update its value before copyin back to original 1142 // variable. 1143 if (const Expr *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD)) 1144 EmitIgnoredExpr(FinalExpr); 1145 const auto *SrcVD = 1146 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl()); 1147 const auto *DestVD = 1148 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl()); 1149 // Get the address of the private variable. 1150 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD); 1151 if (const auto *RefTy = PrivateVD->getType()->getAs<ReferenceType>()) 1152 PrivateAddr = 1153 Address(Builder.CreateLoad(PrivateAddr), 1154 CGM.getNaturalTypeAlignment(RefTy->getPointeeType())); 1155 // Store the last value to the private copy in the last iteration. 1156 if (C->getKind() == OMPC_LASTPRIVATE_conditional) 1157 CGM.getOpenMPRuntime().emitLastprivateConditionalFinalUpdate( 1158 *this, MakeAddrLValue(PrivateAddr, (*IRef)->getType()), PrivateVD, 1159 (*IRef)->getExprLoc()); 1160 // Get the address of the original variable. 1161 Address OriginalAddr = GetAddrOfLocalVar(DestVD); 1162 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp); 1163 } 1164 ++IRef; 1165 ++ISrcRef; 1166 ++IDestRef; 1167 } 1168 if (const Expr *PostUpdate = C->getPostUpdateExpr()) 1169 EmitIgnoredExpr(PostUpdate); 1170 } 1171 if (IsLastIterCond) 1172 EmitBlock(DoneBB, /*IsFinished=*/true); 1173 } 1174 1175 void CodeGenFunction::EmitOMPReductionClauseInit( 1176 const OMPExecutableDirective &D, 1177 CodeGenFunction::OMPPrivateScope &PrivateScope, bool ForInscan) { 1178 if (!HaveInsertPoint()) 1179 return; 1180 SmallVector<const Expr *, 4> Shareds; 1181 SmallVector<const Expr *, 4> Privates; 1182 SmallVector<const Expr *, 4> ReductionOps; 1183 SmallVector<const Expr *, 4> LHSs; 1184 SmallVector<const Expr *, 4> RHSs; 1185 OMPTaskDataTy Data; 1186 SmallVector<const Expr *, 4> TaskLHSs; 1187 SmallVector<const Expr *, 4> TaskRHSs; 1188 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) { 1189 if (ForInscan != (C->getModifier() == OMPC_REDUCTION_inscan)) 1190 continue; 1191 Shareds.append(C->varlist_begin(), C->varlist_end()); 1192 Privates.append(C->privates().begin(), C->privates().end()); 1193 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end()); 1194 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 1195 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 1196 if (C->getModifier() == OMPC_REDUCTION_task) { 1197 Data.ReductionVars.append(C->privates().begin(), C->privates().end()); 1198 Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end()); 1199 Data.ReductionCopies.append(C->privates().begin(), C->privates().end()); 1200 Data.ReductionOps.append(C->reduction_ops().begin(), 1201 C->reduction_ops().end()); 1202 TaskLHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 1203 TaskRHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 1204 } 1205 } 1206 ReductionCodeGen RedCG(Shareds, Shareds, Privates, ReductionOps); 1207 unsigned Count = 0; 1208 auto *ILHS = LHSs.begin(); 1209 auto *IRHS = RHSs.begin(); 1210 auto *IPriv = Privates.begin(); 1211 for (const Expr *IRef : Shareds) { 1212 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl()); 1213 // Emit private VarDecl with reduction init. 1214 RedCG.emitSharedOrigLValue(*this, Count); 1215 RedCG.emitAggregateType(*this, Count); 1216 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD); 1217 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(), 1218 RedCG.getSharedLValue(Count), 1219 [&Emission](CodeGenFunction &CGF) { 1220 CGF.EmitAutoVarInit(Emission); 1221 return true; 1222 }); 1223 EmitAutoVarCleanups(Emission); 1224 Address BaseAddr = RedCG.adjustPrivateAddress( 1225 *this, Count, Emission.getAllocatedAddress()); 1226 bool IsRegistered = PrivateScope.addPrivate( 1227 RedCG.getBaseDecl(Count), [BaseAddr]() { return BaseAddr; }); 1228 assert(IsRegistered && "private var already registered as private"); 1229 // Silence the warning about unused variable. 1230 (void)IsRegistered; 1231 1232 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl()); 1233 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl()); 1234 QualType Type = PrivateVD->getType(); 1235 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef); 1236 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) { 1237 // Store the address of the original variable associated with the LHS 1238 // implicit variable. 1239 PrivateScope.addPrivate(LHSVD, [&RedCG, Count, this]() { 1240 return RedCG.getSharedLValue(Count).getAddress(*this); 1241 }); 1242 PrivateScope.addPrivate( 1243 RHSVD, [this, PrivateVD]() { return GetAddrOfLocalVar(PrivateVD); }); 1244 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) || 1245 isa<ArraySubscriptExpr>(IRef)) { 1246 // Store the address of the original variable associated with the LHS 1247 // implicit variable. 1248 PrivateScope.addPrivate(LHSVD, [&RedCG, Count, this]() { 1249 return RedCG.getSharedLValue(Count).getAddress(*this); 1250 }); 1251 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() { 1252 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD), 1253 ConvertTypeForMem(RHSVD->getType()), 1254 "rhs.begin"); 1255 }); 1256 } else { 1257 QualType Type = PrivateVD->getType(); 1258 bool IsArray = getContext().getAsArrayType(Type) != nullptr; 1259 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress(*this); 1260 // Store the address of the original variable associated with the LHS 1261 // implicit variable. 1262 if (IsArray) { 1263 OriginalAddr = Builder.CreateElementBitCast( 1264 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin"); 1265 } 1266 PrivateScope.addPrivate(LHSVD, [OriginalAddr]() { return OriginalAddr; }); 1267 PrivateScope.addPrivate( 1268 RHSVD, [this, PrivateVD, RHSVD, IsArray]() { 1269 return IsArray 1270 ? Builder.CreateElementBitCast( 1271 GetAddrOfLocalVar(PrivateVD), 1272 ConvertTypeForMem(RHSVD->getType()), "rhs.begin") 1273 : GetAddrOfLocalVar(PrivateVD); 1274 }); 1275 } 1276 ++ILHS; 1277 ++IRHS; 1278 ++IPriv; 1279 ++Count; 1280 } 1281 if (!Data.ReductionVars.empty()) { 1282 Data.IsReductionWithTaskMod = true; 1283 Data.IsWorksharingReduction = 1284 isOpenMPWorksharingDirective(D.getDirectiveKind()); 1285 llvm::Value *ReductionDesc = CGM.getOpenMPRuntime().emitTaskReductionInit( 1286 *this, D.getBeginLoc(), TaskLHSs, TaskRHSs, Data); 1287 const Expr *TaskRedRef = nullptr; 1288 switch (D.getDirectiveKind()) { 1289 case OMPD_parallel: 1290 TaskRedRef = cast<OMPParallelDirective>(D).getTaskReductionRefExpr(); 1291 break; 1292 case OMPD_for: 1293 TaskRedRef = cast<OMPForDirective>(D).getTaskReductionRefExpr(); 1294 break; 1295 case OMPD_sections: 1296 TaskRedRef = cast<OMPSectionsDirective>(D).getTaskReductionRefExpr(); 1297 break; 1298 case OMPD_parallel_for: 1299 TaskRedRef = cast<OMPParallelForDirective>(D).getTaskReductionRefExpr(); 1300 break; 1301 case OMPD_parallel_master: 1302 TaskRedRef = 1303 cast<OMPParallelMasterDirective>(D).getTaskReductionRefExpr(); 1304 break; 1305 case OMPD_parallel_sections: 1306 TaskRedRef = 1307 cast<OMPParallelSectionsDirective>(D).getTaskReductionRefExpr(); 1308 break; 1309 case OMPD_target_parallel: 1310 TaskRedRef = 1311 cast<OMPTargetParallelDirective>(D).getTaskReductionRefExpr(); 1312 break; 1313 case OMPD_target_parallel_for: 1314 TaskRedRef = 1315 cast<OMPTargetParallelForDirective>(D).getTaskReductionRefExpr(); 1316 break; 1317 case OMPD_distribute_parallel_for: 1318 TaskRedRef = 1319 cast<OMPDistributeParallelForDirective>(D).getTaskReductionRefExpr(); 1320 break; 1321 case OMPD_teams_distribute_parallel_for: 1322 TaskRedRef = cast<OMPTeamsDistributeParallelForDirective>(D) 1323 .getTaskReductionRefExpr(); 1324 break; 1325 case OMPD_target_teams_distribute_parallel_for: 1326 TaskRedRef = cast<OMPTargetTeamsDistributeParallelForDirective>(D) 1327 .getTaskReductionRefExpr(); 1328 break; 1329 case OMPD_simd: 1330 case OMPD_for_simd: 1331 case OMPD_section: 1332 case OMPD_single: 1333 case OMPD_master: 1334 case OMPD_critical: 1335 case OMPD_parallel_for_simd: 1336 case OMPD_task: 1337 case OMPD_taskyield: 1338 case OMPD_barrier: 1339 case OMPD_taskwait: 1340 case OMPD_taskgroup: 1341 case OMPD_flush: 1342 case OMPD_depobj: 1343 case OMPD_scan: 1344 case OMPD_ordered: 1345 case OMPD_atomic: 1346 case OMPD_teams: 1347 case OMPD_target: 1348 case OMPD_cancellation_point: 1349 case OMPD_cancel: 1350 case OMPD_target_data: 1351 case OMPD_target_enter_data: 1352 case OMPD_target_exit_data: 1353 case OMPD_taskloop: 1354 case OMPD_taskloop_simd: 1355 case OMPD_master_taskloop: 1356 case OMPD_master_taskloop_simd: 1357 case OMPD_parallel_master_taskloop: 1358 case OMPD_parallel_master_taskloop_simd: 1359 case OMPD_distribute: 1360 case OMPD_target_update: 1361 case OMPD_distribute_parallel_for_simd: 1362 case OMPD_distribute_simd: 1363 case OMPD_target_parallel_for_simd: 1364 case OMPD_target_simd: 1365 case OMPD_teams_distribute: 1366 case OMPD_teams_distribute_simd: 1367 case OMPD_teams_distribute_parallel_for_simd: 1368 case OMPD_target_teams: 1369 case OMPD_target_teams_distribute: 1370 case OMPD_target_teams_distribute_parallel_for_simd: 1371 case OMPD_target_teams_distribute_simd: 1372 case OMPD_declare_target: 1373 case OMPD_end_declare_target: 1374 case OMPD_threadprivate: 1375 case OMPD_allocate: 1376 case OMPD_declare_reduction: 1377 case OMPD_declare_mapper: 1378 case OMPD_declare_simd: 1379 case OMPD_requires: 1380 case OMPD_declare_variant: 1381 case OMPD_begin_declare_variant: 1382 case OMPD_end_declare_variant: 1383 case OMPD_unknown: 1384 default: 1385 llvm_unreachable("Enexpected directive with task reductions."); 1386 } 1387 1388 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(TaskRedRef)->getDecl()); 1389 EmitVarDecl(*VD); 1390 EmitStoreOfScalar(ReductionDesc, GetAddrOfLocalVar(VD), 1391 /*Volatile=*/false, TaskRedRef->getType()); 1392 } 1393 } 1394 1395 void CodeGenFunction::EmitOMPReductionClauseFinal( 1396 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) { 1397 if (!HaveInsertPoint()) 1398 return; 1399 llvm::SmallVector<const Expr *, 8> Privates; 1400 llvm::SmallVector<const Expr *, 8> LHSExprs; 1401 llvm::SmallVector<const Expr *, 8> RHSExprs; 1402 llvm::SmallVector<const Expr *, 8> ReductionOps; 1403 bool HasAtLeastOneReduction = false; 1404 bool IsReductionWithTaskMod = false; 1405 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) { 1406 // Do not emit for inscan reductions. 1407 if (C->getModifier() == OMPC_REDUCTION_inscan) 1408 continue; 1409 HasAtLeastOneReduction = true; 1410 Privates.append(C->privates().begin(), C->privates().end()); 1411 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 1412 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 1413 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end()); 1414 IsReductionWithTaskMod = 1415 IsReductionWithTaskMod || C->getModifier() == OMPC_REDUCTION_task; 1416 } 1417 if (HasAtLeastOneReduction) { 1418 if (IsReductionWithTaskMod) { 1419 CGM.getOpenMPRuntime().emitTaskReductionFini( 1420 *this, D.getBeginLoc(), 1421 isOpenMPWorksharingDirective(D.getDirectiveKind())); 1422 } 1423 bool WithNowait = D.getSingleClause<OMPNowaitClause>() || 1424 isOpenMPParallelDirective(D.getDirectiveKind()) || 1425 ReductionKind == OMPD_simd; 1426 bool SimpleReduction = ReductionKind == OMPD_simd; 1427 // Emit nowait reduction if nowait clause is present or directive is a 1428 // parallel directive (it always has implicit barrier). 1429 CGM.getOpenMPRuntime().emitReduction( 1430 *this, D.getEndLoc(), Privates, LHSExprs, RHSExprs, ReductionOps, 1431 {WithNowait, SimpleReduction, ReductionKind}); 1432 } 1433 } 1434 1435 static void emitPostUpdateForReductionClause( 1436 CodeGenFunction &CGF, const OMPExecutableDirective &D, 1437 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) { 1438 if (!CGF.HaveInsertPoint()) 1439 return; 1440 llvm::BasicBlock *DoneBB = nullptr; 1441 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) { 1442 if (const Expr *PostUpdate = C->getPostUpdateExpr()) { 1443 if (!DoneBB) { 1444 if (llvm::Value *Cond = CondGen(CGF)) { 1445 // If the first post-update expression is found, emit conditional 1446 // block if it was requested. 1447 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.pu"); 1448 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done"); 1449 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB); 1450 CGF.EmitBlock(ThenBB); 1451 } 1452 } 1453 CGF.EmitIgnoredExpr(PostUpdate); 1454 } 1455 } 1456 if (DoneBB) 1457 CGF.EmitBlock(DoneBB, /*IsFinished=*/true); 1458 } 1459 1460 namespace { 1461 /// Codegen lambda for appending distribute lower and upper bounds to outlined 1462 /// parallel function. This is necessary for combined constructs such as 1463 /// 'distribute parallel for' 1464 typedef llvm::function_ref<void(CodeGenFunction &, 1465 const OMPExecutableDirective &, 1466 llvm::SmallVectorImpl<llvm::Value *> &)> 1467 CodeGenBoundParametersTy; 1468 } // anonymous namespace 1469 1470 static void 1471 checkForLastprivateConditionalUpdate(CodeGenFunction &CGF, 1472 const OMPExecutableDirective &S) { 1473 if (CGF.getLangOpts().OpenMP < 50) 1474 return; 1475 llvm::DenseSet<CanonicalDeclPtr<const VarDecl>> PrivateDecls; 1476 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) { 1477 for (const Expr *Ref : C->varlists()) { 1478 if (!Ref->getType()->isScalarType()) 1479 continue; 1480 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts()); 1481 if (!DRE) 1482 continue; 1483 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl())); 1484 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref); 1485 } 1486 } 1487 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) { 1488 for (const Expr *Ref : C->varlists()) { 1489 if (!Ref->getType()->isScalarType()) 1490 continue; 1491 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts()); 1492 if (!DRE) 1493 continue; 1494 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl())); 1495 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref); 1496 } 1497 } 1498 for (const auto *C : S.getClausesOfKind<OMPLinearClause>()) { 1499 for (const Expr *Ref : C->varlists()) { 1500 if (!Ref->getType()->isScalarType()) 1501 continue; 1502 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts()); 1503 if (!DRE) 1504 continue; 1505 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl())); 1506 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref); 1507 } 1508 } 1509 // Privates should ne analyzed since they are not captured at all. 1510 // Task reductions may be skipped - tasks are ignored. 1511 // Firstprivates do not return value but may be passed by reference - no need 1512 // to check for updated lastprivate conditional. 1513 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) { 1514 for (const Expr *Ref : C->varlists()) { 1515 if (!Ref->getType()->isScalarType()) 1516 continue; 1517 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts()); 1518 if (!DRE) 1519 continue; 1520 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl())); 1521 } 1522 } 1523 CGF.CGM.getOpenMPRuntime().checkAndEmitSharedLastprivateConditional( 1524 CGF, S, PrivateDecls); 1525 } 1526 1527 static void emitCommonOMPParallelDirective( 1528 CodeGenFunction &CGF, const OMPExecutableDirective &S, 1529 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, 1530 const CodeGenBoundParametersTy &CodeGenBoundParameters) { 1531 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel); 1532 llvm::Function *OutlinedFn = 1533 CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction( 1534 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen); 1535 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) { 1536 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF); 1537 llvm::Value *NumThreads = 1538 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(), 1539 /*IgnoreResultAssign=*/true); 1540 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause( 1541 CGF, NumThreads, NumThreadsClause->getBeginLoc()); 1542 } 1543 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) { 1544 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF); 1545 CGF.CGM.getOpenMPRuntime().emitProcBindClause( 1546 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getBeginLoc()); 1547 } 1548 const Expr *IfCond = nullptr; 1549 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 1550 if (C->getNameModifier() == OMPD_unknown || 1551 C->getNameModifier() == OMPD_parallel) { 1552 IfCond = C->getCondition(); 1553 break; 1554 } 1555 } 1556 1557 OMPParallelScope Scope(CGF, S); 1558 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 1559 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk 1560 // lower and upper bounds with the pragma 'for' chunking mechanism. 1561 // The following lambda takes care of appending the lower and upper bound 1562 // parameters when necessary 1563 CodeGenBoundParameters(CGF, S, CapturedVars); 1564 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars); 1565 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getBeginLoc(), OutlinedFn, 1566 CapturedVars, IfCond); 1567 } 1568 1569 static bool isAllocatableDecl(const VarDecl *VD) { 1570 const VarDecl *CVD = VD->getCanonicalDecl(); 1571 if (!CVD->hasAttr<OMPAllocateDeclAttr>()) 1572 return false; 1573 const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>(); 1574 // Use the default allocation. 1575 return !((AA->getAllocatorType() == OMPAllocateDeclAttr::OMPDefaultMemAlloc || 1576 AA->getAllocatorType() == OMPAllocateDeclAttr::OMPNullMemAlloc) && 1577 !AA->getAllocator()); 1578 } 1579 1580 static void emitEmptyBoundParameters(CodeGenFunction &, 1581 const OMPExecutableDirective &, 1582 llvm::SmallVectorImpl<llvm::Value *> &) {} 1583 1584 Address CodeGenFunction::OMPBuilderCBHelpers::getAddressOfLocalVariable( 1585 CodeGenFunction &CGF, const VarDecl *VD) { 1586 CodeGenModule &CGM = CGF.CGM; 1587 auto &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 1588 1589 if (!VD) 1590 return Address::invalid(); 1591 const VarDecl *CVD = VD->getCanonicalDecl(); 1592 if (!isAllocatableDecl(CVD)) 1593 return Address::invalid(); 1594 llvm::Value *Size; 1595 CharUnits Align = CGM.getContext().getDeclAlign(CVD); 1596 if (CVD->getType()->isVariablyModifiedType()) { 1597 Size = CGF.getTypeSize(CVD->getType()); 1598 // Align the size: ((size + align - 1) / align) * align 1599 Size = CGF.Builder.CreateNUWAdd( 1600 Size, CGM.getSize(Align - CharUnits::fromQuantity(1))); 1601 Size = CGF.Builder.CreateUDiv(Size, CGM.getSize(Align)); 1602 Size = CGF.Builder.CreateNUWMul(Size, CGM.getSize(Align)); 1603 } else { 1604 CharUnits Sz = CGM.getContext().getTypeSizeInChars(CVD->getType()); 1605 Size = CGM.getSize(Sz.alignTo(Align)); 1606 } 1607 1608 const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>(); 1609 assert(AA->getAllocator() && 1610 "Expected allocator expression for non-default allocator."); 1611 llvm::Value *Allocator = CGF.EmitScalarExpr(AA->getAllocator()); 1612 // According to the standard, the original allocator type is a enum (integer). 1613 // Convert to pointer type, if required. 1614 if (Allocator->getType()->isIntegerTy()) 1615 Allocator = CGF.Builder.CreateIntToPtr(Allocator, CGM.VoidPtrTy); 1616 else if (Allocator->getType()->isPointerTy()) 1617 Allocator = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Allocator, 1618 CGM.VoidPtrTy); 1619 1620 llvm::Value *Addr = OMPBuilder.createOMPAlloc( 1621 CGF.Builder, Size, Allocator, 1622 getNameWithSeparators({CVD->getName(), ".void.addr"}, ".", ".")); 1623 llvm::CallInst *FreeCI = 1624 OMPBuilder.createOMPFree(CGF.Builder, Addr, Allocator); 1625 1626 CGF.EHStack.pushCleanup<OMPAllocateCleanupTy>(NormalAndEHCleanup, FreeCI); 1627 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 1628 Addr, 1629 CGF.ConvertTypeForMem(CGM.getContext().getPointerType(CVD->getType())), 1630 getNameWithSeparators({CVD->getName(), ".addr"}, ".", ".")); 1631 return Address(Addr, Align); 1632 } 1633 1634 Address CodeGenFunction::OMPBuilderCBHelpers::getAddrOfThreadPrivate( 1635 CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr, 1636 SourceLocation Loc) { 1637 CodeGenModule &CGM = CGF.CGM; 1638 if (CGM.getLangOpts().OpenMPUseTLS && 1639 CGM.getContext().getTargetInfo().isTLSSupported()) 1640 return VDAddr; 1641 1642 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 1643 1644 llvm::Type *VarTy = VDAddr.getElementType(); 1645 llvm::Value *Data = 1646 CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.Int8PtrTy); 1647 llvm::ConstantInt *Size = CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)); 1648 std::string Suffix = getNameWithSeparators({"cache", ""}); 1649 llvm::Twine CacheName = Twine(CGM.getMangledName(VD)).concat(Suffix); 1650 1651 llvm::CallInst *ThreadPrivateCacheCall = 1652 OMPBuilder.createCachedThreadPrivate(CGF.Builder, Data, Size, CacheName); 1653 1654 return Address(ThreadPrivateCacheCall, VDAddr.getAlignment()); 1655 } 1656 1657 std::string CodeGenFunction::OMPBuilderCBHelpers::getNameWithSeparators( 1658 ArrayRef<StringRef> Parts, StringRef FirstSeparator, StringRef Separator) { 1659 SmallString<128> Buffer; 1660 llvm::raw_svector_ostream OS(Buffer); 1661 StringRef Sep = FirstSeparator; 1662 for (StringRef Part : Parts) { 1663 OS << Sep << Part; 1664 Sep = Separator; 1665 } 1666 return OS.str().str(); 1667 } 1668 void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) { 1669 if (CGM.getLangOpts().OpenMPIRBuilder) { 1670 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 1671 // Check if we have any if clause associated with the directive. 1672 llvm::Value *IfCond = nullptr; 1673 if (const auto *C = S.getSingleClause<OMPIfClause>()) 1674 IfCond = EmitScalarExpr(C->getCondition(), 1675 /*IgnoreResultAssign=*/true); 1676 1677 llvm::Value *NumThreads = nullptr; 1678 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) 1679 NumThreads = EmitScalarExpr(NumThreadsClause->getNumThreads(), 1680 /*IgnoreResultAssign=*/true); 1681 1682 ProcBindKind ProcBind = OMP_PROC_BIND_default; 1683 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) 1684 ProcBind = ProcBindClause->getProcBindKind(); 1685 1686 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 1687 1688 // The cleanup callback that finalizes all variabels at the given location, 1689 // thus calls destructors etc. 1690 auto FiniCB = [this](InsertPointTy IP) { 1691 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP); 1692 }; 1693 1694 // Privatization callback that performs appropriate action for 1695 // shared/private/firstprivate/lastprivate/copyin/... variables. 1696 // 1697 // TODO: This defaults to shared right now. 1698 auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP, 1699 llvm::Value &, llvm::Value &Val, llvm::Value *&ReplVal) { 1700 // The next line is appropriate only for variables (Val) with the 1701 // data-sharing attribute "shared". 1702 ReplVal = &Val; 1703 1704 return CodeGenIP; 1705 }; 1706 1707 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel); 1708 const Stmt *ParallelRegionBodyStmt = CS->getCapturedStmt(); 1709 1710 auto BodyGenCB = [ParallelRegionBodyStmt, 1711 this](InsertPointTy AllocaIP, InsertPointTy CodeGenIP, 1712 llvm::BasicBlock &ContinuationBB) { 1713 OMPBuilderCBHelpers::OutlinedRegionBodyRAII ORB(*this, AllocaIP, 1714 ContinuationBB); 1715 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, ParallelRegionBodyStmt, 1716 CodeGenIP, ContinuationBB); 1717 }; 1718 1719 CGCapturedStmtInfo CGSI(*CS, CR_OpenMP); 1720 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI); 1721 llvm::OpenMPIRBuilder::InsertPointTy AllocaIP( 1722 AllocaInsertPt->getParent(), AllocaInsertPt->getIterator()); 1723 Builder.restoreIP( 1724 OMPBuilder.createParallel(Builder, AllocaIP, BodyGenCB, PrivCB, FiniCB, 1725 IfCond, NumThreads, ProcBind, S.hasCancel())); 1726 return; 1727 } 1728 1729 // Emit parallel region as a standalone region. 1730 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 1731 Action.Enter(CGF); 1732 OMPPrivateScope PrivateScope(CGF); 1733 bool Copyins = CGF.EmitOMPCopyinClause(S); 1734 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 1735 if (Copyins) { 1736 // Emit implicit barrier to synchronize threads and avoid data races on 1737 // propagation master's thread values of threadprivate variables to local 1738 // instances of that variables of all other implicit threads. 1739 CGF.CGM.getOpenMPRuntime().emitBarrierCall( 1740 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 1741 /*ForceSimpleCall=*/true); 1742 } 1743 CGF.EmitOMPPrivateClause(S, PrivateScope); 1744 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 1745 (void)PrivateScope.Privatize(); 1746 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt()); 1747 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 1748 }; 1749 { 1750 auto LPCRegion = 1751 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 1752 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen, 1753 emitEmptyBoundParameters); 1754 emitPostUpdateForReductionClause(*this, S, 1755 [](CodeGenFunction &) { return nullptr; }); 1756 } 1757 // Check for outer lastprivate conditional update. 1758 checkForLastprivateConditionalUpdate(*this, S); 1759 } 1760 1761 namespace { 1762 /// RAII to handle scopes for loop transformation directives. 1763 class OMPTransformDirectiveScopeRAII { 1764 OMPLoopScope *Scope = nullptr; 1765 CodeGenFunction::CGCapturedStmtInfo *CGSI = nullptr; 1766 CodeGenFunction::CGCapturedStmtRAII *CapInfoRAII = nullptr; 1767 1768 public: 1769 OMPTransformDirectiveScopeRAII(CodeGenFunction &CGF, const Stmt *S) { 1770 if (const auto *Dir = dyn_cast<OMPLoopBasedDirective>(S)) { 1771 Scope = new OMPLoopScope(CGF, *Dir); 1772 CGSI = new CodeGenFunction::CGCapturedStmtInfo(CR_OpenMP); 1773 CapInfoRAII = new CodeGenFunction::CGCapturedStmtRAII(CGF, CGSI); 1774 } 1775 } 1776 ~OMPTransformDirectiveScopeRAII() { 1777 if (!Scope) 1778 return; 1779 delete CapInfoRAII; 1780 delete CGSI; 1781 delete Scope; 1782 } 1783 }; 1784 } // namespace 1785 1786 static void emitBody(CodeGenFunction &CGF, const Stmt *S, const Stmt *NextLoop, 1787 int MaxLevel, int Level = 0) { 1788 assert(Level < MaxLevel && "Too deep lookup during loop body codegen."); 1789 const Stmt *SimplifiedS = S->IgnoreContainers(); 1790 if (const auto *CS = dyn_cast<CompoundStmt>(SimplifiedS)) { 1791 PrettyStackTraceLoc CrashInfo( 1792 CGF.getContext().getSourceManager(), CS->getLBracLoc(), 1793 "LLVM IR generation of compound statement ('{}')"); 1794 1795 // Keep track of the current cleanup stack depth, including debug scopes. 1796 CodeGenFunction::LexicalScope Scope(CGF, S->getSourceRange()); 1797 for (const Stmt *CurStmt : CS->body()) 1798 emitBody(CGF, CurStmt, NextLoop, MaxLevel, Level); 1799 return; 1800 } 1801 if (SimplifiedS == NextLoop) { 1802 OMPTransformDirectiveScopeRAII PossiblyTransformDirectiveScope(CGF, 1803 SimplifiedS); 1804 if (auto *Dir = dyn_cast<OMPTileDirective>(SimplifiedS)) 1805 SimplifiedS = Dir->getTransformedStmt(); 1806 if (const auto *CanonLoop = dyn_cast<OMPCanonicalLoop>(SimplifiedS)) 1807 SimplifiedS = CanonLoop->getLoopStmt(); 1808 if (const auto *For = dyn_cast<ForStmt>(SimplifiedS)) { 1809 S = For->getBody(); 1810 } else { 1811 assert(isa<CXXForRangeStmt>(SimplifiedS) && 1812 "Expected canonical for loop or range-based for loop."); 1813 const auto *CXXFor = cast<CXXForRangeStmt>(SimplifiedS); 1814 CGF.EmitStmt(CXXFor->getLoopVarStmt()); 1815 S = CXXFor->getBody(); 1816 } 1817 if (Level + 1 < MaxLevel) { 1818 NextLoop = OMPLoopDirective::tryToFindNextInnerLoop( 1819 S, /*TryImperfectlyNestedLoops=*/true); 1820 emitBody(CGF, S, NextLoop, MaxLevel, Level + 1); 1821 return; 1822 } 1823 } 1824 CGF.EmitStmt(S); 1825 } 1826 1827 void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D, 1828 JumpDest LoopExit) { 1829 RunCleanupsScope BodyScope(*this); 1830 // Update counters values on current iteration. 1831 for (const Expr *UE : D.updates()) 1832 EmitIgnoredExpr(UE); 1833 // Update the linear variables. 1834 // In distribute directives only loop counters may be marked as linear, no 1835 // need to generate the code for them. 1836 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) { 1837 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 1838 for (const Expr *UE : C->updates()) 1839 EmitIgnoredExpr(UE); 1840 } 1841 } 1842 1843 // On a continue in the body, jump to the end. 1844 JumpDest Continue = getJumpDestInCurrentScope("omp.body.continue"); 1845 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 1846 for (const Expr *E : D.finals_conditions()) { 1847 if (!E) 1848 continue; 1849 // Check that loop counter in non-rectangular nest fits into the iteration 1850 // space. 1851 llvm::BasicBlock *NextBB = createBasicBlock("omp.body.next"); 1852 EmitBranchOnBoolExpr(E, NextBB, Continue.getBlock(), 1853 getProfileCount(D.getBody())); 1854 EmitBlock(NextBB); 1855 } 1856 1857 OMPPrivateScope InscanScope(*this); 1858 EmitOMPReductionClauseInit(D, InscanScope, /*ForInscan=*/true); 1859 bool IsInscanRegion = InscanScope.Privatize(); 1860 if (IsInscanRegion) { 1861 // Need to remember the block before and after scan directive 1862 // to dispatch them correctly depending on the clause used in 1863 // this directive, inclusive or exclusive. For inclusive scan the natural 1864 // order of the blocks is used, for exclusive clause the blocks must be 1865 // executed in reverse order. 1866 OMPBeforeScanBlock = createBasicBlock("omp.before.scan.bb"); 1867 OMPAfterScanBlock = createBasicBlock("omp.after.scan.bb"); 1868 // No need to allocate inscan exit block, in simd mode it is selected in the 1869 // codegen for the scan directive. 1870 if (D.getDirectiveKind() != OMPD_simd && !getLangOpts().OpenMPSimd) 1871 OMPScanExitBlock = createBasicBlock("omp.exit.inscan.bb"); 1872 OMPScanDispatch = createBasicBlock("omp.inscan.dispatch"); 1873 EmitBranch(OMPScanDispatch); 1874 EmitBlock(OMPBeforeScanBlock); 1875 } 1876 1877 // Emit loop variables for C++ range loops. 1878 const Stmt *Body = 1879 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(); 1880 // Emit loop body. 1881 emitBody(*this, Body, 1882 OMPLoopBasedDirective::tryToFindNextInnerLoop( 1883 Body, /*TryImperfectlyNestedLoops=*/true), 1884 D.getLoopsNumber()); 1885 1886 // Jump to the dispatcher at the end of the loop body. 1887 if (IsInscanRegion) 1888 EmitBranch(OMPScanExitBlock); 1889 1890 // The end (updates/cleanups). 1891 EmitBlock(Continue.getBlock()); 1892 BreakContinueStack.pop_back(); 1893 } 1894 1895 using EmittedClosureTy = std::pair<llvm::Function *, llvm::Value *>; 1896 1897 /// Emit a captured statement and return the function as well as its captured 1898 /// closure context. 1899 static EmittedClosureTy emitCapturedStmtFunc(CodeGenFunction &ParentCGF, 1900 const CapturedStmt *S) { 1901 LValue CapStruct = ParentCGF.InitCapturedStruct(*S); 1902 CodeGenFunction CGF(ParentCGF.CGM, /*suppressNewContext=*/true); 1903 std::unique_ptr<CodeGenFunction::CGCapturedStmtInfo> CSI = 1904 std::make_unique<CodeGenFunction::CGCapturedStmtInfo>(*S); 1905 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, CSI.get()); 1906 llvm::Function *F = CGF.GenerateCapturedStmtFunction(*S); 1907 1908 return {F, CapStruct.getPointer(ParentCGF)}; 1909 } 1910 1911 /// Emit a call to a previously captured closure. 1912 static llvm::CallInst * 1913 emitCapturedStmtCall(CodeGenFunction &ParentCGF, EmittedClosureTy Cap, 1914 llvm::ArrayRef<llvm::Value *> Args) { 1915 // Append the closure context to the argument. 1916 SmallVector<llvm::Value *> EffectiveArgs; 1917 EffectiveArgs.reserve(Args.size() + 1); 1918 llvm::append_range(EffectiveArgs, Args); 1919 EffectiveArgs.push_back(Cap.second); 1920 1921 return ParentCGF.Builder.CreateCall(Cap.first, EffectiveArgs); 1922 } 1923 1924 llvm::CanonicalLoopInfo * 1925 CodeGenFunction::EmitOMPCollapsedCanonicalLoopNest(const Stmt *S, int Depth) { 1926 assert(Depth == 1 && "Nested loops with OpenMPIRBuilder not yet implemented"); 1927 1928 EmitStmt(S); 1929 assert(OMPLoopNestStack.size() >= (size_t)Depth && "Found too few loops"); 1930 1931 // The last added loop is the outermost one. 1932 return OMPLoopNestStack.back(); 1933 } 1934 1935 void CodeGenFunction::EmitOMPCanonicalLoop(const OMPCanonicalLoop *S) { 1936 const Stmt *SyntacticalLoop = S->getLoopStmt(); 1937 if (!getLangOpts().OpenMPIRBuilder) { 1938 // Ignore if OpenMPIRBuilder is not enabled. 1939 EmitStmt(SyntacticalLoop); 1940 return; 1941 } 1942 1943 LexicalScope ForScope(*this, S->getSourceRange()); 1944 1945 // Emit init statements. The Distance/LoopVar funcs may reference variable 1946 // declarations they contain. 1947 const Stmt *BodyStmt; 1948 if (const auto *For = dyn_cast<ForStmt>(SyntacticalLoop)) { 1949 if (const Stmt *InitStmt = For->getInit()) 1950 EmitStmt(InitStmt); 1951 BodyStmt = For->getBody(); 1952 } else if (const auto *RangeFor = 1953 dyn_cast<CXXForRangeStmt>(SyntacticalLoop)) { 1954 if (const DeclStmt *RangeStmt = RangeFor->getRangeStmt()) 1955 EmitStmt(RangeStmt); 1956 if (const DeclStmt *BeginStmt = RangeFor->getBeginStmt()) 1957 EmitStmt(BeginStmt); 1958 if (const DeclStmt *EndStmt = RangeFor->getEndStmt()) 1959 EmitStmt(EndStmt); 1960 if (const DeclStmt *LoopVarStmt = RangeFor->getLoopVarStmt()) 1961 EmitStmt(LoopVarStmt); 1962 BodyStmt = RangeFor->getBody(); 1963 } else 1964 llvm_unreachable("Expected for-stmt or range-based for-stmt"); 1965 1966 // Emit closure for later use. By-value captures will be captured here. 1967 const CapturedStmt *DistanceFunc = S->getDistanceFunc(); 1968 EmittedClosureTy DistanceClosure = emitCapturedStmtFunc(*this, DistanceFunc); 1969 const CapturedStmt *LoopVarFunc = S->getLoopVarFunc(); 1970 EmittedClosureTy LoopVarClosure = emitCapturedStmtFunc(*this, LoopVarFunc); 1971 1972 // Call the distance function to get the number of iterations of the loop to 1973 // come. 1974 QualType LogicalTy = DistanceFunc->getCapturedDecl() 1975 ->getParam(0) 1976 ->getType() 1977 .getNonReferenceType(); 1978 Address CountAddr = CreateMemTemp(LogicalTy, ".count.addr"); 1979 emitCapturedStmtCall(*this, DistanceClosure, {CountAddr.getPointer()}); 1980 llvm::Value *DistVal = Builder.CreateLoad(CountAddr, ".count"); 1981 1982 // Emit the loop structure. 1983 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 1984 auto BodyGen = [&, this](llvm::OpenMPIRBuilder::InsertPointTy CodeGenIP, 1985 llvm::Value *IndVar) { 1986 Builder.restoreIP(CodeGenIP); 1987 1988 // Emit the loop body: Convert the logical iteration number to the loop 1989 // variable and emit the body. 1990 const DeclRefExpr *LoopVarRef = S->getLoopVarRef(); 1991 LValue LCVal = EmitLValue(LoopVarRef); 1992 Address LoopVarAddress = LCVal.getAddress(*this); 1993 emitCapturedStmtCall(*this, LoopVarClosure, 1994 {LoopVarAddress.getPointer(), IndVar}); 1995 1996 RunCleanupsScope BodyScope(*this); 1997 EmitStmt(BodyStmt); 1998 }; 1999 llvm::CanonicalLoopInfo *CL = 2000 OMPBuilder.createCanonicalLoop(Builder, BodyGen, DistVal); 2001 2002 // Finish up the loop. 2003 Builder.restoreIP(CL->getAfterIP()); 2004 ForScope.ForceCleanup(); 2005 2006 // Remember the CanonicalLoopInfo for parent AST nodes consuming it. 2007 OMPLoopNestStack.push_back(CL); 2008 } 2009 2010 void CodeGenFunction::EmitOMPInnerLoop( 2011 const OMPExecutableDirective &S, bool RequiresCleanup, const Expr *LoopCond, 2012 const Expr *IncExpr, 2013 const llvm::function_ref<void(CodeGenFunction &)> BodyGen, 2014 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen) { 2015 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end"); 2016 2017 // Start the loop with a block that tests the condition. 2018 auto CondBlock = createBasicBlock("omp.inner.for.cond"); 2019 EmitBlock(CondBlock); 2020 const SourceRange R = S.getSourceRange(); 2021 2022 // If attributes are attached, push to the basic block with them. 2023 const auto &OMPED = cast<OMPExecutableDirective>(S); 2024 const CapturedStmt *ICS = OMPED.getInnermostCapturedStmt(); 2025 const Stmt *SS = ICS->getCapturedStmt(); 2026 const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(SS); 2027 OMPLoopNestStack.clear(); 2028 if (AS) 2029 LoopStack.push(CondBlock, CGM.getContext(), CGM.getCodeGenOpts(), 2030 AS->getAttrs(), SourceLocToDebugLoc(R.getBegin()), 2031 SourceLocToDebugLoc(R.getEnd())); 2032 else 2033 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()), 2034 SourceLocToDebugLoc(R.getEnd())); 2035 2036 // If there are any cleanups between here and the loop-exit scope, 2037 // create a block to stage a loop exit along. 2038 llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 2039 if (RequiresCleanup) 2040 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup"); 2041 2042 llvm::BasicBlock *LoopBody = createBasicBlock("omp.inner.for.body"); 2043 2044 // Emit condition. 2045 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S)); 2046 if (ExitBlock != LoopExit.getBlock()) { 2047 EmitBlock(ExitBlock); 2048 EmitBranchThroughCleanup(LoopExit); 2049 } 2050 2051 EmitBlock(LoopBody); 2052 incrementProfileCounter(&S); 2053 2054 // Create a block for the increment. 2055 JumpDest Continue = getJumpDestInCurrentScope("omp.inner.for.inc"); 2056 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 2057 2058 BodyGen(*this); 2059 2060 // Emit "IV = IV + 1" and a back-edge to the condition block. 2061 EmitBlock(Continue.getBlock()); 2062 EmitIgnoredExpr(IncExpr); 2063 PostIncGen(*this); 2064 BreakContinueStack.pop_back(); 2065 EmitBranch(CondBlock); 2066 LoopStack.pop(); 2067 // Emit the fall-through block. 2068 EmitBlock(LoopExit.getBlock()); 2069 } 2070 2071 bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) { 2072 if (!HaveInsertPoint()) 2073 return false; 2074 // Emit inits for the linear variables. 2075 bool HasLinears = false; 2076 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 2077 for (const Expr *Init : C->inits()) { 2078 HasLinears = true; 2079 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl()); 2080 if (const auto *Ref = 2081 dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) { 2082 AutoVarEmission Emission = EmitAutoVarAlloca(*VD); 2083 const auto *OrigVD = cast<VarDecl>(Ref->getDecl()); 2084 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), 2085 CapturedStmtInfo->lookup(OrigVD) != nullptr, 2086 VD->getInit()->getType(), VK_LValue, 2087 VD->getInit()->getExprLoc()); 2088 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(), 2089 VD->getType()), 2090 /*capturedByInit=*/false); 2091 EmitAutoVarCleanups(Emission); 2092 } else { 2093 EmitVarDecl(*VD); 2094 } 2095 } 2096 // Emit the linear steps for the linear clauses. 2097 // If a step is not constant, it is pre-calculated before the loop. 2098 if (const auto *CS = cast_or_null<BinaryOperator>(C->getCalcStep())) 2099 if (const auto *SaveRef = cast<DeclRefExpr>(CS->getLHS())) { 2100 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl())); 2101 // Emit calculation of the linear step. 2102 EmitIgnoredExpr(CS); 2103 } 2104 } 2105 return HasLinears; 2106 } 2107 2108 void CodeGenFunction::EmitOMPLinearClauseFinal( 2109 const OMPLoopDirective &D, 2110 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) { 2111 if (!HaveInsertPoint()) 2112 return; 2113 llvm::BasicBlock *DoneBB = nullptr; 2114 // Emit the final values of the linear variables. 2115 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 2116 auto IC = C->varlist_begin(); 2117 for (const Expr *F : C->finals()) { 2118 if (!DoneBB) { 2119 if (llvm::Value *Cond = CondGen(*this)) { 2120 // If the first post-update expression is found, emit conditional 2121 // block if it was requested. 2122 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.linear.pu"); 2123 DoneBB = createBasicBlock(".omp.linear.pu.done"); 2124 Builder.CreateCondBr(Cond, ThenBB, DoneBB); 2125 EmitBlock(ThenBB); 2126 } 2127 } 2128 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl()); 2129 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), 2130 CapturedStmtInfo->lookup(OrigVD) != nullptr, 2131 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc()); 2132 Address OrigAddr = EmitLValue(&DRE).getAddress(*this); 2133 CodeGenFunction::OMPPrivateScope VarScope(*this); 2134 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; }); 2135 (void)VarScope.Privatize(); 2136 EmitIgnoredExpr(F); 2137 ++IC; 2138 } 2139 if (const Expr *PostUpdate = C->getPostUpdateExpr()) 2140 EmitIgnoredExpr(PostUpdate); 2141 } 2142 if (DoneBB) 2143 EmitBlock(DoneBB, /*IsFinished=*/true); 2144 } 2145 2146 static void emitAlignedClause(CodeGenFunction &CGF, 2147 const OMPExecutableDirective &D) { 2148 if (!CGF.HaveInsertPoint()) 2149 return; 2150 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) { 2151 llvm::APInt ClauseAlignment(64, 0); 2152 if (const Expr *AlignmentExpr = Clause->getAlignment()) { 2153 auto *AlignmentCI = 2154 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr)); 2155 ClauseAlignment = AlignmentCI->getValue(); 2156 } 2157 for (const Expr *E : Clause->varlists()) { 2158 llvm::APInt Alignment(ClauseAlignment); 2159 if (Alignment == 0) { 2160 // OpenMP [2.8.1, Description] 2161 // If no optional parameter is specified, implementation-defined default 2162 // alignments for SIMD instructions on the target platforms are assumed. 2163 Alignment = 2164 CGF.getContext() 2165 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign( 2166 E->getType()->getPointeeType())) 2167 .getQuantity(); 2168 } 2169 assert((Alignment == 0 || Alignment.isPowerOf2()) && 2170 "alignment is not power of 2"); 2171 if (Alignment != 0) { 2172 llvm::Value *PtrValue = CGF.EmitScalarExpr(E); 2173 CGF.emitAlignmentAssumption( 2174 PtrValue, E, /*No second loc needed*/ SourceLocation(), 2175 llvm::ConstantInt::get(CGF.getLLVMContext(), Alignment)); 2176 } 2177 } 2178 } 2179 } 2180 2181 void CodeGenFunction::EmitOMPPrivateLoopCounters( 2182 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) { 2183 if (!HaveInsertPoint()) 2184 return; 2185 auto I = S.private_counters().begin(); 2186 for (const Expr *E : S.counters()) { 2187 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 2188 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()); 2189 // Emit var without initialization. 2190 AutoVarEmission VarEmission = EmitAutoVarAlloca(*PrivateVD); 2191 EmitAutoVarCleanups(VarEmission); 2192 LocalDeclMap.erase(PrivateVD); 2193 (void)LoopScope.addPrivate(VD, [&VarEmission]() { 2194 return VarEmission.getAllocatedAddress(); 2195 }); 2196 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) || 2197 VD->hasGlobalStorage()) { 2198 (void)LoopScope.addPrivate(PrivateVD, [this, VD, E]() { 2199 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), 2200 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD), 2201 E->getType(), VK_LValue, E->getExprLoc()); 2202 return EmitLValue(&DRE).getAddress(*this); 2203 }); 2204 } else { 2205 (void)LoopScope.addPrivate(PrivateVD, [&VarEmission]() { 2206 return VarEmission.getAllocatedAddress(); 2207 }); 2208 } 2209 ++I; 2210 } 2211 // Privatize extra loop counters used in loops for ordered(n) clauses. 2212 for (const auto *C : S.getClausesOfKind<OMPOrderedClause>()) { 2213 if (!C->getNumForLoops()) 2214 continue; 2215 for (unsigned I = S.getLoopsNumber(), E = C->getLoopNumIterations().size(); 2216 I < E; ++I) { 2217 const auto *DRE = cast<DeclRefExpr>(C->getLoopCounter(I)); 2218 const auto *VD = cast<VarDecl>(DRE->getDecl()); 2219 // Override only those variables that can be captured to avoid re-emission 2220 // of the variables declared within the loops. 2221 if (DRE->refersToEnclosingVariableOrCapture()) { 2222 (void)LoopScope.addPrivate(VD, [this, DRE, VD]() { 2223 return CreateMemTemp(DRE->getType(), VD->getName()); 2224 }); 2225 } 2226 } 2227 } 2228 } 2229 2230 static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S, 2231 const Expr *Cond, llvm::BasicBlock *TrueBlock, 2232 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) { 2233 if (!CGF.HaveInsertPoint()) 2234 return; 2235 { 2236 CodeGenFunction::OMPPrivateScope PreCondScope(CGF); 2237 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope); 2238 (void)PreCondScope.Privatize(); 2239 // Get initial values of real counters. 2240 for (const Expr *I : S.inits()) { 2241 CGF.EmitIgnoredExpr(I); 2242 } 2243 } 2244 // Create temp loop control variables with their init values to support 2245 // non-rectangular loops. 2246 CodeGenFunction::OMPMapVars PreCondVars; 2247 for (const Expr * E: S.dependent_counters()) { 2248 if (!E) 2249 continue; 2250 assert(!E->getType().getNonReferenceType()->isRecordType() && 2251 "dependent counter must not be an iterator."); 2252 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 2253 Address CounterAddr = 2254 CGF.CreateMemTemp(VD->getType().getNonReferenceType()); 2255 (void)PreCondVars.setVarAddr(CGF, VD, CounterAddr); 2256 } 2257 (void)PreCondVars.apply(CGF); 2258 for (const Expr *E : S.dependent_inits()) { 2259 if (!E) 2260 continue; 2261 CGF.EmitIgnoredExpr(E); 2262 } 2263 // Check that loop is executed at least one time. 2264 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount); 2265 PreCondVars.restore(CGF); 2266 } 2267 2268 void CodeGenFunction::EmitOMPLinearClause( 2269 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) { 2270 if (!HaveInsertPoint()) 2271 return; 2272 llvm::DenseSet<const VarDecl *> SIMDLCVs; 2273 if (isOpenMPSimdDirective(D.getDirectiveKind())) { 2274 const auto *LoopDirective = cast<OMPLoopDirective>(&D); 2275 for (const Expr *C : LoopDirective->counters()) { 2276 SIMDLCVs.insert( 2277 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl()); 2278 } 2279 } 2280 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 2281 auto CurPrivate = C->privates().begin(); 2282 for (const Expr *E : C->varlists()) { 2283 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 2284 const auto *PrivateVD = 2285 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl()); 2286 if (!SIMDLCVs.count(VD->getCanonicalDecl())) { 2287 bool IsRegistered = PrivateScope.addPrivate(VD, [this, PrivateVD]() { 2288 // Emit private VarDecl with copy init. 2289 EmitVarDecl(*PrivateVD); 2290 return GetAddrOfLocalVar(PrivateVD); 2291 }); 2292 assert(IsRegistered && "linear var already registered as private"); 2293 // Silence the warning about unused variable. 2294 (void)IsRegistered; 2295 } else { 2296 EmitVarDecl(*PrivateVD); 2297 } 2298 ++CurPrivate; 2299 } 2300 } 2301 } 2302 2303 static void emitSimdlenSafelenClause(CodeGenFunction &CGF, 2304 const OMPExecutableDirective &D, 2305 bool IsMonotonic) { 2306 if (!CGF.HaveInsertPoint()) 2307 return; 2308 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) { 2309 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(), 2310 /*ignoreResult=*/true); 2311 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal()); 2312 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue()); 2313 // In presence of finite 'safelen', it may be unsafe to mark all 2314 // the memory instructions parallel, because loop-carried 2315 // dependences of 'safelen' iterations are possible. 2316 if (!IsMonotonic) 2317 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>()); 2318 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) { 2319 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(), 2320 /*ignoreResult=*/true); 2321 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal()); 2322 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue()); 2323 // In presence of finite 'safelen', it may be unsafe to mark all 2324 // the memory instructions parallel, because loop-carried 2325 // dependences of 'safelen' iterations are possible. 2326 CGF.LoopStack.setParallel(/*Enable=*/false); 2327 } 2328 } 2329 2330 void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D, 2331 bool IsMonotonic) { 2332 // Walk clauses and process safelen/lastprivate. 2333 LoopStack.setParallel(!IsMonotonic); 2334 LoopStack.setVectorizeEnable(); 2335 emitSimdlenSafelenClause(*this, D, IsMonotonic); 2336 if (const auto *C = D.getSingleClause<OMPOrderClause>()) 2337 if (C->getKind() == OMPC_ORDER_concurrent) 2338 LoopStack.setParallel(/*Enable=*/true); 2339 if ((D.getDirectiveKind() == OMPD_simd || 2340 (getLangOpts().OpenMPSimd && 2341 isOpenMPSimdDirective(D.getDirectiveKind()))) && 2342 llvm::any_of(D.getClausesOfKind<OMPReductionClause>(), 2343 [](const OMPReductionClause *C) { 2344 return C->getModifier() == OMPC_REDUCTION_inscan; 2345 })) 2346 // Disable parallel access in case of prefix sum. 2347 LoopStack.setParallel(/*Enable=*/false); 2348 } 2349 2350 void CodeGenFunction::EmitOMPSimdFinal( 2351 const OMPLoopDirective &D, 2352 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) { 2353 if (!HaveInsertPoint()) 2354 return; 2355 llvm::BasicBlock *DoneBB = nullptr; 2356 auto IC = D.counters().begin(); 2357 auto IPC = D.private_counters().begin(); 2358 for (const Expr *F : D.finals()) { 2359 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl()); 2360 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl()); 2361 const auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD); 2362 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) || 2363 OrigVD->hasGlobalStorage() || CED) { 2364 if (!DoneBB) { 2365 if (llvm::Value *Cond = CondGen(*this)) { 2366 // If the first post-update expression is found, emit conditional 2367 // block if it was requested. 2368 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.final.then"); 2369 DoneBB = createBasicBlock(".omp.final.done"); 2370 Builder.CreateCondBr(Cond, ThenBB, DoneBB); 2371 EmitBlock(ThenBB); 2372 } 2373 } 2374 Address OrigAddr = Address::invalid(); 2375 if (CED) { 2376 OrigAddr = 2377 EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress(*this); 2378 } else { 2379 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(PrivateVD), 2380 /*RefersToEnclosingVariableOrCapture=*/false, 2381 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc()); 2382 OrigAddr = EmitLValue(&DRE).getAddress(*this); 2383 } 2384 OMPPrivateScope VarScope(*this); 2385 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; }); 2386 (void)VarScope.Privatize(); 2387 EmitIgnoredExpr(F); 2388 } 2389 ++IC; 2390 ++IPC; 2391 } 2392 if (DoneBB) 2393 EmitBlock(DoneBB, /*IsFinished=*/true); 2394 } 2395 2396 static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF, 2397 const OMPLoopDirective &S, 2398 CodeGenFunction::JumpDest LoopExit) { 2399 CGF.EmitOMPLoopBody(S, LoopExit); 2400 CGF.EmitStopPoint(&S); 2401 } 2402 2403 /// Emit a helper variable and return corresponding lvalue. 2404 static LValue EmitOMPHelperVar(CodeGenFunction &CGF, 2405 const DeclRefExpr *Helper) { 2406 auto VDecl = cast<VarDecl>(Helper->getDecl()); 2407 CGF.EmitVarDecl(*VDecl); 2408 return CGF.EmitLValue(Helper); 2409 } 2410 2411 static void emitCommonSimdLoop(CodeGenFunction &CGF, const OMPLoopDirective &S, 2412 const RegionCodeGenTy &SimdInitGen, 2413 const RegionCodeGenTy &BodyCodeGen) { 2414 auto &&ThenGen = [&S, &SimdInitGen, &BodyCodeGen](CodeGenFunction &CGF, 2415 PrePostActionTy &) { 2416 CGOpenMPRuntime::NontemporalDeclsRAII NontemporalsRegion(CGF.CGM, S); 2417 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF); 2418 SimdInitGen(CGF); 2419 2420 BodyCodeGen(CGF); 2421 }; 2422 auto &&ElseGen = [&BodyCodeGen](CodeGenFunction &CGF, PrePostActionTy &) { 2423 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF); 2424 CGF.LoopStack.setVectorizeEnable(/*Enable=*/false); 2425 2426 BodyCodeGen(CGF); 2427 }; 2428 const Expr *IfCond = nullptr; 2429 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 2430 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 2431 if (CGF.getLangOpts().OpenMP >= 50 && 2432 (C->getNameModifier() == OMPD_unknown || 2433 C->getNameModifier() == OMPD_simd)) { 2434 IfCond = C->getCondition(); 2435 break; 2436 } 2437 } 2438 } 2439 if (IfCond) { 2440 CGF.CGM.getOpenMPRuntime().emitIfClause(CGF, IfCond, ThenGen, ElseGen); 2441 } else { 2442 RegionCodeGenTy ThenRCG(ThenGen); 2443 ThenRCG(CGF); 2444 } 2445 } 2446 2447 static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S, 2448 PrePostActionTy &Action) { 2449 Action.Enter(CGF); 2450 assert(isOpenMPSimdDirective(S.getDirectiveKind()) && 2451 "Expected simd directive"); 2452 OMPLoopScope PreInitScope(CGF, S); 2453 // if (PreCond) { 2454 // for (IV in 0..LastIteration) BODY; 2455 // <Final counter/linear vars updates>; 2456 // } 2457 // 2458 if (isOpenMPDistributeDirective(S.getDirectiveKind()) || 2459 isOpenMPWorksharingDirective(S.getDirectiveKind()) || 2460 isOpenMPTaskLoopDirective(S.getDirectiveKind())) { 2461 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable())); 2462 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable())); 2463 } 2464 2465 // Emit: if (PreCond) - begin. 2466 // If the condition constant folds and can be elided, avoid emitting the 2467 // whole loop. 2468 bool CondConstant; 2469 llvm::BasicBlock *ContBlock = nullptr; 2470 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 2471 if (!CondConstant) 2472 return; 2473 } else { 2474 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("simd.if.then"); 2475 ContBlock = CGF.createBasicBlock("simd.if.end"); 2476 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock, 2477 CGF.getProfileCount(&S)); 2478 CGF.EmitBlock(ThenBlock); 2479 CGF.incrementProfileCounter(&S); 2480 } 2481 2482 // Emit the loop iteration variable. 2483 const Expr *IVExpr = S.getIterationVariable(); 2484 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl()); 2485 CGF.EmitVarDecl(*IVDecl); 2486 CGF.EmitIgnoredExpr(S.getInit()); 2487 2488 // Emit the iterations count variable. 2489 // If it is not a variable, Sema decided to calculate iterations count on 2490 // each iteration (e.g., it is foldable into a constant). 2491 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 2492 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 2493 // Emit calculation of the iterations count. 2494 CGF.EmitIgnoredExpr(S.getCalcLastIteration()); 2495 } 2496 2497 emitAlignedClause(CGF, S); 2498 (void)CGF.EmitOMPLinearClauseInit(S); 2499 { 2500 CodeGenFunction::OMPPrivateScope LoopScope(CGF); 2501 CGF.EmitOMPPrivateLoopCounters(S, LoopScope); 2502 CGF.EmitOMPLinearClause(S, LoopScope); 2503 CGF.EmitOMPPrivateClause(S, LoopScope); 2504 CGF.EmitOMPReductionClauseInit(S, LoopScope); 2505 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion( 2506 CGF, S, CGF.EmitLValue(S.getIterationVariable())); 2507 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 2508 (void)LoopScope.Privatize(); 2509 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 2510 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 2511 2512 emitCommonSimdLoop( 2513 CGF, S, 2514 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2515 CGF.EmitOMPSimdInit(S); 2516 }, 2517 [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) { 2518 CGF.EmitOMPInnerLoop( 2519 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(), 2520 [&S](CodeGenFunction &CGF) { 2521 emitOMPLoopBodyWithStopPoint(CGF, S, 2522 CodeGenFunction::JumpDest()); 2523 }, 2524 [](CodeGenFunction &) {}); 2525 }); 2526 CGF.EmitOMPSimdFinal(S, [](CodeGenFunction &) { return nullptr; }); 2527 // Emit final copy of the lastprivate variables at the end of loops. 2528 if (HasLastprivateClause) 2529 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true); 2530 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd); 2531 emitPostUpdateForReductionClause(CGF, S, 2532 [](CodeGenFunction &) { return nullptr; }); 2533 } 2534 CGF.EmitOMPLinearClauseFinal(S, [](CodeGenFunction &) { return nullptr; }); 2535 // Emit: if (PreCond) - end. 2536 if (ContBlock) { 2537 CGF.EmitBranch(ContBlock); 2538 CGF.EmitBlock(ContBlock, true); 2539 } 2540 } 2541 2542 void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) { 2543 ParentLoopDirectiveForScanRegion ScanRegion(*this, S); 2544 OMPFirstScanLoop = true; 2545 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 2546 emitOMPSimdRegion(CGF, S, Action); 2547 }; 2548 { 2549 auto LPCRegion = 2550 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 2551 OMPLexicalScope Scope(*this, S, OMPD_unknown); 2552 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen); 2553 } 2554 // Check for outer lastprivate conditional update. 2555 checkForLastprivateConditionalUpdate(*this, S); 2556 } 2557 2558 void CodeGenFunction::EmitOMPTileDirective(const OMPTileDirective &S) { 2559 // Emit the de-sugared statement. 2560 OMPTransformDirectiveScopeRAII TileScope(*this, &S); 2561 EmitStmt(S.getTransformedStmt()); 2562 } 2563 2564 void CodeGenFunction::EmitOMPOuterLoop( 2565 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S, 2566 CodeGenFunction::OMPPrivateScope &LoopScope, 2567 const CodeGenFunction::OMPLoopArguments &LoopArgs, 2568 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop, 2569 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) { 2570 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 2571 2572 const Expr *IVExpr = S.getIterationVariable(); 2573 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 2574 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 2575 2576 JumpDest LoopExit = getJumpDestInCurrentScope("omp.dispatch.end"); 2577 2578 // Start the loop with a block that tests the condition. 2579 llvm::BasicBlock *CondBlock = createBasicBlock("omp.dispatch.cond"); 2580 EmitBlock(CondBlock); 2581 const SourceRange R = S.getSourceRange(); 2582 OMPLoopNestStack.clear(); 2583 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()), 2584 SourceLocToDebugLoc(R.getEnd())); 2585 2586 llvm::Value *BoolCondVal = nullptr; 2587 if (!DynamicOrOrdered) { 2588 // UB = min(UB, GlobalUB) or 2589 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g. 2590 // 'distribute parallel for') 2591 EmitIgnoredExpr(LoopArgs.EUB); 2592 // IV = LB 2593 EmitIgnoredExpr(LoopArgs.Init); 2594 // IV < UB 2595 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond); 2596 } else { 2597 BoolCondVal = 2598 RT.emitForNext(*this, S.getBeginLoc(), IVSize, IVSigned, LoopArgs.IL, 2599 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST); 2600 } 2601 2602 // If there are any cleanups between here and the loop-exit scope, 2603 // create a block to stage a loop exit along. 2604 llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 2605 if (LoopScope.requiresCleanups()) 2606 ExitBlock = createBasicBlock("omp.dispatch.cleanup"); 2607 2608 llvm::BasicBlock *LoopBody = createBasicBlock("omp.dispatch.body"); 2609 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock); 2610 if (ExitBlock != LoopExit.getBlock()) { 2611 EmitBlock(ExitBlock); 2612 EmitBranchThroughCleanup(LoopExit); 2613 } 2614 EmitBlock(LoopBody); 2615 2616 // Emit "IV = LB" (in case of static schedule, we have already calculated new 2617 // LB for loop condition and emitted it above). 2618 if (DynamicOrOrdered) 2619 EmitIgnoredExpr(LoopArgs.Init); 2620 2621 // Create a block for the increment. 2622 JumpDest Continue = getJumpDestInCurrentScope("omp.dispatch.inc"); 2623 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 2624 2625 emitCommonSimdLoop( 2626 *this, S, 2627 [&S, IsMonotonic](CodeGenFunction &CGF, PrePostActionTy &) { 2628 // Generate !llvm.loop.parallel metadata for loads and stores for loops 2629 // with dynamic/guided scheduling and without ordered clause. 2630 if (!isOpenMPSimdDirective(S.getDirectiveKind())) { 2631 CGF.LoopStack.setParallel(!IsMonotonic); 2632 if (const auto *C = S.getSingleClause<OMPOrderClause>()) 2633 if (C->getKind() == OMPC_ORDER_concurrent) 2634 CGF.LoopStack.setParallel(/*Enable=*/true); 2635 } else { 2636 CGF.EmitOMPSimdInit(S, IsMonotonic); 2637 } 2638 }, 2639 [&S, &LoopArgs, LoopExit, &CodeGenLoop, IVSize, IVSigned, &CodeGenOrdered, 2640 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) { 2641 SourceLocation Loc = S.getBeginLoc(); 2642 // when 'distribute' is not combined with a 'for': 2643 // while (idx <= UB) { BODY; ++idx; } 2644 // when 'distribute' is combined with a 'for' 2645 // (e.g. 'distribute parallel for') 2646 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; } 2647 CGF.EmitOMPInnerLoop( 2648 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr, 2649 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) { 2650 CodeGenLoop(CGF, S, LoopExit); 2651 }, 2652 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) { 2653 CodeGenOrdered(CGF, Loc, IVSize, IVSigned); 2654 }); 2655 }); 2656 2657 EmitBlock(Continue.getBlock()); 2658 BreakContinueStack.pop_back(); 2659 if (!DynamicOrOrdered) { 2660 // Emit "LB = LB + Stride", "UB = UB + Stride". 2661 EmitIgnoredExpr(LoopArgs.NextLB); 2662 EmitIgnoredExpr(LoopArgs.NextUB); 2663 } 2664 2665 EmitBranch(CondBlock); 2666 OMPLoopNestStack.clear(); 2667 LoopStack.pop(); 2668 // Emit the fall-through block. 2669 EmitBlock(LoopExit.getBlock()); 2670 2671 // Tell the runtime we are done. 2672 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) { 2673 if (!DynamicOrOrdered) 2674 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(), 2675 S.getDirectiveKind()); 2676 }; 2677 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen); 2678 } 2679 2680 void CodeGenFunction::EmitOMPForOuterLoop( 2681 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic, 2682 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered, 2683 const OMPLoopArguments &LoopArgs, 2684 const CodeGenDispatchBoundsTy &CGDispatchBounds) { 2685 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 2686 2687 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime). 2688 const bool DynamicOrOrdered = 2689 Ordered || RT.isDynamic(ScheduleKind.Schedule); 2690 2691 assert((Ordered || 2692 !RT.isStaticNonchunked(ScheduleKind.Schedule, 2693 LoopArgs.Chunk != nullptr)) && 2694 "static non-chunked schedule does not need outer loop"); 2695 2696 // Emit outer loop. 2697 // 2698 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 2699 // When schedule(dynamic,chunk_size) is specified, the iterations are 2700 // distributed to threads in the team in chunks as the threads request them. 2701 // Each thread executes a chunk of iterations, then requests another chunk, 2702 // until no chunks remain to be distributed. Each chunk contains chunk_size 2703 // iterations, except for the last chunk to be distributed, which may have 2704 // fewer iterations. When no chunk_size is specified, it defaults to 1. 2705 // 2706 // When schedule(guided,chunk_size) is specified, the iterations are assigned 2707 // to threads in the team in chunks as the executing threads request them. 2708 // Each thread executes a chunk of iterations, then requests another chunk, 2709 // until no chunks remain to be assigned. For a chunk_size of 1, the size of 2710 // each chunk is proportional to the number of unassigned iterations divided 2711 // by the number of threads in the team, decreasing to 1. For a chunk_size 2712 // with value k (greater than 1), the size of each chunk is determined in the 2713 // same way, with the restriction that the chunks do not contain fewer than k 2714 // iterations (except for the last chunk to be assigned, which may have fewer 2715 // than k iterations). 2716 // 2717 // When schedule(auto) is specified, the decision regarding scheduling is 2718 // delegated to the compiler and/or runtime system. The programmer gives the 2719 // implementation the freedom to choose any possible mapping of iterations to 2720 // threads in the team. 2721 // 2722 // When schedule(runtime) is specified, the decision regarding scheduling is 2723 // deferred until run time, and the schedule and chunk size are taken from the 2724 // run-sched-var ICV. If the ICV is set to auto, the schedule is 2725 // implementation defined 2726 // 2727 // while(__kmpc_dispatch_next(&LB, &UB)) { 2728 // idx = LB; 2729 // while (idx <= UB) { BODY; ++idx; 2730 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only. 2731 // } // inner loop 2732 // } 2733 // 2734 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 2735 // When schedule(static, chunk_size) is specified, iterations are divided into 2736 // chunks of size chunk_size, and the chunks are assigned to the threads in 2737 // the team in a round-robin fashion in the order of the thread number. 2738 // 2739 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) { 2740 // while (idx <= UB) { BODY; ++idx; } // inner loop 2741 // LB = LB + ST; 2742 // UB = UB + ST; 2743 // } 2744 // 2745 2746 const Expr *IVExpr = S.getIterationVariable(); 2747 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 2748 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 2749 2750 if (DynamicOrOrdered) { 2751 const std::pair<llvm::Value *, llvm::Value *> DispatchBounds = 2752 CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB); 2753 llvm::Value *LBVal = DispatchBounds.first; 2754 llvm::Value *UBVal = DispatchBounds.second; 2755 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal, 2756 LoopArgs.Chunk}; 2757 RT.emitForDispatchInit(*this, S.getBeginLoc(), ScheduleKind, IVSize, 2758 IVSigned, Ordered, DipatchRTInputValues); 2759 } else { 2760 CGOpenMPRuntime::StaticRTInput StaticInit( 2761 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB, 2762 LoopArgs.ST, LoopArgs.Chunk); 2763 RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(), 2764 ScheduleKind, StaticInit); 2765 } 2766 2767 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc, 2768 const unsigned IVSize, 2769 const bool IVSigned) { 2770 if (Ordered) { 2771 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize, 2772 IVSigned); 2773 } 2774 }; 2775 2776 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST, 2777 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB); 2778 OuterLoopArgs.IncExpr = S.getInc(); 2779 OuterLoopArgs.Init = S.getInit(); 2780 OuterLoopArgs.Cond = S.getCond(); 2781 OuterLoopArgs.NextLB = S.getNextLowerBound(); 2782 OuterLoopArgs.NextUB = S.getNextUpperBound(); 2783 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs, 2784 emitOMPLoopBodyWithStopPoint, CodeGenOrdered); 2785 } 2786 2787 static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc, 2788 const unsigned IVSize, const bool IVSigned) {} 2789 2790 void CodeGenFunction::EmitOMPDistributeOuterLoop( 2791 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S, 2792 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs, 2793 const CodeGenLoopTy &CodeGenLoopContent) { 2794 2795 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 2796 2797 // Emit outer loop. 2798 // Same behavior as a OMPForOuterLoop, except that schedule cannot be 2799 // dynamic 2800 // 2801 2802 const Expr *IVExpr = S.getIterationVariable(); 2803 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 2804 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 2805 2806 CGOpenMPRuntime::StaticRTInput StaticInit( 2807 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB, 2808 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk); 2809 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit); 2810 2811 // for combined 'distribute' and 'for' the increment expression of distribute 2812 // is stored in DistInc. For 'distribute' alone, it is in Inc. 2813 Expr *IncExpr; 2814 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())) 2815 IncExpr = S.getDistInc(); 2816 else 2817 IncExpr = S.getInc(); 2818 2819 // this routine is shared by 'omp distribute parallel for' and 2820 // 'omp distribute': select the right EUB expression depending on the 2821 // directive 2822 OMPLoopArguments OuterLoopArgs; 2823 OuterLoopArgs.LB = LoopArgs.LB; 2824 OuterLoopArgs.UB = LoopArgs.UB; 2825 OuterLoopArgs.ST = LoopArgs.ST; 2826 OuterLoopArgs.IL = LoopArgs.IL; 2827 OuterLoopArgs.Chunk = LoopArgs.Chunk; 2828 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2829 ? S.getCombinedEnsureUpperBound() 2830 : S.getEnsureUpperBound(); 2831 OuterLoopArgs.IncExpr = IncExpr; 2832 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2833 ? S.getCombinedInit() 2834 : S.getInit(); 2835 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2836 ? S.getCombinedCond() 2837 : S.getCond(); 2838 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2839 ? S.getCombinedNextLowerBound() 2840 : S.getNextLowerBound(); 2841 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2842 ? S.getCombinedNextUpperBound() 2843 : S.getNextUpperBound(); 2844 2845 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S, 2846 LoopScope, OuterLoopArgs, CodeGenLoopContent, 2847 emitEmptyOrdered); 2848 } 2849 2850 static std::pair<LValue, LValue> 2851 emitDistributeParallelForInnerBounds(CodeGenFunction &CGF, 2852 const OMPExecutableDirective &S) { 2853 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S); 2854 LValue LB = 2855 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable())); 2856 LValue UB = 2857 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable())); 2858 2859 // When composing 'distribute' with 'for' (e.g. as in 'distribute 2860 // parallel for') we need to use the 'distribute' 2861 // chunk lower and upper bounds rather than the whole loop iteration 2862 // space. These are parameters to the outlined function for 'parallel' 2863 // and we copy the bounds of the previous schedule into the 2864 // the current ones. 2865 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable()); 2866 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable()); 2867 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar( 2868 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc()); 2869 PrevLBVal = CGF.EmitScalarConversion( 2870 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(), 2871 LS.getIterationVariable()->getType(), 2872 LS.getPrevLowerBoundVariable()->getExprLoc()); 2873 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar( 2874 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc()); 2875 PrevUBVal = CGF.EmitScalarConversion( 2876 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(), 2877 LS.getIterationVariable()->getType(), 2878 LS.getPrevUpperBoundVariable()->getExprLoc()); 2879 2880 CGF.EmitStoreOfScalar(PrevLBVal, LB); 2881 CGF.EmitStoreOfScalar(PrevUBVal, UB); 2882 2883 return {LB, UB}; 2884 } 2885 2886 /// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then 2887 /// we need to use the LB and UB expressions generated by the worksharing 2888 /// code generation support, whereas in non combined situations we would 2889 /// just emit 0 and the LastIteration expression 2890 /// This function is necessary due to the difference of the LB and UB 2891 /// types for the RT emission routines for 'for_static_init' and 2892 /// 'for_dispatch_init' 2893 static std::pair<llvm::Value *, llvm::Value *> 2894 emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF, 2895 const OMPExecutableDirective &S, 2896 Address LB, Address UB) { 2897 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S); 2898 const Expr *IVExpr = LS.getIterationVariable(); 2899 // when implementing a dynamic schedule for a 'for' combined with a 2900 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop 2901 // is not normalized as each team only executes its own assigned 2902 // distribute chunk 2903 QualType IteratorTy = IVExpr->getType(); 2904 llvm::Value *LBVal = 2905 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getBeginLoc()); 2906 llvm::Value *UBVal = 2907 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getBeginLoc()); 2908 return {LBVal, UBVal}; 2909 } 2910 2911 static void emitDistributeParallelForDistributeInnerBoundParams( 2912 CodeGenFunction &CGF, const OMPExecutableDirective &S, 2913 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) { 2914 const auto &Dir = cast<OMPLoopDirective>(S); 2915 LValue LB = 2916 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable())); 2917 llvm::Value *LBCast = 2918 CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(LB.getAddress(CGF)), 2919 CGF.SizeTy, /*isSigned=*/false); 2920 CapturedVars.push_back(LBCast); 2921 LValue UB = 2922 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable())); 2923 2924 llvm::Value *UBCast = 2925 CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(UB.getAddress(CGF)), 2926 CGF.SizeTy, /*isSigned=*/false); 2927 CapturedVars.push_back(UBCast); 2928 } 2929 2930 static void 2931 emitInnerParallelForWhenCombined(CodeGenFunction &CGF, 2932 const OMPLoopDirective &S, 2933 CodeGenFunction::JumpDest LoopExit) { 2934 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF, 2935 PrePostActionTy &Action) { 2936 Action.Enter(CGF); 2937 bool HasCancel = false; 2938 if (!isOpenMPSimdDirective(S.getDirectiveKind())) { 2939 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S)) 2940 HasCancel = D->hasCancel(); 2941 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S)) 2942 HasCancel = D->hasCancel(); 2943 else if (const auto *D = 2944 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S)) 2945 HasCancel = D->hasCancel(); 2946 } 2947 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(), 2948 HasCancel); 2949 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(), 2950 emitDistributeParallelForInnerBounds, 2951 emitDistributeParallelForDispatchBounds); 2952 }; 2953 2954 emitCommonOMPParallelDirective( 2955 CGF, S, 2956 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for, 2957 CGInlinedWorksharingLoop, 2958 emitDistributeParallelForDistributeInnerBoundParams); 2959 } 2960 2961 void CodeGenFunction::EmitOMPDistributeParallelForDirective( 2962 const OMPDistributeParallelForDirective &S) { 2963 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2964 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 2965 S.getDistInc()); 2966 }; 2967 OMPLexicalScope Scope(*this, S, OMPD_parallel); 2968 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen); 2969 } 2970 2971 void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective( 2972 const OMPDistributeParallelForSimdDirective &S) { 2973 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2974 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 2975 S.getDistInc()); 2976 }; 2977 OMPLexicalScope Scope(*this, S, OMPD_parallel); 2978 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen); 2979 } 2980 2981 void CodeGenFunction::EmitOMPDistributeSimdDirective( 2982 const OMPDistributeSimdDirective &S) { 2983 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2984 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 2985 }; 2986 OMPLexicalScope Scope(*this, S, OMPD_unknown); 2987 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen); 2988 } 2989 2990 void CodeGenFunction::EmitOMPTargetSimdDeviceFunction( 2991 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) { 2992 // Emit SPMD target parallel for region as a standalone region. 2993 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 2994 emitOMPSimdRegion(CGF, S, Action); 2995 }; 2996 llvm::Function *Fn; 2997 llvm::Constant *Addr; 2998 // Emit target region as a standalone region. 2999 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 3000 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 3001 assert(Fn && Addr && "Target device function emission failed."); 3002 } 3003 3004 void CodeGenFunction::EmitOMPTargetSimdDirective( 3005 const OMPTargetSimdDirective &S) { 3006 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3007 emitOMPSimdRegion(CGF, S, Action); 3008 }; 3009 emitCommonOMPTargetDirective(*this, S, CodeGen); 3010 } 3011 3012 namespace { 3013 struct ScheduleKindModifiersTy { 3014 OpenMPScheduleClauseKind Kind; 3015 OpenMPScheduleClauseModifier M1; 3016 OpenMPScheduleClauseModifier M2; 3017 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind, 3018 OpenMPScheduleClauseModifier M1, 3019 OpenMPScheduleClauseModifier M2) 3020 : Kind(Kind), M1(M1), M2(M2) {} 3021 }; 3022 } // namespace 3023 3024 bool CodeGenFunction::EmitOMPWorksharingLoop( 3025 const OMPLoopDirective &S, Expr *EUB, 3026 const CodeGenLoopBoundsTy &CodeGenLoopBounds, 3027 const CodeGenDispatchBoundsTy &CGDispatchBounds) { 3028 // Emit the loop iteration variable. 3029 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable()); 3030 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl()); 3031 EmitVarDecl(*IVDecl); 3032 3033 // Emit the iterations count variable. 3034 // If it is not a variable, Sema decided to calculate iterations count on each 3035 // iteration (e.g., it is foldable into a constant). 3036 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 3037 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 3038 // Emit calculation of the iterations count. 3039 EmitIgnoredExpr(S.getCalcLastIteration()); 3040 } 3041 3042 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 3043 3044 bool HasLastprivateClause; 3045 // Check pre-condition. 3046 { 3047 OMPLoopScope PreInitScope(*this, S); 3048 // Skip the entire loop if we don't meet the precondition. 3049 // If the condition constant folds and can be elided, avoid emitting the 3050 // whole loop. 3051 bool CondConstant; 3052 llvm::BasicBlock *ContBlock = nullptr; 3053 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 3054 if (!CondConstant) 3055 return false; 3056 } else { 3057 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then"); 3058 ContBlock = createBasicBlock("omp.precond.end"); 3059 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock, 3060 getProfileCount(&S)); 3061 EmitBlock(ThenBlock); 3062 incrementProfileCounter(&S); 3063 } 3064 3065 RunCleanupsScope DoacrossCleanupScope(*this); 3066 bool Ordered = false; 3067 if (const auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) { 3068 if (OrderedClause->getNumForLoops()) 3069 RT.emitDoacrossInit(*this, S, OrderedClause->getLoopNumIterations()); 3070 else 3071 Ordered = true; 3072 } 3073 3074 llvm::DenseSet<const Expr *> EmittedFinals; 3075 emitAlignedClause(*this, S); 3076 bool HasLinears = EmitOMPLinearClauseInit(S); 3077 // Emit helper vars inits. 3078 3079 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S); 3080 LValue LB = Bounds.first; 3081 LValue UB = Bounds.second; 3082 LValue ST = 3083 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable())); 3084 LValue IL = 3085 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable())); 3086 3087 // Emit 'then' code. 3088 { 3089 OMPPrivateScope LoopScope(*this); 3090 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) { 3091 // Emit implicit barrier to synchronize threads and avoid data races on 3092 // initialization of firstprivate variables and post-update of 3093 // lastprivate variables. 3094 CGM.getOpenMPRuntime().emitBarrierCall( 3095 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 3096 /*ForceSimpleCall=*/true); 3097 } 3098 EmitOMPPrivateClause(S, LoopScope); 3099 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion( 3100 *this, S, EmitLValue(S.getIterationVariable())); 3101 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope); 3102 EmitOMPReductionClauseInit(S, LoopScope); 3103 EmitOMPPrivateLoopCounters(S, LoopScope); 3104 EmitOMPLinearClause(S, LoopScope); 3105 (void)LoopScope.Privatize(); 3106 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 3107 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S); 3108 3109 // Detect the loop schedule kind and chunk. 3110 const Expr *ChunkExpr = nullptr; 3111 OpenMPScheduleTy ScheduleKind; 3112 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) { 3113 ScheduleKind.Schedule = C->getScheduleKind(); 3114 ScheduleKind.M1 = C->getFirstScheduleModifier(); 3115 ScheduleKind.M2 = C->getSecondScheduleModifier(); 3116 ChunkExpr = C->getChunkSize(); 3117 } else { 3118 // Default behaviour for schedule clause. 3119 CGM.getOpenMPRuntime().getDefaultScheduleAndChunk( 3120 *this, S, ScheduleKind.Schedule, ChunkExpr); 3121 } 3122 bool HasChunkSizeOne = false; 3123 llvm::Value *Chunk = nullptr; 3124 if (ChunkExpr) { 3125 Chunk = EmitScalarExpr(ChunkExpr); 3126 Chunk = EmitScalarConversion(Chunk, ChunkExpr->getType(), 3127 S.getIterationVariable()->getType(), 3128 S.getBeginLoc()); 3129 Expr::EvalResult Result; 3130 if (ChunkExpr->EvaluateAsInt(Result, getContext())) { 3131 llvm::APSInt EvaluatedChunk = Result.Val.getInt(); 3132 HasChunkSizeOne = (EvaluatedChunk.getLimitedValue() == 1); 3133 } 3134 } 3135 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 3136 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 3137 // OpenMP 4.5, 2.7.1 Loop Construct, Description. 3138 // If the static schedule kind is specified or if the ordered clause is 3139 // specified, and if no monotonic modifier is specified, the effect will 3140 // be as if the monotonic modifier was specified. 3141 bool StaticChunkedOne = RT.isStaticChunked(ScheduleKind.Schedule, 3142 /* Chunked */ Chunk != nullptr) && HasChunkSizeOne && 3143 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()); 3144 bool IsMonotonic = 3145 Ordered || 3146 ((ScheduleKind.Schedule == OMPC_SCHEDULE_static || 3147 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown) && 3148 !(ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 3149 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)) || 3150 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic || 3151 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic; 3152 if ((RT.isStaticNonchunked(ScheduleKind.Schedule, 3153 /* Chunked */ Chunk != nullptr) || 3154 StaticChunkedOne) && 3155 !Ordered) { 3156 JumpDest LoopExit = 3157 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit")); 3158 emitCommonSimdLoop( 3159 *this, S, 3160 [&S, IsMonotonic](CodeGenFunction &CGF, PrePostActionTy &) { 3161 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 3162 CGF.EmitOMPSimdInit(S, IsMonotonic); 3163 } else if (const auto *C = S.getSingleClause<OMPOrderClause>()) { 3164 if (C->getKind() == OMPC_ORDER_concurrent) 3165 CGF.LoopStack.setParallel(/*Enable=*/true); 3166 } 3167 }, 3168 [IVSize, IVSigned, Ordered, IL, LB, UB, ST, StaticChunkedOne, Chunk, 3169 &S, ScheduleKind, LoopExit, 3170 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) { 3171 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 3172 // When no chunk_size is specified, the iteration space is divided 3173 // into chunks that are approximately equal in size, and at most 3174 // one chunk is distributed to each thread. Note that the size of 3175 // the chunks is unspecified in this case. 3176 CGOpenMPRuntime::StaticRTInput StaticInit( 3177 IVSize, IVSigned, Ordered, IL.getAddress(CGF), 3178 LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF), 3179 StaticChunkedOne ? Chunk : nullptr); 3180 CGF.CGM.getOpenMPRuntime().emitForStaticInit( 3181 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, 3182 StaticInit); 3183 // UB = min(UB, GlobalUB); 3184 if (!StaticChunkedOne) 3185 CGF.EmitIgnoredExpr(S.getEnsureUpperBound()); 3186 // IV = LB; 3187 CGF.EmitIgnoredExpr(S.getInit()); 3188 // For unchunked static schedule generate: 3189 // 3190 // while (idx <= UB) { 3191 // BODY; 3192 // ++idx; 3193 // } 3194 // 3195 // For static schedule with chunk one: 3196 // 3197 // while (IV <= PrevUB) { 3198 // BODY; 3199 // IV += ST; 3200 // } 3201 CGF.EmitOMPInnerLoop( 3202 S, LoopScope.requiresCleanups(), 3203 StaticChunkedOne ? S.getCombinedParForInDistCond() 3204 : S.getCond(), 3205 StaticChunkedOne ? S.getDistInc() : S.getInc(), 3206 [&S, LoopExit](CodeGenFunction &CGF) { 3207 emitOMPLoopBodyWithStopPoint(CGF, S, LoopExit); 3208 }, 3209 [](CodeGenFunction &) {}); 3210 }); 3211 EmitBlock(LoopExit.getBlock()); 3212 // Tell the runtime we are done. 3213 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 3214 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(), 3215 S.getDirectiveKind()); 3216 }; 3217 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen); 3218 } else { 3219 // Emit the outer loop, which requests its work chunk [LB..UB] from 3220 // runtime and runs the inner loop to process it. 3221 const OMPLoopArguments LoopArguments( 3222 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this), 3223 IL.getAddress(*this), Chunk, EUB); 3224 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered, 3225 LoopArguments, CGDispatchBounds); 3226 } 3227 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 3228 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) { 3229 return CGF.Builder.CreateIsNotNull( 3230 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 3231 }); 3232 } 3233 EmitOMPReductionClauseFinal( 3234 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind()) 3235 ? /*Parallel and Simd*/ OMPD_parallel_for_simd 3236 : /*Parallel only*/ OMPD_parallel); 3237 // Emit post-update of the reduction variables if IsLastIter != 0. 3238 emitPostUpdateForReductionClause( 3239 *this, S, [IL, &S](CodeGenFunction &CGF) { 3240 return CGF.Builder.CreateIsNotNull( 3241 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 3242 }); 3243 // Emit final copy of the lastprivate variables if IsLastIter != 0. 3244 if (HasLastprivateClause) 3245 EmitOMPLastprivateClauseFinal( 3246 S, isOpenMPSimdDirective(S.getDirectiveKind()), 3247 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc()))); 3248 } 3249 EmitOMPLinearClauseFinal(S, [IL, &S](CodeGenFunction &CGF) { 3250 return CGF.Builder.CreateIsNotNull( 3251 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 3252 }); 3253 DoacrossCleanupScope.ForceCleanup(); 3254 // We're now done with the loop, so jump to the continuation block. 3255 if (ContBlock) { 3256 EmitBranch(ContBlock); 3257 EmitBlock(ContBlock, /*IsFinished=*/true); 3258 } 3259 } 3260 return HasLastprivateClause; 3261 } 3262 3263 /// The following two functions generate expressions for the loop lower 3264 /// and upper bounds in case of static and dynamic (dispatch) schedule 3265 /// of the associated 'for' or 'distribute' loop. 3266 static std::pair<LValue, LValue> 3267 emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) { 3268 const auto &LS = cast<OMPLoopDirective>(S); 3269 LValue LB = 3270 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable())); 3271 LValue UB = 3272 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable())); 3273 return {LB, UB}; 3274 } 3275 3276 /// When dealing with dispatch schedules (e.g. dynamic, guided) we do not 3277 /// consider the lower and upper bound expressions generated by the 3278 /// worksharing loop support, but we use 0 and the iteration space size as 3279 /// constants 3280 static std::pair<llvm::Value *, llvm::Value *> 3281 emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S, 3282 Address LB, Address UB) { 3283 const auto &LS = cast<OMPLoopDirective>(S); 3284 const Expr *IVExpr = LS.getIterationVariable(); 3285 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType()); 3286 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0); 3287 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration()); 3288 return {LBVal, UBVal}; 3289 } 3290 3291 /// Emits the code for the directive with inscan reductions. 3292 /// The code is the following: 3293 /// \code 3294 /// size num_iters = <num_iters>; 3295 /// <type> buffer[num_iters]; 3296 /// #pragma omp ... 3297 /// for (i: 0..<num_iters>) { 3298 /// <input phase>; 3299 /// buffer[i] = red; 3300 /// } 3301 /// for (int k = 0; k != ceil(log2(num_iters)); ++k) 3302 /// for (size cnt = last_iter; cnt >= pow(2, k); --k) 3303 /// buffer[i] op= buffer[i-pow(2,k)]; 3304 /// #pragma omp ... 3305 /// for (0..<num_iters>) { 3306 /// red = InclusiveScan ? buffer[i] : buffer[i-1]; 3307 /// <scan phase>; 3308 /// } 3309 /// \endcode 3310 static void emitScanBasedDirective( 3311 CodeGenFunction &CGF, const OMPLoopDirective &S, 3312 llvm::function_ref<llvm::Value *(CodeGenFunction &)> NumIteratorsGen, 3313 llvm::function_ref<void(CodeGenFunction &)> FirstGen, 3314 llvm::function_ref<void(CodeGenFunction &)> SecondGen) { 3315 llvm::Value *OMPScanNumIterations = CGF.Builder.CreateIntCast( 3316 NumIteratorsGen(CGF), CGF.SizeTy, /*isSigned=*/false); 3317 SmallVector<const Expr *, 4> Shareds; 3318 SmallVector<const Expr *, 4> Privates; 3319 SmallVector<const Expr *, 4> ReductionOps; 3320 SmallVector<const Expr *, 4> LHSs; 3321 SmallVector<const Expr *, 4> RHSs; 3322 SmallVector<const Expr *, 4> CopyOps; 3323 SmallVector<const Expr *, 4> CopyArrayTemps; 3324 SmallVector<const Expr *, 4> CopyArrayElems; 3325 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) { 3326 assert(C->getModifier() == OMPC_REDUCTION_inscan && 3327 "Only inscan reductions are expected."); 3328 Shareds.append(C->varlist_begin(), C->varlist_end()); 3329 Privates.append(C->privates().begin(), C->privates().end()); 3330 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end()); 3331 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 3332 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 3333 CopyOps.append(C->copy_ops().begin(), C->copy_ops().end()); 3334 CopyArrayTemps.append(C->copy_array_temps().begin(), 3335 C->copy_array_temps().end()); 3336 CopyArrayElems.append(C->copy_array_elems().begin(), 3337 C->copy_array_elems().end()); 3338 } 3339 { 3340 // Emit buffers for each reduction variables. 3341 // ReductionCodeGen is required to emit correctly the code for array 3342 // reductions. 3343 ReductionCodeGen RedCG(Shareds, Shareds, Privates, ReductionOps); 3344 unsigned Count = 0; 3345 auto *ITA = CopyArrayTemps.begin(); 3346 for (const Expr *IRef : Privates) { 3347 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl()); 3348 // Emit variably modified arrays, used for arrays/array sections 3349 // reductions. 3350 if (PrivateVD->getType()->isVariablyModifiedType()) { 3351 RedCG.emitSharedOrigLValue(CGF, Count); 3352 RedCG.emitAggregateType(CGF, Count); 3353 } 3354 CodeGenFunction::OpaqueValueMapping DimMapping( 3355 CGF, 3356 cast<OpaqueValueExpr>( 3357 cast<VariableArrayType>((*ITA)->getType()->getAsArrayTypeUnsafe()) 3358 ->getSizeExpr()), 3359 RValue::get(OMPScanNumIterations)); 3360 // Emit temp buffer. 3361 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(*ITA)->getDecl())); 3362 ++ITA; 3363 ++Count; 3364 } 3365 } 3366 CodeGenFunction::ParentLoopDirectiveForScanRegion ScanRegion(CGF, S); 3367 { 3368 // Emit loop with input phase: 3369 // #pragma omp ... 3370 // for (i: 0..<num_iters>) { 3371 // <input phase>; 3372 // buffer[i] = red; 3373 // } 3374 CGF.OMPFirstScanLoop = true; 3375 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF); 3376 FirstGen(CGF); 3377 } 3378 // Emit prefix reduction: 3379 // for (int k = 0; k <= ceil(log2(n)); ++k) 3380 llvm::BasicBlock *InputBB = CGF.Builder.GetInsertBlock(); 3381 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.outer.log.scan.body"); 3382 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.outer.log.scan.exit"); 3383 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::log2, CGF.DoubleTy); 3384 llvm::Value *Arg = 3385 CGF.Builder.CreateUIToFP(OMPScanNumIterations, CGF.DoubleTy); 3386 llvm::Value *LogVal = CGF.EmitNounwindRuntimeCall(F, Arg); 3387 F = CGF.CGM.getIntrinsic(llvm::Intrinsic::ceil, CGF.DoubleTy); 3388 LogVal = CGF.EmitNounwindRuntimeCall(F, LogVal); 3389 LogVal = CGF.Builder.CreateFPToUI(LogVal, CGF.IntTy); 3390 llvm::Value *NMin1 = CGF.Builder.CreateNUWSub( 3391 OMPScanNumIterations, llvm::ConstantInt::get(CGF.SizeTy, 1)); 3392 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, S.getBeginLoc()); 3393 CGF.EmitBlock(LoopBB); 3394 auto *Counter = CGF.Builder.CreatePHI(CGF.IntTy, 2); 3395 // size pow2k = 1; 3396 auto *Pow2K = CGF.Builder.CreatePHI(CGF.SizeTy, 2); 3397 Counter->addIncoming(llvm::ConstantInt::get(CGF.IntTy, 0), InputBB); 3398 Pow2K->addIncoming(llvm::ConstantInt::get(CGF.SizeTy, 1), InputBB); 3399 // for (size i = n - 1; i >= 2 ^ k; --i) 3400 // tmp[i] op= tmp[i-pow2k]; 3401 llvm::BasicBlock *InnerLoopBB = 3402 CGF.createBasicBlock("omp.inner.log.scan.body"); 3403 llvm::BasicBlock *InnerExitBB = 3404 CGF.createBasicBlock("omp.inner.log.scan.exit"); 3405 llvm::Value *CmpI = CGF.Builder.CreateICmpUGE(NMin1, Pow2K); 3406 CGF.Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB); 3407 CGF.EmitBlock(InnerLoopBB); 3408 auto *IVal = CGF.Builder.CreatePHI(CGF.SizeTy, 2); 3409 IVal->addIncoming(NMin1, LoopBB); 3410 { 3411 CodeGenFunction::OMPPrivateScope PrivScope(CGF); 3412 auto *ILHS = LHSs.begin(); 3413 auto *IRHS = RHSs.begin(); 3414 for (const Expr *CopyArrayElem : CopyArrayElems) { 3415 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl()); 3416 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl()); 3417 Address LHSAddr = Address::invalid(); 3418 { 3419 CodeGenFunction::OpaqueValueMapping IdxMapping( 3420 CGF, 3421 cast<OpaqueValueExpr>( 3422 cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()), 3423 RValue::get(IVal)); 3424 LHSAddr = CGF.EmitLValue(CopyArrayElem).getAddress(CGF); 3425 } 3426 PrivScope.addPrivate(LHSVD, [LHSAddr]() { return LHSAddr; }); 3427 Address RHSAddr = Address::invalid(); 3428 { 3429 llvm::Value *OffsetIVal = CGF.Builder.CreateNUWSub(IVal, Pow2K); 3430 CodeGenFunction::OpaqueValueMapping IdxMapping( 3431 CGF, 3432 cast<OpaqueValueExpr>( 3433 cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()), 3434 RValue::get(OffsetIVal)); 3435 RHSAddr = CGF.EmitLValue(CopyArrayElem).getAddress(CGF); 3436 } 3437 PrivScope.addPrivate(RHSVD, [RHSAddr]() { return RHSAddr; }); 3438 ++ILHS; 3439 ++IRHS; 3440 } 3441 PrivScope.Privatize(); 3442 CGF.CGM.getOpenMPRuntime().emitReduction( 3443 CGF, S.getEndLoc(), Privates, LHSs, RHSs, ReductionOps, 3444 {/*WithNowait=*/true, /*SimpleReduction=*/true, OMPD_unknown}); 3445 } 3446 llvm::Value *NextIVal = 3447 CGF.Builder.CreateNUWSub(IVal, llvm::ConstantInt::get(CGF.SizeTy, 1)); 3448 IVal->addIncoming(NextIVal, CGF.Builder.GetInsertBlock()); 3449 CmpI = CGF.Builder.CreateICmpUGE(NextIVal, Pow2K); 3450 CGF.Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB); 3451 CGF.EmitBlock(InnerExitBB); 3452 llvm::Value *Next = 3453 CGF.Builder.CreateNUWAdd(Counter, llvm::ConstantInt::get(CGF.IntTy, 1)); 3454 Counter->addIncoming(Next, CGF.Builder.GetInsertBlock()); 3455 // pow2k <<= 1; 3456 llvm::Value *NextPow2K = CGF.Builder.CreateShl(Pow2K, 1, "", /*HasNUW=*/true); 3457 Pow2K->addIncoming(NextPow2K, CGF.Builder.GetInsertBlock()); 3458 llvm::Value *Cmp = CGF.Builder.CreateICmpNE(Next, LogVal); 3459 CGF.Builder.CreateCondBr(Cmp, LoopBB, ExitBB); 3460 auto DL1 = ApplyDebugLocation::CreateDefaultArtificial(CGF, S.getEndLoc()); 3461 CGF.EmitBlock(ExitBB); 3462 3463 CGF.OMPFirstScanLoop = false; 3464 SecondGen(CGF); 3465 } 3466 3467 static bool emitWorksharingDirective(CodeGenFunction &CGF, 3468 const OMPLoopDirective &S, 3469 bool HasCancel) { 3470 bool HasLastprivates; 3471 if (llvm::any_of(S.getClausesOfKind<OMPReductionClause>(), 3472 [](const OMPReductionClause *C) { 3473 return C->getModifier() == OMPC_REDUCTION_inscan; 3474 })) { 3475 const auto &&NumIteratorsGen = [&S](CodeGenFunction &CGF) { 3476 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF); 3477 OMPLoopScope LoopScope(CGF, S); 3478 return CGF.EmitScalarExpr(S.getNumIterations()); 3479 }; 3480 const auto &&FirstGen = [&S, HasCancel](CodeGenFunction &CGF) { 3481 CodeGenFunction::OMPCancelStackRAII CancelRegion( 3482 CGF, S.getDirectiveKind(), HasCancel); 3483 (void)CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), 3484 emitForLoopBounds, 3485 emitDispatchForLoopBounds); 3486 // Emit an implicit barrier at the end. 3487 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getBeginLoc(), 3488 OMPD_for); 3489 }; 3490 const auto &&SecondGen = [&S, HasCancel, 3491 &HasLastprivates](CodeGenFunction &CGF) { 3492 CodeGenFunction::OMPCancelStackRAII CancelRegion( 3493 CGF, S.getDirectiveKind(), HasCancel); 3494 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), 3495 emitForLoopBounds, 3496 emitDispatchForLoopBounds); 3497 }; 3498 emitScanBasedDirective(CGF, S, NumIteratorsGen, FirstGen, SecondGen); 3499 } else { 3500 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(), 3501 HasCancel); 3502 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), 3503 emitForLoopBounds, 3504 emitDispatchForLoopBounds); 3505 } 3506 return HasLastprivates; 3507 } 3508 3509 static bool isSupportedByOpenMPIRBuilder(const OMPForDirective &S) { 3510 if (S.hasCancel()) 3511 return false; 3512 for (OMPClause *C : S.clauses()) 3513 if (!isa<OMPNowaitClause>(C)) 3514 return false; 3515 3516 return true; 3517 } 3518 3519 void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) { 3520 bool HasLastprivates = false; 3521 bool UseOMPIRBuilder = 3522 CGM.getLangOpts().OpenMPIRBuilder && isSupportedByOpenMPIRBuilder(S); 3523 auto &&CodeGen = [this, &S, &HasLastprivates, 3524 UseOMPIRBuilder](CodeGenFunction &CGF, PrePostActionTy &) { 3525 // Use the OpenMPIRBuilder if enabled. 3526 if (UseOMPIRBuilder) { 3527 // Emit the associated statement and get its loop representation. 3528 const Stmt *Inner = S.getRawStmt(); 3529 llvm::CanonicalLoopInfo *CLI = 3530 EmitOMPCollapsedCanonicalLoopNest(Inner, 1); 3531 3532 bool NeedsBarrier = !S.getSingleClause<OMPNowaitClause>(); 3533 llvm::OpenMPIRBuilder &OMPBuilder = 3534 CGM.getOpenMPRuntime().getOMPBuilder(); 3535 llvm::OpenMPIRBuilder::InsertPointTy AllocaIP( 3536 AllocaInsertPt->getParent(), AllocaInsertPt->getIterator()); 3537 OMPBuilder.createWorkshareLoop(Builder, CLI, AllocaIP, NeedsBarrier); 3538 return; 3539 } 3540 3541 HasLastprivates = emitWorksharingDirective(CGF, S, S.hasCancel()); 3542 }; 3543 { 3544 auto LPCRegion = 3545 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3546 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3547 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen, 3548 S.hasCancel()); 3549 } 3550 3551 if (!UseOMPIRBuilder) { 3552 // Emit an implicit barrier at the end. 3553 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) 3554 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for); 3555 } 3556 // Check for outer lastprivate conditional update. 3557 checkForLastprivateConditionalUpdate(*this, S); 3558 } 3559 3560 void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) { 3561 bool HasLastprivates = false; 3562 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF, 3563 PrePostActionTy &) { 3564 HasLastprivates = emitWorksharingDirective(CGF, S, /*HasCancel=*/false); 3565 }; 3566 { 3567 auto LPCRegion = 3568 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3569 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3570 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen); 3571 } 3572 3573 // Emit an implicit barrier at the end. 3574 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) 3575 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for); 3576 // Check for outer lastprivate conditional update. 3577 checkForLastprivateConditionalUpdate(*this, S); 3578 } 3579 3580 static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty, 3581 const Twine &Name, 3582 llvm::Value *Init = nullptr) { 3583 LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty); 3584 if (Init) 3585 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true); 3586 return LVal; 3587 } 3588 3589 void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) { 3590 const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt(); 3591 const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt); 3592 bool HasLastprivates = false; 3593 auto &&CodeGen = [&S, CapturedStmt, CS, 3594 &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) { 3595 const ASTContext &C = CGF.getContext(); 3596 QualType KmpInt32Ty = 3597 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 3598 // Emit helper vars inits. 3599 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.", 3600 CGF.Builder.getInt32(0)); 3601 llvm::ConstantInt *GlobalUBVal = CS != nullptr 3602 ? CGF.Builder.getInt32(CS->size() - 1) 3603 : CGF.Builder.getInt32(0); 3604 LValue UB = 3605 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal); 3606 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.", 3607 CGF.Builder.getInt32(1)); 3608 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.", 3609 CGF.Builder.getInt32(0)); 3610 // Loop counter. 3611 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv."); 3612 OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue); 3613 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV); 3614 OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue); 3615 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB); 3616 // Generate condition for loop. 3617 BinaryOperator *Cond = BinaryOperator::Create( 3618 C, &IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue, OK_Ordinary, 3619 S.getBeginLoc(), FPOptionsOverride()); 3620 // Increment for loop counter. 3621 UnaryOperator *Inc = UnaryOperator::Create( 3622 C, &IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary, 3623 S.getBeginLoc(), true, FPOptionsOverride()); 3624 auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) { 3625 // Iterate through all sections and emit a switch construct: 3626 // switch (IV) { 3627 // case 0: 3628 // <SectionStmt[0]>; 3629 // break; 3630 // ... 3631 // case <NumSection> - 1: 3632 // <SectionStmt[<NumSection> - 1]>; 3633 // break; 3634 // } 3635 // .omp.sections.exit: 3636 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit"); 3637 llvm::SwitchInst *SwitchStmt = 3638 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()), 3639 ExitBB, CS == nullptr ? 1 : CS->size()); 3640 if (CS) { 3641 unsigned CaseNumber = 0; 3642 for (const Stmt *SubStmt : CS->children()) { 3643 auto CaseBB = CGF.createBasicBlock(".omp.sections.case"); 3644 CGF.EmitBlock(CaseBB); 3645 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB); 3646 CGF.EmitStmt(SubStmt); 3647 CGF.EmitBranch(ExitBB); 3648 ++CaseNumber; 3649 } 3650 } else { 3651 llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case"); 3652 CGF.EmitBlock(CaseBB); 3653 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB); 3654 CGF.EmitStmt(CapturedStmt); 3655 CGF.EmitBranch(ExitBB); 3656 } 3657 CGF.EmitBlock(ExitBB, /*IsFinished=*/true); 3658 }; 3659 3660 CodeGenFunction::OMPPrivateScope LoopScope(CGF); 3661 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) { 3662 // Emit implicit barrier to synchronize threads and avoid data races on 3663 // initialization of firstprivate variables and post-update of lastprivate 3664 // variables. 3665 CGF.CGM.getOpenMPRuntime().emitBarrierCall( 3666 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 3667 /*ForceSimpleCall=*/true); 3668 } 3669 CGF.EmitOMPPrivateClause(S, LoopScope); 3670 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(CGF, S, IV); 3671 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 3672 CGF.EmitOMPReductionClauseInit(S, LoopScope); 3673 (void)LoopScope.Privatize(); 3674 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 3675 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 3676 3677 // Emit static non-chunked loop. 3678 OpenMPScheduleTy ScheduleKind; 3679 ScheduleKind.Schedule = OMPC_SCHEDULE_static; 3680 CGOpenMPRuntime::StaticRTInput StaticInit( 3681 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(CGF), 3682 LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF)); 3683 CGF.CGM.getOpenMPRuntime().emitForStaticInit( 3684 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, StaticInit); 3685 // UB = min(UB, GlobalUB); 3686 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc()); 3687 llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect( 3688 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal); 3689 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB); 3690 // IV = LB; 3691 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV); 3692 // while (idx <= UB) { BODY; ++idx; } 3693 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, Cond, Inc, BodyGen, 3694 [](CodeGenFunction &) {}); 3695 // Tell the runtime we are done. 3696 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 3697 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(), 3698 S.getDirectiveKind()); 3699 }; 3700 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen); 3701 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 3702 // Emit post-update of the reduction variables if IsLastIter != 0. 3703 emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) { 3704 return CGF.Builder.CreateIsNotNull( 3705 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 3706 }); 3707 3708 // Emit final copy of the lastprivate variables if IsLastIter != 0. 3709 if (HasLastprivates) 3710 CGF.EmitOMPLastprivateClauseFinal( 3711 S, /*NoFinals=*/false, 3712 CGF.Builder.CreateIsNotNull( 3713 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()))); 3714 }; 3715 3716 bool HasCancel = false; 3717 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S)) 3718 HasCancel = OSD->hasCancel(); 3719 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S)) 3720 HasCancel = OPSD->hasCancel(); 3721 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel); 3722 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen, 3723 HasCancel); 3724 // Emit barrier for lastprivates only if 'sections' directive has 'nowait' 3725 // clause. Otherwise the barrier will be generated by the codegen for the 3726 // directive. 3727 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) { 3728 // Emit implicit barrier to synchronize threads and avoid data races on 3729 // initialization of firstprivate variables. 3730 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), 3731 OMPD_unknown); 3732 } 3733 } 3734 3735 void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) { 3736 { 3737 auto LPCRegion = 3738 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3739 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3740 EmitSections(S); 3741 } 3742 // Emit an implicit barrier at the end. 3743 if (!S.getSingleClause<OMPNowaitClause>()) { 3744 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), 3745 OMPD_sections); 3746 } 3747 // Check for outer lastprivate conditional update. 3748 checkForLastprivateConditionalUpdate(*this, S); 3749 } 3750 3751 void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) { 3752 LexicalScope Scope(*this, S.getSourceRange()); 3753 EmitStopPoint(&S); 3754 EmitStmt(S.getAssociatedStmt()); 3755 } 3756 3757 void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) { 3758 llvm::SmallVector<const Expr *, 8> CopyprivateVars; 3759 llvm::SmallVector<const Expr *, 8> DestExprs; 3760 llvm::SmallVector<const Expr *, 8> SrcExprs; 3761 llvm::SmallVector<const Expr *, 8> AssignmentOps; 3762 // Check if there are any 'copyprivate' clauses associated with this 3763 // 'single' construct. 3764 // Build a list of copyprivate variables along with helper expressions 3765 // (<source>, <destination>, <destination>=<source> expressions) 3766 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) { 3767 CopyprivateVars.append(C->varlists().begin(), C->varlists().end()); 3768 DestExprs.append(C->destination_exprs().begin(), 3769 C->destination_exprs().end()); 3770 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end()); 3771 AssignmentOps.append(C->assignment_ops().begin(), 3772 C->assignment_ops().end()); 3773 } 3774 // Emit code for 'single' region along with 'copyprivate' clauses 3775 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3776 Action.Enter(CGF); 3777 OMPPrivateScope SingleScope(CGF); 3778 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope); 3779 CGF.EmitOMPPrivateClause(S, SingleScope); 3780 (void)SingleScope.Privatize(); 3781 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 3782 }; 3783 { 3784 auto LPCRegion = 3785 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3786 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3787 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(), 3788 CopyprivateVars, DestExprs, 3789 SrcExprs, AssignmentOps); 3790 } 3791 // Emit an implicit barrier at the end (to avoid data race on firstprivate 3792 // init or if no 'nowait' clause was specified and no 'copyprivate' clause). 3793 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) { 3794 CGM.getOpenMPRuntime().emitBarrierCall( 3795 *this, S.getBeginLoc(), 3796 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single); 3797 } 3798 // Check for outer lastprivate conditional update. 3799 checkForLastprivateConditionalUpdate(*this, S); 3800 } 3801 3802 static void emitMaster(CodeGenFunction &CGF, const OMPExecutableDirective &S) { 3803 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3804 Action.Enter(CGF); 3805 CGF.EmitStmt(S.getRawStmt()); 3806 }; 3807 CGF.CGM.getOpenMPRuntime().emitMasterRegion(CGF, CodeGen, S.getBeginLoc()); 3808 } 3809 3810 void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) { 3811 if (CGM.getLangOpts().OpenMPIRBuilder) { 3812 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 3813 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 3814 3815 const Stmt *MasterRegionBodyStmt = S.getAssociatedStmt(); 3816 3817 auto FiniCB = [this](InsertPointTy IP) { 3818 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP); 3819 }; 3820 3821 auto BodyGenCB = [MasterRegionBodyStmt, this](InsertPointTy AllocaIP, 3822 InsertPointTy CodeGenIP, 3823 llvm::BasicBlock &FiniBB) { 3824 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB); 3825 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, MasterRegionBodyStmt, 3826 CodeGenIP, FiniBB); 3827 }; 3828 3829 LexicalScope Scope(*this, S.getSourceRange()); 3830 EmitStopPoint(&S); 3831 Builder.restoreIP(OMPBuilder.createMaster(Builder, BodyGenCB, FiniCB)); 3832 3833 return; 3834 } 3835 LexicalScope Scope(*this, S.getSourceRange()); 3836 EmitStopPoint(&S); 3837 emitMaster(*this, S); 3838 } 3839 3840 void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) { 3841 if (CGM.getLangOpts().OpenMPIRBuilder) { 3842 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 3843 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 3844 3845 const Stmt *CriticalRegionBodyStmt = S.getAssociatedStmt(); 3846 const Expr *Hint = nullptr; 3847 if (const auto *HintClause = S.getSingleClause<OMPHintClause>()) 3848 Hint = HintClause->getHint(); 3849 3850 // TODO: This is slightly different from what's currently being done in 3851 // clang. Fix the Int32Ty to IntPtrTy (pointer width size) when everything 3852 // about typing is final. 3853 llvm::Value *HintInst = nullptr; 3854 if (Hint) 3855 HintInst = 3856 Builder.CreateIntCast(EmitScalarExpr(Hint), CGM.Int32Ty, false); 3857 3858 auto FiniCB = [this](InsertPointTy IP) { 3859 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP); 3860 }; 3861 3862 auto BodyGenCB = [CriticalRegionBodyStmt, this](InsertPointTy AllocaIP, 3863 InsertPointTy CodeGenIP, 3864 llvm::BasicBlock &FiniBB) { 3865 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB); 3866 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, CriticalRegionBodyStmt, 3867 CodeGenIP, FiniBB); 3868 }; 3869 3870 LexicalScope Scope(*this, S.getSourceRange()); 3871 EmitStopPoint(&S); 3872 Builder.restoreIP(OMPBuilder.createCritical( 3873 Builder, BodyGenCB, FiniCB, S.getDirectiveName().getAsString(), 3874 HintInst)); 3875 3876 return; 3877 } 3878 3879 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3880 Action.Enter(CGF); 3881 CGF.EmitStmt(S.getAssociatedStmt()); 3882 }; 3883 const Expr *Hint = nullptr; 3884 if (const auto *HintClause = S.getSingleClause<OMPHintClause>()) 3885 Hint = HintClause->getHint(); 3886 LexicalScope Scope(*this, S.getSourceRange()); 3887 EmitStopPoint(&S); 3888 CGM.getOpenMPRuntime().emitCriticalRegion(*this, 3889 S.getDirectiveName().getAsString(), 3890 CodeGen, S.getBeginLoc(), Hint); 3891 } 3892 3893 void CodeGenFunction::EmitOMPParallelForDirective( 3894 const OMPParallelForDirective &S) { 3895 // Emit directive as a combined directive that consists of two implicit 3896 // directives: 'parallel' with 'for' directive. 3897 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3898 Action.Enter(CGF); 3899 (void)emitWorksharingDirective(CGF, S, S.hasCancel()); 3900 }; 3901 { 3902 auto LPCRegion = 3903 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3904 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen, 3905 emitEmptyBoundParameters); 3906 } 3907 // Check for outer lastprivate conditional update. 3908 checkForLastprivateConditionalUpdate(*this, S); 3909 } 3910 3911 void CodeGenFunction::EmitOMPParallelForSimdDirective( 3912 const OMPParallelForSimdDirective &S) { 3913 // Emit directive as a combined directive that consists of two implicit 3914 // directives: 'parallel' with 'for' directive. 3915 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3916 Action.Enter(CGF); 3917 (void)emitWorksharingDirective(CGF, S, /*HasCancel=*/false); 3918 }; 3919 { 3920 auto LPCRegion = 3921 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3922 emitCommonOMPParallelDirective(*this, S, OMPD_for_simd, CodeGen, 3923 emitEmptyBoundParameters); 3924 } 3925 // Check for outer lastprivate conditional update. 3926 checkForLastprivateConditionalUpdate(*this, S); 3927 } 3928 3929 void CodeGenFunction::EmitOMPParallelMasterDirective( 3930 const OMPParallelMasterDirective &S) { 3931 // Emit directive as a combined directive that consists of two implicit 3932 // directives: 'parallel' with 'master' directive. 3933 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3934 Action.Enter(CGF); 3935 OMPPrivateScope PrivateScope(CGF); 3936 bool Copyins = CGF.EmitOMPCopyinClause(S); 3937 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 3938 if (Copyins) { 3939 // Emit implicit barrier to synchronize threads and avoid data races on 3940 // propagation master's thread values of threadprivate variables to local 3941 // instances of that variables of all other implicit threads. 3942 CGF.CGM.getOpenMPRuntime().emitBarrierCall( 3943 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 3944 /*ForceSimpleCall=*/true); 3945 } 3946 CGF.EmitOMPPrivateClause(S, PrivateScope); 3947 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 3948 (void)PrivateScope.Privatize(); 3949 emitMaster(CGF, S); 3950 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 3951 }; 3952 { 3953 auto LPCRegion = 3954 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3955 emitCommonOMPParallelDirective(*this, S, OMPD_master, CodeGen, 3956 emitEmptyBoundParameters); 3957 emitPostUpdateForReductionClause(*this, S, 3958 [](CodeGenFunction &) { return nullptr; }); 3959 } 3960 // Check for outer lastprivate conditional update. 3961 checkForLastprivateConditionalUpdate(*this, S); 3962 } 3963 3964 void CodeGenFunction::EmitOMPParallelSectionsDirective( 3965 const OMPParallelSectionsDirective &S) { 3966 // Emit directive as a combined directive that consists of two implicit 3967 // directives: 'parallel' with 'sections' directive. 3968 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3969 Action.Enter(CGF); 3970 CGF.EmitSections(S); 3971 }; 3972 { 3973 auto LPCRegion = 3974 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3975 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen, 3976 emitEmptyBoundParameters); 3977 } 3978 // Check for outer lastprivate conditional update. 3979 checkForLastprivateConditionalUpdate(*this, S); 3980 } 3981 3982 namespace { 3983 /// Get the list of variables declared in the context of the untied tasks. 3984 class CheckVarsEscapingUntiedTaskDeclContext final 3985 : public ConstStmtVisitor<CheckVarsEscapingUntiedTaskDeclContext> { 3986 llvm::SmallVector<const VarDecl *, 4> PrivateDecls; 3987 3988 public: 3989 explicit CheckVarsEscapingUntiedTaskDeclContext() = default; 3990 virtual ~CheckVarsEscapingUntiedTaskDeclContext() = default; 3991 void VisitDeclStmt(const DeclStmt *S) { 3992 if (!S) 3993 return; 3994 // Need to privatize only local vars, static locals can be processed as is. 3995 for (const Decl *D : S->decls()) { 3996 if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) 3997 if (VD->hasLocalStorage()) 3998 PrivateDecls.push_back(VD); 3999 } 4000 } 4001 void VisitOMPExecutableDirective(const OMPExecutableDirective *) { return; } 4002 void VisitCapturedStmt(const CapturedStmt *) { return; } 4003 void VisitLambdaExpr(const LambdaExpr *) { return; } 4004 void VisitBlockExpr(const BlockExpr *) { return; } 4005 void VisitStmt(const Stmt *S) { 4006 if (!S) 4007 return; 4008 for (const Stmt *Child : S->children()) 4009 if (Child) 4010 Visit(Child); 4011 } 4012 4013 /// Swaps list of vars with the provided one. 4014 ArrayRef<const VarDecl *> getPrivateDecls() const { return PrivateDecls; } 4015 }; 4016 } // anonymous namespace 4017 4018 void CodeGenFunction::EmitOMPTaskBasedDirective( 4019 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion, 4020 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen, 4021 OMPTaskDataTy &Data) { 4022 // Emit outlined function for task construct. 4023 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion); 4024 auto I = CS->getCapturedDecl()->param_begin(); 4025 auto PartId = std::next(I); 4026 auto TaskT = std::next(I, 4); 4027 // Check if the task is final 4028 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) { 4029 // If the condition constant folds and can be elided, try to avoid emitting 4030 // the condition and the dead arm of the if/else. 4031 const Expr *Cond = Clause->getCondition(); 4032 bool CondConstant; 4033 if (ConstantFoldsToSimpleInteger(Cond, CondConstant)) 4034 Data.Final.setInt(CondConstant); 4035 else 4036 Data.Final.setPointer(EvaluateExprAsBool(Cond)); 4037 } else { 4038 // By default the task is not final. 4039 Data.Final.setInt(/*IntVal=*/false); 4040 } 4041 // Check if the task has 'priority' clause. 4042 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) { 4043 const Expr *Prio = Clause->getPriority(); 4044 Data.Priority.setInt(/*IntVal=*/true); 4045 Data.Priority.setPointer(EmitScalarConversion( 4046 EmitScalarExpr(Prio), Prio->getType(), 4047 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1), 4048 Prio->getExprLoc())); 4049 } 4050 // The first function argument for tasks is a thread id, the second one is a 4051 // part id (0 for tied tasks, >=0 for untied task). 4052 llvm::DenseSet<const VarDecl *> EmittedAsPrivate; 4053 // Get list of private variables. 4054 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) { 4055 auto IRef = C->varlist_begin(); 4056 for (const Expr *IInit : C->private_copies()) { 4057 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 4058 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 4059 Data.PrivateVars.push_back(*IRef); 4060 Data.PrivateCopies.push_back(IInit); 4061 } 4062 ++IRef; 4063 } 4064 } 4065 EmittedAsPrivate.clear(); 4066 // Get list of firstprivate variables. 4067 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) { 4068 auto IRef = C->varlist_begin(); 4069 auto IElemInitRef = C->inits().begin(); 4070 for (const Expr *IInit : C->private_copies()) { 4071 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 4072 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 4073 Data.FirstprivateVars.push_back(*IRef); 4074 Data.FirstprivateCopies.push_back(IInit); 4075 Data.FirstprivateInits.push_back(*IElemInitRef); 4076 } 4077 ++IRef; 4078 ++IElemInitRef; 4079 } 4080 } 4081 // Get list of lastprivate variables (for taskloops). 4082 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs; 4083 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) { 4084 auto IRef = C->varlist_begin(); 4085 auto ID = C->destination_exprs().begin(); 4086 for (const Expr *IInit : C->private_copies()) { 4087 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 4088 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 4089 Data.LastprivateVars.push_back(*IRef); 4090 Data.LastprivateCopies.push_back(IInit); 4091 } 4092 LastprivateDstsOrigs.insert( 4093 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()), 4094 cast<DeclRefExpr>(*IRef)}); 4095 ++IRef; 4096 ++ID; 4097 } 4098 } 4099 SmallVector<const Expr *, 4> LHSs; 4100 SmallVector<const Expr *, 4> RHSs; 4101 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) { 4102 Data.ReductionVars.append(C->varlist_begin(), C->varlist_end()); 4103 Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end()); 4104 Data.ReductionCopies.append(C->privates().begin(), C->privates().end()); 4105 Data.ReductionOps.append(C->reduction_ops().begin(), 4106 C->reduction_ops().end()); 4107 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 4108 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 4109 } 4110 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit( 4111 *this, S.getBeginLoc(), LHSs, RHSs, Data); 4112 // Build list of dependences. 4113 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) { 4114 OMPTaskDataTy::DependData &DD = 4115 Data.Dependences.emplace_back(C->getDependencyKind(), C->getModifier()); 4116 DD.DepExprs.append(C->varlist_begin(), C->varlist_end()); 4117 } 4118 // Get list of local vars for untied tasks. 4119 if (!Data.Tied) { 4120 CheckVarsEscapingUntiedTaskDeclContext Checker; 4121 Checker.Visit(S.getInnermostCapturedStmt()->getCapturedStmt()); 4122 Data.PrivateLocals.append(Checker.getPrivateDecls().begin(), 4123 Checker.getPrivateDecls().end()); 4124 } 4125 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs, 4126 CapturedRegion](CodeGenFunction &CGF, 4127 PrePostActionTy &Action) { 4128 llvm::DenseMap<CanonicalDeclPtr<const VarDecl>, std::pair<Address, Address>> 4129 UntiedLocalVars; 4130 // Set proper addresses for generated private copies. 4131 OMPPrivateScope Scope(CGF); 4132 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> FirstprivatePtrs; 4133 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() || 4134 !Data.LastprivateVars.empty() || !Data.PrivateLocals.empty()) { 4135 llvm::FunctionType *CopyFnTy = llvm::FunctionType::get( 4136 CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true); 4137 enum { PrivatesParam = 2, CopyFnParam = 3 }; 4138 llvm::Value *CopyFn = CGF.Builder.CreateLoad( 4139 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam))); 4140 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar( 4141 CS->getCapturedDecl()->getParam(PrivatesParam))); 4142 // Map privates. 4143 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs; 4144 llvm::SmallVector<llvm::Value *, 16> CallArgs; 4145 CallArgs.push_back(PrivatesPtr); 4146 for (const Expr *E : Data.PrivateVars) { 4147 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4148 Address PrivatePtr = CGF.CreateMemTemp( 4149 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr"); 4150 PrivatePtrs.emplace_back(VD, PrivatePtr); 4151 CallArgs.push_back(PrivatePtr.getPointer()); 4152 } 4153 for (const Expr *E : Data.FirstprivateVars) { 4154 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4155 Address PrivatePtr = 4156 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()), 4157 ".firstpriv.ptr.addr"); 4158 PrivatePtrs.emplace_back(VD, PrivatePtr); 4159 FirstprivatePtrs.emplace_back(VD, PrivatePtr); 4160 CallArgs.push_back(PrivatePtr.getPointer()); 4161 } 4162 for (const Expr *E : Data.LastprivateVars) { 4163 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4164 Address PrivatePtr = 4165 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()), 4166 ".lastpriv.ptr.addr"); 4167 PrivatePtrs.emplace_back(VD, PrivatePtr); 4168 CallArgs.push_back(PrivatePtr.getPointer()); 4169 } 4170 for (const VarDecl *VD : Data.PrivateLocals) { 4171 QualType Ty = VD->getType().getNonReferenceType(); 4172 if (VD->getType()->isLValueReferenceType()) 4173 Ty = CGF.getContext().getPointerType(Ty); 4174 if (isAllocatableDecl(VD)) 4175 Ty = CGF.getContext().getPointerType(Ty); 4176 Address PrivatePtr = CGF.CreateMemTemp( 4177 CGF.getContext().getPointerType(Ty), ".local.ptr.addr"); 4178 UntiedLocalVars.try_emplace(VD, PrivatePtr, Address::invalid()); 4179 CallArgs.push_back(PrivatePtr.getPointer()); 4180 } 4181 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall( 4182 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs); 4183 for (const auto &Pair : LastprivateDstsOrigs) { 4184 const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl()); 4185 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(OrigVD), 4186 /*RefersToEnclosingVariableOrCapture=*/ 4187 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr, 4188 Pair.second->getType(), VK_LValue, 4189 Pair.second->getExprLoc()); 4190 Scope.addPrivate(Pair.first, [&CGF, &DRE]() { 4191 return CGF.EmitLValue(&DRE).getAddress(CGF); 4192 }); 4193 } 4194 for (const auto &Pair : PrivatePtrs) { 4195 Address Replacement(CGF.Builder.CreateLoad(Pair.second), 4196 CGF.getContext().getDeclAlign(Pair.first)); 4197 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; }); 4198 } 4199 // Adjust mapping for internal locals by mapping actual memory instead of 4200 // a pointer to this memory. 4201 for (auto &Pair : UntiedLocalVars) { 4202 if (isAllocatableDecl(Pair.first)) { 4203 llvm::Value *Ptr = CGF.Builder.CreateLoad(Pair.second.first); 4204 Address Replacement(Ptr, CGF.getPointerAlign()); 4205 Pair.getSecond().first = Replacement; 4206 Ptr = CGF.Builder.CreateLoad(Replacement); 4207 Replacement = Address(Ptr, CGF.getContext().getDeclAlign(Pair.first)); 4208 Pair.getSecond().second = Replacement; 4209 } else { 4210 llvm::Value *Ptr = CGF.Builder.CreateLoad(Pair.second.first); 4211 Address Replacement(Ptr, CGF.getContext().getDeclAlign(Pair.first)); 4212 Pair.getSecond().first = Replacement; 4213 } 4214 } 4215 } 4216 if (Data.Reductions) { 4217 OMPPrivateScope FirstprivateScope(CGF); 4218 for (const auto &Pair : FirstprivatePtrs) { 4219 Address Replacement(CGF.Builder.CreateLoad(Pair.second), 4220 CGF.getContext().getDeclAlign(Pair.first)); 4221 FirstprivateScope.addPrivate(Pair.first, 4222 [Replacement]() { return Replacement; }); 4223 } 4224 (void)FirstprivateScope.Privatize(); 4225 OMPLexicalScope LexScope(CGF, S, CapturedRegion); 4226 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionVars, 4227 Data.ReductionCopies, Data.ReductionOps); 4228 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad( 4229 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9))); 4230 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) { 4231 RedCG.emitSharedOrigLValue(CGF, Cnt); 4232 RedCG.emitAggregateType(CGF, Cnt); 4233 // FIXME: This must removed once the runtime library is fixed. 4234 // Emit required threadprivate variables for 4235 // initializer/combiner/finalizer. 4236 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(), 4237 RedCG, Cnt); 4238 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem( 4239 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt)); 4240 Replacement = 4241 Address(CGF.EmitScalarConversion( 4242 Replacement.getPointer(), CGF.getContext().VoidPtrTy, 4243 CGF.getContext().getPointerType( 4244 Data.ReductionCopies[Cnt]->getType()), 4245 Data.ReductionCopies[Cnt]->getExprLoc()), 4246 Replacement.getAlignment()); 4247 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement); 4248 Scope.addPrivate(RedCG.getBaseDecl(Cnt), 4249 [Replacement]() { return Replacement; }); 4250 } 4251 } 4252 // Privatize all private variables except for in_reduction items. 4253 (void)Scope.Privatize(); 4254 SmallVector<const Expr *, 4> InRedVars; 4255 SmallVector<const Expr *, 4> InRedPrivs; 4256 SmallVector<const Expr *, 4> InRedOps; 4257 SmallVector<const Expr *, 4> TaskgroupDescriptors; 4258 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) { 4259 auto IPriv = C->privates().begin(); 4260 auto IRed = C->reduction_ops().begin(); 4261 auto ITD = C->taskgroup_descriptors().begin(); 4262 for (const Expr *Ref : C->varlists()) { 4263 InRedVars.emplace_back(Ref); 4264 InRedPrivs.emplace_back(*IPriv); 4265 InRedOps.emplace_back(*IRed); 4266 TaskgroupDescriptors.emplace_back(*ITD); 4267 std::advance(IPriv, 1); 4268 std::advance(IRed, 1); 4269 std::advance(ITD, 1); 4270 } 4271 } 4272 // Privatize in_reduction items here, because taskgroup descriptors must be 4273 // privatized earlier. 4274 OMPPrivateScope InRedScope(CGF); 4275 if (!InRedVars.empty()) { 4276 ReductionCodeGen RedCG(InRedVars, InRedVars, InRedPrivs, InRedOps); 4277 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) { 4278 RedCG.emitSharedOrigLValue(CGF, Cnt); 4279 RedCG.emitAggregateType(CGF, Cnt); 4280 // The taskgroup descriptor variable is always implicit firstprivate and 4281 // privatized already during processing of the firstprivates. 4282 // FIXME: This must removed once the runtime library is fixed. 4283 // Emit required threadprivate variables for 4284 // initializer/combiner/finalizer. 4285 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(), 4286 RedCG, Cnt); 4287 llvm::Value *ReductionsPtr; 4288 if (const Expr *TRExpr = TaskgroupDescriptors[Cnt]) { 4289 ReductionsPtr = CGF.EmitLoadOfScalar(CGF.EmitLValue(TRExpr), 4290 TRExpr->getExprLoc()); 4291 } else { 4292 ReductionsPtr = llvm::ConstantPointerNull::get(CGF.VoidPtrTy); 4293 } 4294 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem( 4295 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt)); 4296 Replacement = Address( 4297 CGF.EmitScalarConversion( 4298 Replacement.getPointer(), CGF.getContext().VoidPtrTy, 4299 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()), 4300 InRedPrivs[Cnt]->getExprLoc()), 4301 Replacement.getAlignment()); 4302 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement); 4303 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt), 4304 [Replacement]() { return Replacement; }); 4305 } 4306 } 4307 (void)InRedScope.Privatize(); 4308 4309 CGOpenMPRuntime::UntiedTaskLocalDeclsRAII LocalVarsScope(CGF, 4310 UntiedLocalVars); 4311 Action.Enter(CGF); 4312 BodyGen(CGF); 4313 }; 4314 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction( 4315 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied, 4316 Data.NumberOfParts); 4317 OMPLexicalScope Scope(*this, S, llvm::None, 4318 !isOpenMPParallelDirective(S.getDirectiveKind()) && 4319 !isOpenMPSimdDirective(S.getDirectiveKind())); 4320 TaskGen(*this, OutlinedFn, Data); 4321 } 4322 4323 static ImplicitParamDecl * 4324 createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data, 4325 QualType Ty, CapturedDecl *CD, 4326 SourceLocation Loc) { 4327 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty, 4328 ImplicitParamDecl::Other); 4329 auto *OrigRef = DeclRefExpr::Create( 4330 C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD, 4331 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue); 4332 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty, 4333 ImplicitParamDecl::Other); 4334 auto *PrivateRef = DeclRefExpr::Create( 4335 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD, 4336 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue); 4337 QualType ElemType = C.getBaseElementType(Ty); 4338 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType, 4339 ImplicitParamDecl::Other); 4340 auto *InitRef = DeclRefExpr::Create( 4341 C, NestedNameSpecifierLoc(), SourceLocation(), InitVD, 4342 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue); 4343 PrivateVD->setInitStyle(VarDecl::CInit); 4344 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue, 4345 InitRef, /*BasePath=*/nullptr, 4346 VK_RValue, FPOptionsOverride())); 4347 Data.FirstprivateVars.emplace_back(OrigRef); 4348 Data.FirstprivateCopies.emplace_back(PrivateRef); 4349 Data.FirstprivateInits.emplace_back(InitRef); 4350 return OrigVD; 4351 } 4352 4353 void CodeGenFunction::EmitOMPTargetTaskBasedDirective( 4354 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen, 4355 OMPTargetDataInfo &InputInfo) { 4356 // Emit outlined function for task construct. 4357 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task); 4358 Address CapturedStruct = GenerateCapturedStmtArgument(*CS); 4359 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 4360 auto I = CS->getCapturedDecl()->param_begin(); 4361 auto PartId = std::next(I); 4362 auto TaskT = std::next(I, 4); 4363 OMPTaskDataTy Data; 4364 // The task is not final. 4365 Data.Final.setInt(/*IntVal=*/false); 4366 // Get list of firstprivate variables. 4367 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) { 4368 auto IRef = C->varlist_begin(); 4369 auto IElemInitRef = C->inits().begin(); 4370 for (auto *IInit : C->private_copies()) { 4371 Data.FirstprivateVars.push_back(*IRef); 4372 Data.FirstprivateCopies.push_back(IInit); 4373 Data.FirstprivateInits.push_back(*IElemInitRef); 4374 ++IRef; 4375 ++IElemInitRef; 4376 } 4377 } 4378 OMPPrivateScope TargetScope(*this); 4379 VarDecl *BPVD = nullptr; 4380 VarDecl *PVD = nullptr; 4381 VarDecl *SVD = nullptr; 4382 VarDecl *MVD = nullptr; 4383 if (InputInfo.NumberOfTargetItems > 0) { 4384 auto *CD = CapturedDecl::Create( 4385 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0); 4386 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems); 4387 QualType BaseAndPointerAndMapperType = getContext().getConstantArrayType( 4388 getContext().VoidPtrTy, ArrSize, nullptr, ArrayType::Normal, 4389 /*IndexTypeQuals=*/0); 4390 BPVD = createImplicitFirstprivateForType( 4391 getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc()); 4392 PVD = createImplicitFirstprivateForType( 4393 getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc()); 4394 QualType SizesType = getContext().getConstantArrayType( 4395 getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1), 4396 ArrSize, nullptr, ArrayType::Normal, 4397 /*IndexTypeQuals=*/0); 4398 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD, 4399 S.getBeginLoc()); 4400 TargetScope.addPrivate( 4401 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; }); 4402 TargetScope.addPrivate(PVD, 4403 [&InputInfo]() { return InputInfo.PointersArray; }); 4404 TargetScope.addPrivate(SVD, 4405 [&InputInfo]() { return InputInfo.SizesArray; }); 4406 // If there is no user-defined mapper, the mapper array will be nullptr. In 4407 // this case, we don't need to privatize it. 4408 if (!dyn_cast_or_null<llvm::ConstantPointerNull>( 4409 InputInfo.MappersArray.getPointer())) { 4410 MVD = createImplicitFirstprivateForType( 4411 getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc()); 4412 TargetScope.addPrivate(MVD, 4413 [&InputInfo]() { return InputInfo.MappersArray; }); 4414 } 4415 } 4416 (void)TargetScope.Privatize(); 4417 // Build list of dependences. 4418 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) { 4419 OMPTaskDataTy::DependData &DD = 4420 Data.Dependences.emplace_back(C->getDependencyKind(), C->getModifier()); 4421 DD.DepExprs.append(C->varlist_begin(), C->varlist_end()); 4422 } 4423 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD, MVD, 4424 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) { 4425 // Set proper addresses for generated private copies. 4426 OMPPrivateScope Scope(CGF); 4427 if (!Data.FirstprivateVars.empty()) { 4428 llvm::FunctionType *CopyFnTy = llvm::FunctionType::get( 4429 CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true); 4430 enum { PrivatesParam = 2, CopyFnParam = 3 }; 4431 llvm::Value *CopyFn = CGF.Builder.CreateLoad( 4432 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam))); 4433 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar( 4434 CS->getCapturedDecl()->getParam(PrivatesParam))); 4435 // Map privates. 4436 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs; 4437 llvm::SmallVector<llvm::Value *, 16> CallArgs; 4438 CallArgs.push_back(PrivatesPtr); 4439 for (const Expr *E : Data.FirstprivateVars) { 4440 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4441 Address PrivatePtr = 4442 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()), 4443 ".firstpriv.ptr.addr"); 4444 PrivatePtrs.emplace_back(VD, PrivatePtr); 4445 CallArgs.push_back(PrivatePtr.getPointer()); 4446 } 4447 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall( 4448 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs); 4449 for (const auto &Pair : PrivatePtrs) { 4450 Address Replacement(CGF.Builder.CreateLoad(Pair.second), 4451 CGF.getContext().getDeclAlign(Pair.first)); 4452 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; }); 4453 } 4454 } 4455 // Privatize all private variables except for in_reduction items. 4456 (void)Scope.Privatize(); 4457 if (InputInfo.NumberOfTargetItems > 0) { 4458 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP( 4459 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0); 4460 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP( 4461 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0); 4462 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP( 4463 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0); 4464 // If MVD is nullptr, the mapper array is not privatized 4465 if (MVD) 4466 InputInfo.MappersArray = CGF.Builder.CreateConstArrayGEP( 4467 CGF.GetAddrOfLocalVar(MVD), /*Index=*/0); 4468 } 4469 4470 Action.Enter(CGF); 4471 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false); 4472 BodyGen(CGF); 4473 }; 4474 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction( 4475 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true, 4476 Data.NumberOfParts); 4477 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0); 4478 IntegerLiteral IfCond(getContext(), TrueOrFalse, 4479 getContext().getIntTypeForBitwidth(32, /*Signed=*/0), 4480 SourceLocation()); 4481 4482 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn, 4483 SharedsTy, CapturedStruct, &IfCond, Data); 4484 } 4485 4486 void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) { 4487 // Emit outlined function for task construct. 4488 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task); 4489 Address CapturedStruct = GenerateCapturedStmtArgument(*CS); 4490 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 4491 const Expr *IfCond = nullptr; 4492 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 4493 if (C->getNameModifier() == OMPD_unknown || 4494 C->getNameModifier() == OMPD_task) { 4495 IfCond = C->getCondition(); 4496 break; 4497 } 4498 } 4499 4500 OMPTaskDataTy Data; 4501 // Check if we should emit tied or untied task. 4502 Data.Tied = !S.getSingleClause<OMPUntiedClause>(); 4503 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) { 4504 CGF.EmitStmt(CS->getCapturedStmt()); 4505 }; 4506 auto &&TaskGen = [&S, SharedsTy, CapturedStruct, 4507 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn, 4508 const OMPTaskDataTy &Data) { 4509 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn, 4510 SharedsTy, CapturedStruct, IfCond, 4511 Data); 4512 }; 4513 auto LPCRegion = 4514 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 4515 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data); 4516 } 4517 4518 void CodeGenFunction::EmitOMPTaskyieldDirective( 4519 const OMPTaskyieldDirective &S) { 4520 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc()); 4521 } 4522 4523 void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) { 4524 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier); 4525 } 4526 4527 void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) { 4528 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc()); 4529 } 4530 4531 void CodeGenFunction::EmitOMPTaskgroupDirective( 4532 const OMPTaskgroupDirective &S) { 4533 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4534 Action.Enter(CGF); 4535 if (const Expr *E = S.getReductionRef()) { 4536 SmallVector<const Expr *, 4> LHSs; 4537 SmallVector<const Expr *, 4> RHSs; 4538 OMPTaskDataTy Data; 4539 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) { 4540 Data.ReductionVars.append(C->varlist_begin(), C->varlist_end()); 4541 Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end()); 4542 Data.ReductionCopies.append(C->privates().begin(), C->privates().end()); 4543 Data.ReductionOps.append(C->reduction_ops().begin(), 4544 C->reduction_ops().end()); 4545 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 4546 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 4547 } 4548 llvm::Value *ReductionDesc = 4549 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(), 4550 LHSs, RHSs, Data); 4551 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4552 CGF.EmitVarDecl(*VD); 4553 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD), 4554 /*Volatile=*/false, E->getType()); 4555 } 4556 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 4557 }; 4558 OMPLexicalScope Scope(*this, S, OMPD_unknown); 4559 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc()); 4560 } 4561 4562 void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) { 4563 llvm::AtomicOrdering AO = S.getSingleClause<OMPFlushClause>() 4564 ? llvm::AtomicOrdering::NotAtomic 4565 : llvm::AtomicOrdering::AcquireRelease; 4566 CGM.getOpenMPRuntime().emitFlush( 4567 *this, 4568 [&S]() -> ArrayRef<const Expr *> { 4569 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) 4570 return llvm::makeArrayRef(FlushClause->varlist_begin(), 4571 FlushClause->varlist_end()); 4572 return llvm::None; 4573 }(), 4574 S.getBeginLoc(), AO); 4575 } 4576 4577 void CodeGenFunction::EmitOMPDepobjDirective(const OMPDepobjDirective &S) { 4578 const auto *DO = S.getSingleClause<OMPDepobjClause>(); 4579 LValue DOLVal = EmitLValue(DO->getDepobj()); 4580 if (const auto *DC = S.getSingleClause<OMPDependClause>()) { 4581 OMPTaskDataTy::DependData Dependencies(DC->getDependencyKind(), 4582 DC->getModifier()); 4583 Dependencies.DepExprs.append(DC->varlist_begin(), DC->varlist_end()); 4584 Address DepAddr = CGM.getOpenMPRuntime().emitDepobjDependClause( 4585 *this, Dependencies, DC->getBeginLoc()); 4586 EmitStoreOfScalar(DepAddr.getPointer(), DOLVal); 4587 return; 4588 } 4589 if (const auto *DC = S.getSingleClause<OMPDestroyClause>()) { 4590 CGM.getOpenMPRuntime().emitDestroyClause(*this, DOLVal, DC->getBeginLoc()); 4591 return; 4592 } 4593 if (const auto *UC = S.getSingleClause<OMPUpdateClause>()) { 4594 CGM.getOpenMPRuntime().emitUpdateClause( 4595 *this, DOLVal, UC->getDependencyKind(), UC->getBeginLoc()); 4596 return; 4597 } 4598 } 4599 4600 void CodeGenFunction::EmitOMPScanDirective(const OMPScanDirective &S) { 4601 if (!OMPParentLoopDirectiveForScan) 4602 return; 4603 const OMPExecutableDirective &ParentDir = *OMPParentLoopDirectiveForScan; 4604 bool IsInclusive = S.hasClausesOfKind<OMPInclusiveClause>(); 4605 SmallVector<const Expr *, 4> Shareds; 4606 SmallVector<const Expr *, 4> Privates; 4607 SmallVector<const Expr *, 4> LHSs; 4608 SmallVector<const Expr *, 4> RHSs; 4609 SmallVector<const Expr *, 4> ReductionOps; 4610 SmallVector<const Expr *, 4> CopyOps; 4611 SmallVector<const Expr *, 4> CopyArrayTemps; 4612 SmallVector<const Expr *, 4> CopyArrayElems; 4613 for (const auto *C : ParentDir.getClausesOfKind<OMPReductionClause>()) { 4614 if (C->getModifier() != OMPC_REDUCTION_inscan) 4615 continue; 4616 Shareds.append(C->varlist_begin(), C->varlist_end()); 4617 Privates.append(C->privates().begin(), C->privates().end()); 4618 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 4619 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 4620 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end()); 4621 CopyOps.append(C->copy_ops().begin(), C->copy_ops().end()); 4622 CopyArrayTemps.append(C->copy_array_temps().begin(), 4623 C->copy_array_temps().end()); 4624 CopyArrayElems.append(C->copy_array_elems().begin(), 4625 C->copy_array_elems().end()); 4626 } 4627 if (ParentDir.getDirectiveKind() == OMPD_simd || 4628 (getLangOpts().OpenMPSimd && 4629 isOpenMPSimdDirective(ParentDir.getDirectiveKind()))) { 4630 // For simd directive and simd-based directives in simd only mode, use the 4631 // following codegen: 4632 // int x = 0; 4633 // #pragma omp simd reduction(inscan, +: x) 4634 // for (..) { 4635 // <first part> 4636 // #pragma omp scan inclusive(x) 4637 // <second part> 4638 // } 4639 // is transformed to: 4640 // int x = 0; 4641 // for (..) { 4642 // int x_priv = 0; 4643 // <first part> 4644 // x = x_priv + x; 4645 // x_priv = x; 4646 // <second part> 4647 // } 4648 // and 4649 // int x = 0; 4650 // #pragma omp simd reduction(inscan, +: x) 4651 // for (..) { 4652 // <first part> 4653 // #pragma omp scan exclusive(x) 4654 // <second part> 4655 // } 4656 // to 4657 // int x = 0; 4658 // for (..) { 4659 // int x_priv = 0; 4660 // <second part> 4661 // int temp = x; 4662 // x = x_priv + x; 4663 // x_priv = temp; 4664 // <first part> 4665 // } 4666 llvm::BasicBlock *OMPScanReduce = createBasicBlock("omp.inscan.reduce"); 4667 EmitBranch(IsInclusive 4668 ? OMPScanReduce 4669 : BreakContinueStack.back().ContinueBlock.getBlock()); 4670 EmitBlock(OMPScanDispatch); 4671 { 4672 // New scope for correct construction/destruction of temp variables for 4673 // exclusive scan. 4674 LexicalScope Scope(*this, S.getSourceRange()); 4675 EmitBranch(IsInclusive ? OMPBeforeScanBlock : OMPAfterScanBlock); 4676 EmitBlock(OMPScanReduce); 4677 if (!IsInclusive) { 4678 // Create temp var and copy LHS value to this temp value. 4679 // TMP = LHS; 4680 for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) { 4681 const Expr *PrivateExpr = Privates[I]; 4682 const Expr *TempExpr = CopyArrayTemps[I]; 4683 EmitAutoVarDecl( 4684 *cast<VarDecl>(cast<DeclRefExpr>(TempExpr)->getDecl())); 4685 LValue DestLVal = EmitLValue(TempExpr); 4686 LValue SrcLVal = EmitLValue(LHSs[I]); 4687 EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this), 4688 SrcLVal.getAddress(*this), 4689 cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()), 4690 cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()), 4691 CopyOps[I]); 4692 } 4693 } 4694 CGM.getOpenMPRuntime().emitReduction( 4695 *this, ParentDir.getEndLoc(), Privates, LHSs, RHSs, ReductionOps, 4696 {/*WithNowait=*/true, /*SimpleReduction=*/true, OMPD_simd}); 4697 for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) { 4698 const Expr *PrivateExpr = Privates[I]; 4699 LValue DestLVal; 4700 LValue SrcLVal; 4701 if (IsInclusive) { 4702 DestLVal = EmitLValue(RHSs[I]); 4703 SrcLVal = EmitLValue(LHSs[I]); 4704 } else { 4705 const Expr *TempExpr = CopyArrayTemps[I]; 4706 DestLVal = EmitLValue(RHSs[I]); 4707 SrcLVal = EmitLValue(TempExpr); 4708 } 4709 EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this), 4710 SrcLVal.getAddress(*this), 4711 cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()), 4712 cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()), 4713 CopyOps[I]); 4714 } 4715 } 4716 EmitBranch(IsInclusive ? OMPAfterScanBlock : OMPBeforeScanBlock); 4717 OMPScanExitBlock = IsInclusive 4718 ? BreakContinueStack.back().ContinueBlock.getBlock() 4719 : OMPScanReduce; 4720 EmitBlock(OMPAfterScanBlock); 4721 return; 4722 } 4723 if (!IsInclusive) { 4724 EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock()); 4725 EmitBlock(OMPScanExitBlock); 4726 } 4727 if (OMPFirstScanLoop) { 4728 // Emit buffer[i] = red; at the end of the input phase. 4729 const auto *IVExpr = cast<OMPLoopDirective>(ParentDir) 4730 .getIterationVariable() 4731 ->IgnoreParenImpCasts(); 4732 LValue IdxLVal = EmitLValue(IVExpr); 4733 llvm::Value *IdxVal = EmitLoadOfScalar(IdxLVal, IVExpr->getExprLoc()); 4734 IdxVal = Builder.CreateIntCast(IdxVal, SizeTy, /*isSigned=*/false); 4735 for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) { 4736 const Expr *PrivateExpr = Privates[I]; 4737 const Expr *OrigExpr = Shareds[I]; 4738 const Expr *CopyArrayElem = CopyArrayElems[I]; 4739 OpaqueValueMapping IdxMapping( 4740 *this, 4741 cast<OpaqueValueExpr>( 4742 cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()), 4743 RValue::get(IdxVal)); 4744 LValue DestLVal = EmitLValue(CopyArrayElem); 4745 LValue SrcLVal = EmitLValue(OrigExpr); 4746 EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this), 4747 SrcLVal.getAddress(*this), 4748 cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()), 4749 cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()), 4750 CopyOps[I]); 4751 } 4752 } 4753 EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock()); 4754 if (IsInclusive) { 4755 EmitBlock(OMPScanExitBlock); 4756 EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock()); 4757 } 4758 EmitBlock(OMPScanDispatch); 4759 if (!OMPFirstScanLoop) { 4760 // Emit red = buffer[i]; at the entrance to the scan phase. 4761 const auto *IVExpr = cast<OMPLoopDirective>(ParentDir) 4762 .getIterationVariable() 4763 ->IgnoreParenImpCasts(); 4764 LValue IdxLVal = EmitLValue(IVExpr); 4765 llvm::Value *IdxVal = EmitLoadOfScalar(IdxLVal, IVExpr->getExprLoc()); 4766 IdxVal = Builder.CreateIntCast(IdxVal, SizeTy, /*isSigned=*/false); 4767 llvm::BasicBlock *ExclusiveExitBB = nullptr; 4768 if (!IsInclusive) { 4769 llvm::BasicBlock *ContBB = createBasicBlock("omp.exclusive.dec"); 4770 ExclusiveExitBB = createBasicBlock("omp.exclusive.copy.exit"); 4771 llvm::Value *Cmp = Builder.CreateIsNull(IdxVal); 4772 Builder.CreateCondBr(Cmp, ExclusiveExitBB, ContBB); 4773 EmitBlock(ContBB); 4774 // Use idx - 1 iteration for exclusive scan. 4775 IdxVal = Builder.CreateNUWSub(IdxVal, llvm::ConstantInt::get(SizeTy, 1)); 4776 } 4777 for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) { 4778 const Expr *PrivateExpr = Privates[I]; 4779 const Expr *OrigExpr = Shareds[I]; 4780 const Expr *CopyArrayElem = CopyArrayElems[I]; 4781 OpaqueValueMapping IdxMapping( 4782 *this, 4783 cast<OpaqueValueExpr>( 4784 cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()), 4785 RValue::get(IdxVal)); 4786 LValue SrcLVal = EmitLValue(CopyArrayElem); 4787 LValue DestLVal = EmitLValue(OrigExpr); 4788 EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this), 4789 SrcLVal.getAddress(*this), 4790 cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()), 4791 cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()), 4792 CopyOps[I]); 4793 } 4794 if (!IsInclusive) { 4795 EmitBlock(ExclusiveExitBB); 4796 } 4797 } 4798 EmitBranch((OMPFirstScanLoop == IsInclusive) ? OMPBeforeScanBlock 4799 : OMPAfterScanBlock); 4800 EmitBlock(OMPAfterScanBlock); 4801 } 4802 4803 void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S, 4804 const CodeGenLoopTy &CodeGenLoop, 4805 Expr *IncExpr) { 4806 // Emit the loop iteration variable. 4807 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable()); 4808 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl()); 4809 EmitVarDecl(*IVDecl); 4810 4811 // Emit the iterations count variable. 4812 // If it is not a variable, Sema decided to calculate iterations count on each 4813 // iteration (e.g., it is foldable into a constant). 4814 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 4815 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 4816 // Emit calculation of the iterations count. 4817 EmitIgnoredExpr(S.getCalcLastIteration()); 4818 } 4819 4820 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 4821 4822 bool HasLastprivateClause = false; 4823 // Check pre-condition. 4824 { 4825 OMPLoopScope PreInitScope(*this, S); 4826 // Skip the entire loop if we don't meet the precondition. 4827 // If the condition constant folds and can be elided, avoid emitting the 4828 // whole loop. 4829 bool CondConstant; 4830 llvm::BasicBlock *ContBlock = nullptr; 4831 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 4832 if (!CondConstant) 4833 return; 4834 } else { 4835 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then"); 4836 ContBlock = createBasicBlock("omp.precond.end"); 4837 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock, 4838 getProfileCount(&S)); 4839 EmitBlock(ThenBlock); 4840 incrementProfileCounter(&S); 4841 } 4842 4843 emitAlignedClause(*this, S); 4844 // Emit 'then' code. 4845 { 4846 // Emit helper vars inits. 4847 4848 LValue LB = EmitOMPHelperVar( 4849 *this, cast<DeclRefExpr>( 4850 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 4851 ? S.getCombinedLowerBoundVariable() 4852 : S.getLowerBoundVariable()))); 4853 LValue UB = EmitOMPHelperVar( 4854 *this, cast<DeclRefExpr>( 4855 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 4856 ? S.getCombinedUpperBoundVariable() 4857 : S.getUpperBoundVariable()))); 4858 LValue ST = 4859 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable())); 4860 LValue IL = 4861 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable())); 4862 4863 OMPPrivateScope LoopScope(*this); 4864 if (EmitOMPFirstprivateClause(S, LoopScope)) { 4865 // Emit implicit barrier to synchronize threads and avoid data races 4866 // on initialization of firstprivate variables and post-update of 4867 // lastprivate variables. 4868 CGM.getOpenMPRuntime().emitBarrierCall( 4869 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 4870 /*ForceSimpleCall=*/true); 4871 } 4872 EmitOMPPrivateClause(S, LoopScope); 4873 if (isOpenMPSimdDirective(S.getDirectiveKind()) && 4874 !isOpenMPParallelDirective(S.getDirectiveKind()) && 4875 !isOpenMPTeamsDirective(S.getDirectiveKind())) 4876 EmitOMPReductionClauseInit(S, LoopScope); 4877 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope); 4878 EmitOMPPrivateLoopCounters(S, LoopScope); 4879 (void)LoopScope.Privatize(); 4880 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 4881 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S); 4882 4883 // Detect the distribute schedule kind and chunk. 4884 llvm::Value *Chunk = nullptr; 4885 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown; 4886 if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) { 4887 ScheduleKind = C->getDistScheduleKind(); 4888 if (const Expr *Ch = C->getChunkSize()) { 4889 Chunk = EmitScalarExpr(Ch); 4890 Chunk = EmitScalarConversion(Chunk, Ch->getType(), 4891 S.getIterationVariable()->getType(), 4892 S.getBeginLoc()); 4893 } 4894 } else { 4895 // Default behaviour for dist_schedule clause. 4896 CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk( 4897 *this, S, ScheduleKind, Chunk); 4898 } 4899 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 4900 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 4901 4902 // OpenMP [2.10.8, distribute Construct, Description] 4903 // If dist_schedule is specified, kind must be static. If specified, 4904 // iterations are divided into chunks of size chunk_size, chunks are 4905 // assigned to the teams of the league in a round-robin fashion in the 4906 // order of the team number. When no chunk_size is specified, the 4907 // iteration space is divided into chunks that are approximately equal 4908 // in size, and at most one chunk is distributed to each team of the 4909 // league. The size of the chunks is unspecified in this case. 4910 bool StaticChunked = RT.isStaticChunked( 4911 ScheduleKind, /* Chunked */ Chunk != nullptr) && 4912 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()); 4913 if (RT.isStaticNonchunked(ScheduleKind, 4914 /* Chunked */ Chunk != nullptr) || 4915 StaticChunked) { 4916 CGOpenMPRuntime::StaticRTInput StaticInit( 4917 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(*this), 4918 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this), 4919 StaticChunked ? Chunk : nullptr); 4920 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, 4921 StaticInit); 4922 JumpDest LoopExit = 4923 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit")); 4924 // UB = min(UB, GlobalUB); 4925 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 4926 ? S.getCombinedEnsureUpperBound() 4927 : S.getEnsureUpperBound()); 4928 // IV = LB; 4929 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 4930 ? S.getCombinedInit() 4931 : S.getInit()); 4932 4933 const Expr *Cond = 4934 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 4935 ? S.getCombinedCond() 4936 : S.getCond(); 4937 4938 if (StaticChunked) 4939 Cond = S.getCombinedDistCond(); 4940 4941 // For static unchunked schedules generate: 4942 // 4943 // 1. For distribute alone, codegen 4944 // while (idx <= UB) { 4945 // BODY; 4946 // ++idx; 4947 // } 4948 // 4949 // 2. When combined with 'for' (e.g. as in 'distribute parallel for') 4950 // while (idx <= UB) { 4951 // <CodeGen rest of pragma>(LB, UB); 4952 // idx += ST; 4953 // } 4954 // 4955 // For static chunk one schedule generate: 4956 // 4957 // while (IV <= GlobalUB) { 4958 // <CodeGen rest of pragma>(LB, UB); 4959 // LB += ST; 4960 // UB += ST; 4961 // UB = min(UB, GlobalUB); 4962 // IV = LB; 4963 // } 4964 // 4965 emitCommonSimdLoop( 4966 *this, S, 4967 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 4968 if (isOpenMPSimdDirective(S.getDirectiveKind())) 4969 CGF.EmitOMPSimdInit(S, /*IsMonotonic=*/true); 4970 }, 4971 [&S, &LoopScope, Cond, IncExpr, LoopExit, &CodeGenLoop, 4972 StaticChunked](CodeGenFunction &CGF, PrePostActionTy &) { 4973 CGF.EmitOMPInnerLoop( 4974 S, LoopScope.requiresCleanups(), Cond, IncExpr, 4975 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) { 4976 CodeGenLoop(CGF, S, LoopExit); 4977 }, 4978 [&S, StaticChunked](CodeGenFunction &CGF) { 4979 if (StaticChunked) { 4980 CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound()); 4981 CGF.EmitIgnoredExpr(S.getCombinedNextUpperBound()); 4982 CGF.EmitIgnoredExpr(S.getCombinedEnsureUpperBound()); 4983 CGF.EmitIgnoredExpr(S.getCombinedInit()); 4984 } 4985 }); 4986 }); 4987 EmitBlock(LoopExit.getBlock()); 4988 // Tell the runtime we are done. 4989 RT.emitForStaticFinish(*this, S.getEndLoc(), S.getDirectiveKind()); 4990 } else { 4991 // Emit the outer loop, which requests its work chunk [LB..UB] from 4992 // runtime and runs the inner loop to process it. 4993 const OMPLoopArguments LoopArguments = { 4994 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this), 4995 IL.getAddress(*this), Chunk}; 4996 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments, 4997 CodeGenLoop); 4998 } 4999 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 5000 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) { 5001 return CGF.Builder.CreateIsNotNull( 5002 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 5003 }); 5004 } 5005 if (isOpenMPSimdDirective(S.getDirectiveKind()) && 5006 !isOpenMPParallelDirective(S.getDirectiveKind()) && 5007 !isOpenMPTeamsDirective(S.getDirectiveKind())) { 5008 EmitOMPReductionClauseFinal(S, OMPD_simd); 5009 // Emit post-update of the reduction variables if IsLastIter != 0. 5010 emitPostUpdateForReductionClause( 5011 *this, S, [IL, &S](CodeGenFunction &CGF) { 5012 return CGF.Builder.CreateIsNotNull( 5013 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 5014 }); 5015 } 5016 // Emit final copy of the lastprivate variables if IsLastIter != 0. 5017 if (HasLastprivateClause) { 5018 EmitOMPLastprivateClauseFinal( 5019 S, /*NoFinals=*/false, 5020 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc()))); 5021 } 5022 } 5023 5024 // We're now done with the loop, so jump to the continuation block. 5025 if (ContBlock) { 5026 EmitBranch(ContBlock); 5027 EmitBlock(ContBlock, true); 5028 } 5029 } 5030 } 5031 5032 void CodeGenFunction::EmitOMPDistributeDirective( 5033 const OMPDistributeDirective &S) { 5034 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5035 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 5036 }; 5037 OMPLexicalScope Scope(*this, S, OMPD_unknown); 5038 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen); 5039 } 5040 5041 static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM, 5042 const CapturedStmt *S, 5043 SourceLocation Loc) { 5044 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true); 5045 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo; 5046 CGF.CapturedStmtInfo = &CapStmtInfo; 5047 llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S, Loc); 5048 Fn->setDoesNotRecurse(); 5049 return Fn; 5050 } 5051 5052 void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) { 5053 if (S.hasClausesOfKind<OMPDependClause>()) { 5054 assert(!S.hasAssociatedStmt() && 5055 "No associated statement must be in ordered depend construct."); 5056 for (const auto *DC : S.getClausesOfKind<OMPDependClause>()) 5057 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC); 5058 return; 5059 } 5060 const auto *C = S.getSingleClause<OMPSIMDClause>(); 5061 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF, 5062 PrePostActionTy &Action) { 5063 const CapturedStmt *CS = S.getInnermostCapturedStmt(); 5064 if (C) { 5065 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 5066 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars); 5067 llvm::Function *OutlinedFn = 5068 emitOutlinedOrderedFunction(CGM, CS, S.getBeginLoc()); 5069 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(), 5070 OutlinedFn, CapturedVars); 5071 } else { 5072 Action.Enter(CGF); 5073 CGF.EmitStmt(CS->getCapturedStmt()); 5074 } 5075 }; 5076 OMPLexicalScope Scope(*this, S, OMPD_unknown); 5077 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C); 5078 } 5079 5080 static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val, 5081 QualType SrcType, QualType DestType, 5082 SourceLocation Loc) { 5083 assert(CGF.hasScalarEvaluationKind(DestType) && 5084 "DestType must have scalar evaluation kind."); 5085 assert(!Val.isAggregate() && "Must be a scalar or complex."); 5086 return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, 5087 DestType, Loc) 5088 : CGF.EmitComplexToScalarConversion( 5089 Val.getComplexVal(), SrcType, DestType, Loc); 5090 } 5091 5092 static CodeGenFunction::ComplexPairTy 5093 convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType, 5094 QualType DestType, SourceLocation Loc) { 5095 assert(CGF.getEvaluationKind(DestType) == TEK_Complex && 5096 "DestType must have complex evaluation kind."); 5097 CodeGenFunction::ComplexPairTy ComplexVal; 5098 if (Val.isScalar()) { 5099 // Convert the input element to the element type of the complex. 5100 QualType DestElementType = 5101 DestType->castAs<ComplexType>()->getElementType(); 5102 llvm::Value *ScalarVal = CGF.EmitScalarConversion( 5103 Val.getScalarVal(), SrcType, DestElementType, Loc); 5104 ComplexVal = CodeGenFunction::ComplexPairTy( 5105 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType())); 5106 } else { 5107 assert(Val.isComplex() && "Must be a scalar or complex."); 5108 QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType(); 5109 QualType DestElementType = 5110 DestType->castAs<ComplexType>()->getElementType(); 5111 ComplexVal.first = CGF.EmitScalarConversion( 5112 Val.getComplexVal().first, SrcElementType, DestElementType, Loc); 5113 ComplexVal.second = CGF.EmitScalarConversion( 5114 Val.getComplexVal().second, SrcElementType, DestElementType, Loc); 5115 } 5116 return ComplexVal; 5117 } 5118 5119 static void emitSimpleAtomicStore(CodeGenFunction &CGF, llvm::AtomicOrdering AO, 5120 LValue LVal, RValue RVal) { 5121 if (LVal.isGlobalReg()) 5122 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal); 5123 else 5124 CGF.EmitAtomicStore(RVal, LVal, AO, LVal.isVolatile(), /*isInit=*/false); 5125 } 5126 5127 static RValue emitSimpleAtomicLoad(CodeGenFunction &CGF, 5128 llvm::AtomicOrdering AO, LValue LVal, 5129 SourceLocation Loc) { 5130 if (LVal.isGlobalReg()) 5131 return CGF.EmitLoadOfLValue(LVal, Loc); 5132 return CGF.EmitAtomicLoad( 5133 LVal, Loc, llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO), 5134 LVal.isVolatile()); 5135 } 5136 5137 void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal, 5138 QualType RValTy, SourceLocation Loc) { 5139 switch (getEvaluationKind(LVal.getType())) { 5140 case TEK_Scalar: 5141 EmitStoreThroughLValue(RValue::get(convertToScalarValue( 5142 *this, RVal, RValTy, LVal.getType(), Loc)), 5143 LVal); 5144 break; 5145 case TEK_Complex: 5146 EmitStoreOfComplex( 5147 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal, 5148 /*isInit=*/false); 5149 break; 5150 case TEK_Aggregate: 5151 llvm_unreachable("Must be a scalar or complex."); 5152 } 5153 } 5154 5155 static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, llvm::AtomicOrdering AO, 5156 const Expr *X, const Expr *V, 5157 SourceLocation Loc) { 5158 // v = x; 5159 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue"); 5160 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue"); 5161 LValue XLValue = CGF.EmitLValue(X); 5162 LValue VLValue = CGF.EmitLValue(V); 5163 RValue Res = emitSimpleAtomicLoad(CGF, AO, XLValue, Loc); 5164 // OpenMP, 2.17.7, atomic Construct 5165 // If the read or capture clause is specified and the acquire, acq_rel, or 5166 // seq_cst clause is specified then the strong flush on exit from the atomic 5167 // operation is also an acquire flush. 5168 switch (AO) { 5169 case llvm::AtomicOrdering::Acquire: 5170 case llvm::AtomicOrdering::AcquireRelease: 5171 case llvm::AtomicOrdering::SequentiallyConsistent: 5172 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 5173 llvm::AtomicOrdering::Acquire); 5174 break; 5175 case llvm::AtomicOrdering::Monotonic: 5176 case llvm::AtomicOrdering::Release: 5177 break; 5178 case llvm::AtomicOrdering::NotAtomic: 5179 case llvm::AtomicOrdering::Unordered: 5180 llvm_unreachable("Unexpected ordering."); 5181 } 5182 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc); 5183 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V); 5184 } 5185 5186 static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF, 5187 llvm::AtomicOrdering AO, const Expr *X, 5188 const Expr *E, SourceLocation Loc) { 5189 // x = expr; 5190 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue"); 5191 emitSimpleAtomicStore(CGF, AO, CGF.EmitLValue(X), CGF.EmitAnyExpr(E)); 5192 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 5193 // OpenMP, 2.17.7, atomic Construct 5194 // If the write, update, or capture clause is specified and the release, 5195 // acq_rel, or seq_cst clause is specified then the strong flush on entry to 5196 // the atomic operation is also a release flush. 5197 switch (AO) { 5198 case llvm::AtomicOrdering::Release: 5199 case llvm::AtomicOrdering::AcquireRelease: 5200 case llvm::AtomicOrdering::SequentiallyConsistent: 5201 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 5202 llvm::AtomicOrdering::Release); 5203 break; 5204 case llvm::AtomicOrdering::Acquire: 5205 case llvm::AtomicOrdering::Monotonic: 5206 break; 5207 case llvm::AtomicOrdering::NotAtomic: 5208 case llvm::AtomicOrdering::Unordered: 5209 llvm_unreachable("Unexpected ordering."); 5210 } 5211 } 5212 5213 static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X, 5214 RValue Update, 5215 BinaryOperatorKind BO, 5216 llvm::AtomicOrdering AO, 5217 bool IsXLHSInRHSPart) { 5218 ASTContext &Context = CGF.getContext(); 5219 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x' 5220 // expression is simple and atomic is allowed for the given type for the 5221 // target platform. 5222 if (BO == BO_Comma || !Update.isScalar() || 5223 !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() || 5224 (!isa<llvm::ConstantInt>(Update.getScalarVal()) && 5225 (Update.getScalarVal()->getType() != 5226 X.getAddress(CGF).getElementType())) || 5227 !X.getAddress(CGF).getElementType()->isIntegerTy() || 5228 !Context.getTargetInfo().hasBuiltinAtomic( 5229 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment()))) 5230 return std::make_pair(false, RValue::get(nullptr)); 5231 5232 llvm::AtomicRMWInst::BinOp RMWOp; 5233 switch (BO) { 5234 case BO_Add: 5235 RMWOp = llvm::AtomicRMWInst::Add; 5236 break; 5237 case BO_Sub: 5238 if (!IsXLHSInRHSPart) 5239 return std::make_pair(false, RValue::get(nullptr)); 5240 RMWOp = llvm::AtomicRMWInst::Sub; 5241 break; 5242 case BO_And: 5243 RMWOp = llvm::AtomicRMWInst::And; 5244 break; 5245 case BO_Or: 5246 RMWOp = llvm::AtomicRMWInst::Or; 5247 break; 5248 case BO_Xor: 5249 RMWOp = llvm::AtomicRMWInst::Xor; 5250 break; 5251 case BO_LT: 5252 RMWOp = X.getType()->hasSignedIntegerRepresentation() 5253 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min 5254 : llvm::AtomicRMWInst::Max) 5255 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin 5256 : llvm::AtomicRMWInst::UMax); 5257 break; 5258 case BO_GT: 5259 RMWOp = X.getType()->hasSignedIntegerRepresentation() 5260 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max 5261 : llvm::AtomicRMWInst::Min) 5262 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax 5263 : llvm::AtomicRMWInst::UMin); 5264 break; 5265 case BO_Assign: 5266 RMWOp = llvm::AtomicRMWInst::Xchg; 5267 break; 5268 case BO_Mul: 5269 case BO_Div: 5270 case BO_Rem: 5271 case BO_Shl: 5272 case BO_Shr: 5273 case BO_LAnd: 5274 case BO_LOr: 5275 return std::make_pair(false, RValue::get(nullptr)); 5276 case BO_PtrMemD: 5277 case BO_PtrMemI: 5278 case BO_LE: 5279 case BO_GE: 5280 case BO_EQ: 5281 case BO_NE: 5282 case BO_Cmp: 5283 case BO_AddAssign: 5284 case BO_SubAssign: 5285 case BO_AndAssign: 5286 case BO_OrAssign: 5287 case BO_XorAssign: 5288 case BO_MulAssign: 5289 case BO_DivAssign: 5290 case BO_RemAssign: 5291 case BO_ShlAssign: 5292 case BO_ShrAssign: 5293 case BO_Comma: 5294 llvm_unreachable("Unsupported atomic update operation"); 5295 } 5296 llvm::Value *UpdateVal = Update.getScalarVal(); 5297 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) { 5298 UpdateVal = CGF.Builder.CreateIntCast( 5299 IC, X.getAddress(CGF).getElementType(), 5300 X.getType()->hasSignedIntegerRepresentation()); 5301 } 5302 llvm::Value *Res = 5303 CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(CGF), UpdateVal, AO); 5304 return std::make_pair(true, RValue::get(Res)); 5305 } 5306 5307 std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr( 5308 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart, 5309 llvm::AtomicOrdering AO, SourceLocation Loc, 5310 const llvm::function_ref<RValue(RValue)> CommonGen) { 5311 // Update expressions are allowed to have the following forms: 5312 // x binop= expr; -> xrval + expr; 5313 // x++, ++x -> xrval + 1; 5314 // x--, --x -> xrval - 1; 5315 // x = x binop expr; -> xrval binop expr 5316 // x = expr Op x; - > expr binop xrval; 5317 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart); 5318 if (!Res.first) { 5319 if (X.isGlobalReg()) { 5320 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop 5321 // 'xrval'. 5322 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X); 5323 } else { 5324 // Perform compare-and-swap procedure. 5325 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified()); 5326 } 5327 } 5328 return Res; 5329 } 5330 5331 static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF, 5332 llvm::AtomicOrdering AO, const Expr *X, 5333 const Expr *E, const Expr *UE, 5334 bool IsXLHSInRHSPart, SourceLocation Loc) { 5335 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) && 5336 "Update expr in 'atomic update' must be a binary operator."); 5337 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts()); 5338 // Update expressions are allowed to have the following forms: 5339 // x binop= expr; -> xrval + expr; 5340 // x++, ++x -> xrval + 1; 5341 // x--, --x -> xrval - 1; 5342 // x = x binop expr; -> xrval binop expr 5343 // x = expr Op x; - > expr binop xrval; 5344 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue"); 5345 LValue XLValue = CGF.EmitLValue(X); 5346 RValue ExprRValue = CGF.EmitAnyExpr(E); 5347 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts()); 5348 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts()); 5349 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS; 5350 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS; 5351 auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) { 5352 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 5353 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue); 5354 return CGF.EmitAnyExpr(UE); 5355 }; 5356 (void)CGF.EmitOMPAtomicSimpleUpdateExpr( 5357 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen); 5358 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 5359 // OpenMP, 2.17.7, atomic Construct 5360 // If the write, update, or capture clause is specified and the release, 5361 // acq_rel, or seq_cst clause is specified then the strong flush on entry to 5362 // the atomic operation is also a release flush. 5363 switch (AO) { 5364 case llvm::AtomicOrdering::Release: 5365 case llvm::AtomicOrdering::AcquireRelease: 5366 case llvm::AtomicOrdering::SequentiallyConsistent: 5367 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 5368 llvm::AtomicOrdering::Release); 5369 break; 5370 case llvm::AtomicOrdering::Acquire: 5371 case llvm::AtomicOrdering::Monotonic: 5372 break; 5373 case llvm::AtomicOrdering::NotAtomic: 5374 case llvm::AtomicOrdering::Unordered: 5375 llvm_unreachable("Unexpected ordering."); 5376 } 5377 } 5378 5379 static RValue convertToType(CodeGenFunction &CGF, RValue Value, 5380 QualType SourceType, QualType ResType, 5381 SourceLocation Loc) { 5382 switch (CGF.getEvaluationKind(ResType)) { 5383 case TEK_Scalar: 5384 return RValue::get( 5385 convertToScalarValue(CGF, Value, SourceType, ResType, Loc)); 5386 case TEK_Complex: { 5387 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc); 5388 return RValue::getComplex(Res.first, Res.second); 5389 } 5390 case TEK_Aggregate: 5391 break; 5392 } 5393 llvm_unreachable("Must be a scalar or complex."); 5394 } 5395 5396 static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF, 5397 llvm::AtomicOrdering AO, 5398 bool IsPostfixUpdate, const Expr *V, 5399 const Expr *X, const Expr *E, 5400 const Expr *UE, bool IsXLHSInRHSPart, 5401 SourceLocation Loc) { 5402 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue"); 5403 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue"); 5404 RValue NewVVal; 5405 LValue VLValue = CGF.EmitLValue(V); 5406 LValue XLValue = CGF.EmitLValue(X); 5407 RValue ExprRValue = CGF.EmitAnyExpr(E); 5408 QualType NewVValType; 5409 if (UE) { 5410 // 'x' is updated with some additional value. 5411 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) && 5412 "Update expr in 'atomic capture' must be a binary operator."); 5413 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts()); 5414 // Update expressions are allowed to have the following forms: 5415 // x binop= expr; -> xrval + expr; 5416 // x++, ++x -> xrval + 1; 5417 // x--, --x -> xrval - 1; 5418 // x = x binop expr; -> xrval binop expr 5419 // x = expr Op x; - > expr binop xrval; 5420 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts()); 5421 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts()); 5422 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS; 5423 NewVValType = XRValExpr->getType(); 5424 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS; 5425 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr, 5426 IsPostfixUpdate](RValue XRValue) { 5427 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 5428 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue); 5429 RValue Res = CGF.EmitAnyExpr(UE); 5430 NewVVal = IsPostfixUpdate ? XRValue : Res; 5431 return Res; 5432 }; 5433 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr( 5434 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen); 5435 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 5436 if (Res.first) { 5437 // 'atomicrmw' instruction was generated. 5438 if (IsPostfixUpdate) { 5439 // Use old value from 'atomicrmw'. 5440 NewVVal = Res.second; 5441 } else { 5442 // 'atomicrmw' does not provide new value, so evaluate it using old 5443 // value of 'x'. 5444 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 5445 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second); 5446 NewVVal = CGF.EmitAnyExpr(UE); 5447 } 5448 } 5449 } else { 5450 // 'x' is simply rewritten with some 'expr'. 5451 NewVValType = X->getType().getNonReferenceType(); 5452 ExprRValue = convertToType(CGF, ExprRValue, E->getType(), 5453 X->getType().getNonReferenceType(), Loc); 5454 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) { 5455 NewVVal = XRValue; 5456 return ExprRValue; 5457 }; 5458 // Try to perform atomicrmw xchg, otherwise simple exchange. 5459 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr( 5460 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO, 5461 Loc, Gen); 5462 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 5463 if (Res.first) { 5464 // 'atomicrmw' instruction was generated. 5465 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue; 5466 } 5467 } 5468 // Emit post-update store to 'v' of old/new 'x' value. 5469 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc); 5470 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V); 5471 // OpenMP, 2.17.7, atomic Construct 5472 // If the write, update, or capture clause is specified and the release, 5473 // acq_rel, or seq_cst clause is specified then the strong flush on entry to 5474 // the atomic operation is also a release flush. 5475 // If the read or capture clause is specified and the acquire, acq_rel, or 5476 // seq_cst clause is specified then the strong flush on exit from the atomic 5477 // operation is also an acquire flush. 5478 switch (AO) { 5479 case llvm::AtomicOrdering::Release: 5480 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 5481 llvm::AtomicOrdering::Release); 5482 break; 5483 case llvm::AtomicOrdering::Acquire: 5484 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 5485 llvm::AtomicOrdering::Acquire); 5486 break; 5487 case llvm::AtomicOrdering::AcquireRelease: 5488 case llvm::AtomicOrdering::SequentiallyConsistent: 5489 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 5490 llvm::AtomicOrdering::AcquireRelease); 5491 break; 5492 case llvm::AtomicOrdering::Monotonic: 5493 break; 5494 case llvm::AtomicOrdering::NotAtomic: 5495 case llvm::AtomicOrdering::Unordered: 5496 llvm_unreachable("Unexpected ordering."); 5497 } 5498 } 5499 5500 static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind, 5501 llvm::AtomicOrdering AO, bool IsPostfixUpdate, 5502 const Expr *X, const Expr *V, const Expr *E, 5503 const Expr *UE, bool IsXLHSInRHSPart, 5504 SourceLocation Loc) { 5505 switch (Kind) { 5506 case OMPC_read: 5507 emitOMPAtomicReadExpr(CGF, AO, X, V, Loc); 5508 break; 5509 case OMPC_write: 5510 emitOMPAtomicWriteExpr(CGF, AO, X, E, Loc); 5511 break; 5512 case OMPC_unknown: 5513 case OMPC_update: 5514 emitOMPAtomicUpdateExpr(CGF, AO, X, E, UE, IsXLHSInRHSPart, Loc); 5515 break; 5516 case OMPC_capture: 5517 emitOMPAtomicCaptureExpr(CGF, AO, IsPostfixUpdate, V, X, E, UE, 5518 IsXLHSInRHSPart, Loc); 5519 break; 5520 case OMPC_if: 5521 case OMPC_final: 5522 case OMPC_num_threads: 5523 case OMPC_private: 5524 case OMPC_firstprivate: 5525 case OMPC_lastprivate: 5526 case OMPC_reduction: 5527 case OMPC_task_reduction: 5528 case OMPC_in_reduction: 5529 case OMPC_safelen: 5530 case OMPC_simdlen: 5531 case OMPC_sizes: 5532 case OMPC_allocator: 5533 case OMPC_allocate: 5534 case OMPC_collapse: 5535 case OMPC_default: 5536 case OMPC_seq_cst: 5537 case OMPC_acq_rel: 5538 case OMPC_acquire: 5539 case OMPC_release: 5540 case OMPC_relaxed: 5541 case OMPC_shared: 5542 case OMPC_linear: 5543 case OMPC_aligned: 5544 case OMPC_copyin: 5545 case OMPC_copyprivate: 5546 case OMPC_flush: 5547 case OMPC_depobj: 5548 case OMPC_proc_bind: 5549 case OMPC_schedule: 5550 case OMPC_ordered: 5551 case OMPC_nowait: 5552 case OMPC_untied: 5553 case OMPC_threadprivate: 5554 case OMPC_depend: 5555 case OMPC_mergeable: 5556 case OMPC_device: 5557 case OMPC_threads: 5558 case OMPC_simd: 5559 case OMPC_map: 5560 case OMPC_num_teams: 5561 case OMPC_thread_limit: 5562 case OMPC_priority: 5563 case OMPC_grainsize: 5564 case OMPC_nogroup: 5565 case OMPC_num_tasks: 5566 case OMPC_hint: 5567 case OMPC_dist_schedule: 5568 case OMPC_defaultmap: 5569 case OMPC_uniform: 5570 case OMPC_to: 5571 case OMPC_from: 5572 case OMPC_use_device_ptr: 5573 case OMPC_use_device_addr: 5574 case OMPC_is_device_ptr: 5575 case OMPC_unified_address: 5576 case OMPC_unified_shared_memory: 5577 case OMPC_reverse_offload: 5578 case OMPC_dynamic_allocators: 5579 case OMPC_atomic_default_mem_order: 5580 case OMPC_device_type: 5581 case OMPC_match: 5582 case OMPC_nontemporal: 5583 case OMPC_order: 5584 case OMPC_destroy: 5585 case OMPC_detach: 5586 case OMPC_inclusive: 5587 case OMPC_exclusive: 5588 case OMPC_uses_allocators: 5589 case OMPC_affinity: 5590 default: 5591 llvm_unreachable("Clause is not allowed in 'omp atomic'."); 5592 } 5593 } 5594 5595 void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) { 5596 llvm::AtomicOrdering AO = llvm::AtomicOrdering::Monotonic; 5597 bool MemOrderingSpecified = false; 5598 if (S.getSingleClause<OMPSeqCstClause>()) { 5599 AO = llvm::AtomicOrdering::SequentiallyConsistent; 5600 MemOrderingSpecified = true; 5601 } else if (S.getSingleClause<OMPAcqRelClause>()) { 5602 AO = llvm::AtomicOrdering::AcquireRelease; 5603 MemOrderingSpecified = true; 5604 } else if (S.getSingleClause<OMPAcquireClause>()) { 5605 AO = llvm::AtomicOrdering::Acquire; 5606 MemOrderingSpecified = true; 5607 } else if (S.getSingleClause<OMPReleaseClause>()) { 5608 AO = llvm::AtomicOrdering::Release; 5609 MemOrderingSpecified = true; 5610 } else if (S.getSingleClause<OMPRelaxedClause>()) { 5611 AO = llvm::AtomicOrdering::Monotonic; 5612 MemOrderingSpecified = true; 5613 } 5614 OpenMPClauseKind Kind = OMPC_unknown; 5615 for (const OMPClause *C : S.clauses()) { 5616 // Find first clause (skip seq_cst|acq_rel|aqcuire|release|relaxed clause, 5617 // if it is first). 5618 if (C->getClauseKind() != OMPC_seq_cst && 5619 C->getClauseKind() != OMPC_acq_rel && 5620 C->getClauseKind() != OMPC_acquire && 5621 C->getClauseKind() != OMPC_release && 5622 C->getClauseKind() != OMPC_relaxed) { 5623 Kind = C->getClauseKind(); 5624 break; 5625 } 5626 } 5627 if (!MemOrderingSpecified) { 5628 llvm::AtomicOrdering DefaultOrder = 5629 CGM.getOpenMPRuntime().getDefaultMemoryOrdering(); 5630 if (DefaultOrder == llvm::AtomicOrdering::Monotonic || 5631 DefaultOrder == llvm::AtomicOrdering::SequentiallyConsistent || 5632 (DefaultOrder == llvm::AtomicOrdering::AcquireRelease && 5633 Kind == OMPC_capture)) { 5634 AO = DefaultOrder; 5635 } else if (DefaultOrder == llvm::AtomicOrdering::AcquireRelease) { 5636 if (Kind == OMPC_unknown || Kind == OMPC_update || Kind == OMPC_write) { 5637 AO = llvm::AtomicOrdering::Release; 5638 } else if (Kind == OMPC_read) { 5639 assert(Kind == OMPC_read && "Unexpected atomic kind."); 5640 AO = llvm::AtomicOrdering::Acquire; 5641 } 5642 } 5643 } 5644 5645 LexicalScope Scope(*this, S.getSourceRange()); 5646 EmitStopPoint(S.getAssociatedStmt()); 5647 emitOMPAtomicExpr(*this, Kind, AO, S.isPostfixUpdate(), S.getX(), S.getV(), 5648 S.getExpr(), S.getUpdateExpr(), S.isXLHSInRHSPart(), 5649 S.getBeginLoc()); 5650 } 5651 5652 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF, 5653 const OMPExecutableDirective &S, 5654 const RegionCodeGenTy &CodeGen) { 5655 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind())); 5656 CodeGenModule &CGM = CGF.CGM; 5657 5658 // On device emit this construct as inlined code. 5659 if (CGM.getLangOpts().OpenMPIsDevice) { 5660 OMPLexicalScope Scope(CGF, S, OMPD_target); 5661 CGM.getOpenMPRuntime().emitInlinedDirective( 5662 CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5663 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 5664 }); 5665 return; 5666 } 5667 5668 auto LPCRegion = 5669 CGOpenMPRuntime::LastprivateConditionalRAII::disable(CGF, S); 5670 llvm::Function *Fn = nullptr; 5671 llvm::Constant *FnID = nullptr; 5672 5673 const Expr *IfCond = nullptr; 5674 // Check for the at most one if clause associated with the target region. 5675 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 5676 if (C->getNameModifier() == OMPD_unknown || 5677 C->getNameModifier() == OMPD_target) { 5678 IfCond = C->getCondition(); 5679 break; 5680 } 5681 } 5682 5683 // Check if we have any device clause associated with the directive. 5684 llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device( 5685 nullptr, OMPC_DEVICE_unknown); 5686 if (auto *C = S.getSingleClause<OMPDeviceClause>()) 5687 Device.setPointerAndInt(C->getDevice(), C->getModifier()); 5688 5689 // Check if we have an if clause whose conditional always evaluates to false 5690 // or if we do not have any targets specified. If so the target region is not 5691 // an offload entry point. 5692 bool IsOffloadEntry = true; 5693 if (IfCond) { 5694 bool Val; 5695 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val) 5696 IsOffloadEntry = false; 5697 } 5698 if (CGM.getLangOpts().OMPTargetTriples.empty()) 5699 IsOffloadEntry = false; 5700 5701 assert(CGF.CurFuncDecl && "No parent declaration for target region!"); 5702 StringRef ParentName; 5703 // In case we have Ctors/Dtors we use the complete type variant to produce 5704 // the mangling of the device outlined kernel. 5705 if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl)) 5706 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete)); 5707 else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl)) 5708 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete)); 5709 else 5710 ParentName = 5711 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl))); 5712 5713 // Emit target region as a standalone region. 5714 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID, 5715 IsOffloadEntry, CodeGen); 5716 OMPLexicalScope Scope(CGF, S, OMPD_task); 5717 auto &&SizeEmitter = 5718 [IsOffloadEntry](CodeGenFunction &CGF, 5719 const OMPLoopDirective &D) -> llvm::Value * { 5720 if (IsOffloadEntry) { 5721 OMPLoopScope(CGF, D); 5722 // Emit calculation of the iterations count. 5723 llvm::Value *NumIterations = CGF.EmitScalarExpr(D.getNumIterations()); 5724 NumIterations = CGF.Builder.CreateIntCast(NumIterations, CGF.Int64Ty, 5725 /*isSigned=*/false); 5726 return NumIterations; 5727 } 5728 return nullptr; 5729 }; 5730 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device, 5731 SizeEmitter); 5732 } 5733 5734 static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S, 5735 PrePostActionTy &Action) { 5736 Action.Enter(CGF); 5737 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 5738 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 5739 CGF.EmitOMPPrivateClause(S, PrivateScope); 5740 (void)PrivateScope.Privatize(); 5741 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 5742 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 5743 5744 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt()); 5745 CGF.EnsureInsertPoint(); 5746 } 5747 5748 void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM, 5749 StringRef ParentName, 5750 const OMPTargetDirective &S) { 5751 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5752 emitTargetRegion(CGF, S, Action); 5753 }; 5754 llvm::Function *Fn; 5755 llvm::Constant *Addr; 5756 // Emit target region as a standalone region. 5757 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 5758 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 5759 assert(Fn && Addr && "Target device function emission failed."); 5760 } 5761 5762 void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) { 5763 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5764 emitTargetRegion(CGF, S, Action); 5765 }; 5766 emitCommonOMPTargetDirective(*this, S, CodeGen); 5767 } 5768 5769 static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF, 5770 const OMPExecutableDirective &S, 5771 OpenMPDirectiveKind InnermostKind, 5772 const RegionCodeGenTy &CodeGen) { 5773 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams); 5774 llvm::Function *OutlinedFn = 5775 CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction( 5776 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen); 5777 5778 const auto *NT = S.getSingleClause<OMPNumTeamsClause>(); 5779 const auto *TL = S.getSingleClause<OMPThreadLimitClause>(); 5780 if (NT || TL) { 5781 const Expr *NumTeams = NT ? NT->getNumTeams() : nullptr; 5782 const Expr *ThreadLimit = TL ? TL->getThreadLimit() : nullptr; 5783 5784 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit, 5785 S.getBeginLoc()); 5786 } 5787 5788 OMPTeamsScope Scope(CGF, S); 5789 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 5790 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars); 5791 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn, 5792 CapturedVars); 5793 } 5794 5795 void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) { 5796 // Emit teams region as a standalone region. 5797 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5798 Action.Enter(CGF); 5799 OMPPrivateScope PrivateScope(CGF); 5800 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 5801 CGF.EmitOMPPrivateClause(S, PrivateScope); 5802 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 5803 (void)PrivateScope.Privatize(); 5804 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt()); 5805 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 5806 }; 5807 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen); 5808 emitPostUpdateForReductionClause(*this, S, 5809 [](CodeGenFunction &) { return nullptr; }); 5810 } 5811 5812 static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action, 5813 const OMPTargetTeamsDirective &S) { 5814 auto *CS = S.getCapturedStmt(OMPD_teams); 5815 Action.Enter(CGF); 5816 // Emit teams region as a standalone region. 5817 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) { 5818 Action.Enter(CGF); 5819 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 5820 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 5821 CGF.EmitOMPPrivateClause(S, PrivateScope); 5822 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 5823 (void)PrivateScope.Privatize(); 5824 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 5825 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 5826 CGF.EmitStmt(CS->getCapturedStmt()); 5827 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 5828 }; 5829 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen); 5830 emitPostUpdateForReductionClause(CGF, S, 5831 [](CodeGenFunction &) { return nullptr; }); 5832 } 5833 5834 void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction( 5835 CodeGenModule &CGM, StringRef ParentName, 5836 const OMPTargetTeamsDirective &S) { 5837 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5838 emitTargetTeamsRegion(CGF, Action, S); 5839 }; 5840 llvm::Function *Fn; 5841 llvm::Constant *Addr; 5842 // Emit target region as a standalone region. 5843 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 5844 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 5845 assert(Fn && Addr && "Target device function emission failed."); 5846 } 5847 5848 void CodeGenFunction::EmitOMPTargetTeamsDirective( 5849 const OMPTargetTeamsDirective &S) { 5850 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5851 emitTargetTeamsRegion(CGF, Action, S); 5852 }; 5853 emitCommonOMPTargetDirective(*this, S, CodeGen); 5854 } 5855 5856 static void 5857 emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action, 5858 const OMPTargetTeamsDistributeDirective &S) { 5859 Action.Enter(CGF); 5860 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5861 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 5862 }; 5863 5864 // Emit teams region as a standalone region. 5865 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 5866 PrePostActionTy &Action) { 5867 Action.Enter(CGF); 5868 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 5869 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 5870 (void)PrivateScope.Privatize(); 5871 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 5872 CodeGenDistribute); 5873 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 5874 }; 5875 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen); 5876 emitPostUpdateForReductionClause(CGF, S, 5877 [](CodeGenFunction &) { return nullptr; }); 5878 } 5879 5880 void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction( 5881 CodeGenModule &CGM, StringRef ParentName, 5882 const OMPTargetTeamsDistributeDirective &S) { 5883 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5884 emitTargetTeamsDistributeRegion(CGF, Action, S); 5885 }; 5886 llvm::Function *Fn; 5887 llvm::Constant *Addr; 5888 // Emit target region as a standalone region. 5889 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 5890 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 5891 assert(Fn && Addr && "Target device function emission failed."); 5892 } 5893 5894 void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective( 5895 const OMPTargetTeamsDistributeDirective &S) { 5896 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5897 emitTargetTeamsDistributeRegion(CGF, Action, S); 5898 }; 5899 emitCommonOMPTargetDirective(*this, S, CodeGen); 5900 } 5901 5902 static void emitTargetTeamsDistributeSimdRegion( 5903 CodeGenFunction &CGF, PrePostActionTy &Action, 5904 const OMPTargetTeamsDistributeSimdDirective &S) { 5905 Action.Enter(CGF); 5906 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5907 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 5908 }; 5909 5910 // Emit teams region as a standalone region. 5911 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 5912 PrePostActionTy &Action) { 5913 Action.Enter(CGF); 5914 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 5915 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 5916 (void)PrivateScope.Privatize(); 5917 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 5918 CodeGenDistribute); 5919 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 5920 }; 5921 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen); 5922 emitPostUpdateForReductionClause(CGF, S, 5923 [](CodeGenFunction &) { return nullptr; }); 5924 } 5925 5926 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction( 5927 CodeGenModule &CGM, StringRef ParentName, 5928 const OMPTargetTeamsDistributeSimdDirective &S) { 5929 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5930 emitTargetTeamsDistributeSimdRegion(CGF, Action, S); 5931 }; 5932 llvm::Function *Fn; 5933 llvm::Constant *Addr; 5934 // Emit target region as a standalone region. 5935 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 5936 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 5937 assert(Fn && Addr && "Target device function emission failed."); 5938 } 5939 5940 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective( 5941 const OMPTargetTeamsDistributeSimdDirective &S) { 5942 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5943 emitTargetTeamsDistributeSimdRegion(CGF, Action, S); 5944 }; 5945 emitCommonOMPTargetDirective(*this, S, CodeGen); 5946 } 5947 5948 void CodeGenFunction::EmitOMPTeamsDistributeDirective( 5949 const OMPTeamsDistributeDirective &S) { 5950 5951 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5952 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 5953 }; 5954 5955 // Emit teams region as a standalone region. 5956 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 5957 PrePostActionTy &Action) { 5958 Action.Enter(CGF); 5959 OMPPrivateScope PrivateScope(CGF); 5960 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 5961 (void)PrivateScope.Privatize(); 5962 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 5963 CodeGenDistribute); 5964 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 5965 }; 5966 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen); 5967 emitPostUpdateForReductionClause(*this, S, 5968 [](CodeGenFunction &) { return nullptr; }); 5969 } 5970 5971 void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective( 5972 const OMPTeamsDistributeSimdDirective &S) { 5973 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5974 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 5975 }; 5976 5977 // Emit teams region as a standalone region. 5978 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 5979 PrePostActionTy &Action) { 5980 Action.Enter(CGF); 5981 OMPPrivateScope PrivateScope(CGF); 5982 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 5983 (void)PrivateScope.Privatize(); 5984 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd, 5985 CodeGenDistribute); 5986 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 5987 }; 5988 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen); 5989 emitPostUpdateForReductionClause(*this, S, 5990 [](CodeGenFunction &) { return nullptr; }); 5991 } 5992 5993 void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective( 5994 const OMPTeamsDistributeParallelForDirective &S) { 5995 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5996 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 5997 S.getDistInc()); 5998 }; 5999 6000 // Emit teams region as a standalone region. 6001 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 6002 PrePostActionTy &Action) { 6003 Action.Enter(CGF); 6004 OMPPrivateScope PrivateScope(CGF); 6005 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6006 (void)PrivateScope.Privatize(); 6007 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 6008 CodeGenDistribute); 6009 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6010 }; 6011 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen); 6012 emitPostUpdateForReductionClause(*this, S, 6013 [](CodeGenFunction &) { return nullptr; }); 6014 } 6015 6016 void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective( 6017 const OMPTeamsDistributeParallelForSimdDirective &S) { 6018 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6019 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 6020 S.getDistInc()); 6021 }; 6022 6023 // Emit teams region as a standalone region. 6024 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 6025 PrePostActionTy &Action) { 6026 Action.Enter(CGF); 6027 OMPPrivateScope PrivateScope(CGF); 6028 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6029 (void)PrivateScope.Privatize(); 6030 CGF.CGM.getOpenMPRuntime().emitInlinedDirective( 6031 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false); 6032 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6033 }; 6034 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for_simd, 6035 CodeGen); 6036 emitPostUpdateForReductionClause(*this, S, 6037 [](CodeGenFunction &) { return nullptr; }); 6038 } 6039 6040 static void emitTargetTeamsDistributeParallelForRegion( 6041 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S, 6042 PrePostActionTy &Action) { 6043 Action.Enter(CGF); 6044 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6045 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 6046 S.getDistInc()); 6047 }; 6048 6049 // Emit teams region as a standalone region. 6050 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 6051 PrePostActionTy &Action) { 6052 Action.Enter(CGF); 6053 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 6054 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6055 (void)PrivateScope.Privatize(); 6056 CGF.CGM.getOpenMPRuntime().emitInlinedDirective( 6057 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false); 6058 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6059 }; 6060 6061 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for, 6062 CodeGenTeams); 6063 emitPostUpdateForReductionClause(CGF, S, 6064 [](CodeGenFunction &) { return nullptr; }); 6065 } 6066 6067 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction( 6068 CodeGenModule &CGM, StringRef ParentName, 6069 const OMPTargetTeamsDistributeParallelForDirective &S) { 6070 // Emit SPMD target teams distribute parallel for region as a standalone 6071 // region. 6072 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6073 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action); 6074 }; 6075 llvm::Function *Fn; 6076 llvm::Constant *Addr; 6077 // Emit target region as a standalone region. 6078 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 6079 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 6080 assert(Fn && Addr && "Target device function emission failed."); 6081 } 6082 6083 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective( 6084 const OMPTargetTeamsDistributeParallelForDirective &S) { 6085 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6086 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action); 6087 }; 6088 emitCommonOMPTargetDirective(*this, S, CodeGen); 6089 } 6090 6091 static void emitTargetTeamsDistributeParallelForSimdRegion( 6092 CodeGenFunction &CGF, 6093 const OMPTargetTeamsDistributeParallelForSimdDirective &S, 6094 PrePostActionTy &Action) { 6095 Action.Enter(CGF); 6096 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6097 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 6098 S.getDistInc()); 6099 }; 6100 6101 // Emit teams region as a standalone region. 6102 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 6103 PrePostActionTy &Action) { 6104 Action.Enter(CGF); 6105 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 6106 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6107 (void)PrivateScope.Privatize(); 6108 CGF.CGM.getOpenMPRuntime().emitInlinedDirective( 6109 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false); 6110 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6111 }; 6112 6113 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd, 6114 CodeGenTeams); 6115 emitPostUpdateForReductionClause(CGF, S, 6116 [](CodeGenFunction &) { return nullptr; }); 6117 } 6118 6119 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction( 6120 CodeGenModule &CGM, StringRef ParentName, 6121 const OMPTargetTeamsDistributeParallelForSimdDirective &S) { 6122 // Emit SPMD target teams distribute parallel for simd region as a standalone 6123 // region. 6124 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6125 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action); 6126 }; 6127 llvm::Function *Fn; 6128 llvm::Constant *Addr; 6129 // Emit target region as a standalone region. 6130 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 6131 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 6132 assert(Fn && Addr && "Target device function emission failed."); 6133 } 6134 6135 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective( 6136 const OMPTargetTeamsDistributeParallelForSimdDirective &S) { 6137 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6138 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action); 6139 }; 6140 emitCommonOMPTargetDirective(*this, S, CodeGen); 6141 } 6142 6143 void CodeGenFunction::EmitOMPCancellationPointDirective( 6144 const OMPCancellationPointDirective &S) { 6145 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(), 6146 S.getCancelRegion()); 6147 } 6148 6149 void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) { 6150 const Expr *IfCond = nullptr; 6151 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 6152 if (C->getNameModifier() == OMPD_unknown || 6153 C->getNameModifier() == OMPD_cancel) { 6154 IfCond = C->getCondition(); 6155 break; 6156 } 6157 } 6158 if (CGM.getLangOpts().OpenMPIRBuilder) { 6159 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 6160 // TODO: This check is necessary as we only generate `omp parallel` through 6161 // the OpenMPIRBuilder for now. 6162 if (S.getCancelRegion() == OMPD_parallel) { 6163 llvm::Value *IfCondition = nullptr; 6164 if (IfCond) 6165 IfCondition = EmitScalarExpr(IfCond, 6166 /*IgnoreResultAssign=*/true); 6167 return Builder.restoreIP( 6168 OMPBuilder.createCancel(Builder, IfCondition, S.getCancelRegion())); 6169 } 6170 } 6171 6172 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond, 6173 S.getCancelRegion()); 6174 } 6175 6176 CodeGenFunction::JumpDest 6177 CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) { 6178 if (Kind == OMPD_parallel || Kind == OMPD_task || 6179 Kind == OMPD_target_parallel || Kind == OMPD_taskloop || 6180 Kind == OMPD_master_taskloop || Kind == OMPD_parallel_master_taskloop) 6181 return ReturnBlock; 6182 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections || 6183 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for || 6184 Kind == OMPD_distribute_parallel_for || 6185 Kind == OMPD_target_parallel_for || 6186 Kind == OMPD_teams_distribute_parallel_for || 6187 Kind == OMPD_target_teams_distribute_parallel_for); 6188 return OMPCancelStack.getExitBlock(); 6189 } 6190 6191 void CodeGenFunction::EmitOMPUseDevicePtrClause( 6192 const OMPUseDevicePtrClause &C, OMPPrivateScope &PrivateScope, 6193 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) { 6194 auto OrigVarIt = C.varlist_begin(); 6195 auto InitIt = C.inits().begin(); 6196 for (const Expr *PvtVarIt : C.private_copies()) { 6197 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl()); 6198 const auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl()); 6199 const auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl()); 6200 6201 // In order to identify the right initializer we need to match the 6202 // declaration used by the mapping logic. In some cases we may get 6203 // OMPCapturedExprDecl that refers to the original declaration. 6204 const ValueDecl *MatchingVD = OrigVD; 6205 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) { 6206 // OMPCapturedExprDecl are used to privative fields of the current 6207 // structure. 6208 const auto *ME = cast<MemberExpr>(OED->getInit()); 6209 assert(isa<CXXThisExpr>(ME->getBase()) && 6210 "Base should be the current struct!"); 6211 MatchingVD = ME->getMemberDecl(); 6212 } 6213 6214 // If we don't have information about the current list item, move on to 6215 // the next one. 6216 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD); 6217 if (InitAddrIt == CaptureDeviceAddrMap.end()) 6218 continue; 6219 6220 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, OrigVD, 6221 InitAddrIt, InitVD, 6222 PvtVD]() { 6223 // Initialize the temporary initialization variable with the address we 6224 // get from the runtime library. We have to cast the source address 6225 // because it is always a void *. References are materialized in the 6226 // privatization scope, so the initialization here disregards the fact 6227 // the original variable is a reference. 6228 QualType AddrQTy = 6229 getContext().getPointerType(OrigVD->getType().getNonReferenceType()); 6230 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy); 6231 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy); 6232 setAddrOfLocalVar(InitVD, InitAddr); 6233 6234 // Emit private declaration, it will be initialized by the value we 6235 // declaration we just added to the local declarations map. 6236 EmitDecl(*PvtVD); 6237 6238 // The initialization variables reached its purpose in the emission 6239 // of the previous declaration, so we don't need it anymore. 6240 LocalDeclMap.erase(InitVD); 6241 6242 // Return the address of the private variable. 6243 return GetAddrOfLocalVar(PvtVD); 6244 }); 6245 assert(IsRegistered && "firstprivate var already registered as private"); 6246 // Silence the warning about unused variable. 6247 (void)IsRegistered; 6248 6249 ++OrigVarIt; 6250 ++InitIt; 6251 } 6252 } 6253 6254 static const VarDecl *getBaseDecl(const Expr *Ref) { 6255 const Expr *Base = Ref->IgnoreParenImpCasts(); 6256 while (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Base)) 6257 Base = OASE->getBase()->IgnoreParenImpCasts(); 6258 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Base)) 6259 Base = ASE->getBase()->IgnoreParenImpCasts(); 6260 return cast<VarDecl>(cast<DeclRefExpr>(Base)->getDecl()); 6261 } 6262 6263 void CodeGenFunction::EmitOMPUseDeviceAddrClause( 6264 const OMPUseDeviceAddrClause &C, OMPPrivateScope &PrivateScope, 6265 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) { 6266 llvm::SmallDenseSet<CanonicalDeclPtr<const Decl>, 4> Processed; 6267 for (const Expr *Ref : C.varlists()) { 6268 const VarDecl *OrigVD = getBaseDecl(Ref); 6269 if (!Processed.insert(OrigVD).second) 6270 continue; 6271 // In order to identify the right initializer we need to match the 6272 // declaration used by the mapping logic. In some cases we may get 6273 // OMPCapturedExprDecl that refers to the original declaration. 6274 const ValueDecl *MatchingVD = OrigVD; 6275 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) { 6276 // OMPCapturedExprDecl are used to privative fields of the current 6277 // structure. 6278 const auto *ME = cast<MemberExpr>(OED->getInit()); 6279 assert(isa<CXXThisExpr>(ME->getBase()) && 6280 "Base should be the current struct!"); 6281 MatchingVD = ME->getMemberDecl(); 6282 } 6283 6284 // If we don't have information about the current list item, move on to 6285 // the next one. 6286 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD); 6287 if (InitAddrIt == CaptureDeviceAddrMap.end()) 6288 continue; 6289 6290 Address PrivAddr = InitAddrIt->getSecond(); 6291 // For declrefs and variable length array need to load the pointer for 6292 // correct mapping, since the pointer to the data was passed to the runtime. 6293 if (isa<DeclRefExpr>(Ref->IgnoreParenImpCasts()) || 6294 MatchingVD->getType()->isArrayType()) 6295 PrivAddr = 6296 EmitLoadOfPointer(PrivAddr, getContext() 6297 .getPointerType(OrigVD->getType()) 6298 ->castAs<PointerType>()); 6299 llvm::Type *RealTy = 6300 ConvertTypeForMem(OrigVD->getType().getNonReferenceType()) 6301 ->getPointerTo(); 6302 PrivAddr = Builder.CreatePointerBitCastOrAddrSpaceCast(PrivAddr, RealTy); 6303 6304 (void)PrivateScope.addPrivate(OrigVD, [PrivAddr]() { return PrivAddr; }); 6305 } 6306 } 6307 6308 // Generate the instructions for '#pragma omp target data' directive. 6309 void CodeGenFunction::EmitOMPTargetDataDirective( 6310 const OMPTargetDataDirective &S) { 6311 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true, 6312 /*SeparateBeginEndCalls=*/true); 6313 6314 // Create a pre/post action to signal the privatization of the device pointer. 6315 // This action can be replaced by the OpenMP runtime code generation to 6316 // deactivate privatization. 6317 bool PrivatizeDevicePointers = false; 6318 class DevicePointerPrivActionTy : public PrePostActionTy { 6319 bool &PrivatizeDevicePointers; 6320 6321 public: 6322 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers) 6323 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {} 6324 void Enter(CodeGenFunction &CGF) override { 6325 PrivatizeDevicePointers = true; 6326 } 6327 }; 6328 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers); 6329 6330 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers]( 6331 CodeGenFunction &CGF, PrePostActionTy &Action) { 6332 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6333 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 6334 }; 6335 6336 // Codegen that selects whether to generate the privatization code or not. 6337 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers, 6338 &InnermostCodeGen](CodeGenFunction &CGF, 6339 PrePostActionTy &Action) { 6340 RegionCodeGenTy RCG(InnermostCodeGen); 6341 PrivatizeDevicePointers = false; 6342 6343 // Call the pre-action to change the status of PrivatizeDevicePointers if 6344 // needed. 6345 Action.Enter(CGF); 6346 6347 if (PrivatizeDevicePointers) { 6348 OMPPrivateScope PrivateScope(CGF); 6349 // Emit all instances of the use_device_ptr clause. 6350 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>()) 6351 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope, 6352 Info.CaptureDeviceAddrMap); 6353 for (const auto *C : S.getClausesOfKind<OMPUseDeviceAddrClause>()) 6354 CGF.EmitOMPUseDeviceAddrClause(*C, PrivateScope, 6355 Info.CaptureDeviceAddrMap); 6356 (void)PrivateScope.Privatize(); 6357 RCG(CGF); 6358 } else { 6359 OMPLexicalScope Scope(CGF, S, OMPD_unknown); 6360 RCG(CGF); 6361 } 6362 }; 6363 6364 // Forward the provided action to the privatization codegen. 6365 RegionCodeGenTy PrivRCG(PrivCodeGen); 6366 PrivRCG.setAction(Action); 6367 6368 // Notwithstanding the body of the region is emitted as inlined directive, 6369 // we don't use an inline scope as changes in the references inside the 6370 // region are expected to be visible outside, so we do not privative them. 6371 OMPLexicalScope Scope(CGF, S); 6372 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data, 6373 PrivRCG); 6374 }; 6375 6376 RegionCodeGenTy RCG(CodeGen); 6377 6378 // If we don't have target devices, don't bother emitting the data mapping 6379 // code. 6380 if (CGM.getLangOpts().OMPTargetTriples.empty()) { 6381 RCG(*this); 6382 return; 6383 } 6384 6385 // Check if we have any if clause associated with the directive. 6386 const Expr *IfCond = nullptr; 6387 if (const auto *C = S.getSingleClause<OMPIfClause>()) 6388 IfCond = C->getCondition(); 6389 6390 // Check if we have any device clause associated with the directive. 6391 const Expr *Device = nullptr; 6392 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 6393 Device = C->getDevice(); 6394 6395 // Set the action to signal privatization of device pointers. 6396 RCG.setAction(PrivAction); 6397 6398 // Emit region code. 6399 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG, 6400 Info); 6401 } 6402 6403 void CodeGenFunction::EmitOMPTargetEnterDataDirective( 6404 const OMPTargetEnterDataDirective &S) { 6405 // If we don't have target devices, don't bother emitting the data mapping 6406 // code. 6407 if (CGM.getLangOpts().OMPTargetTriples.empty()) 6408 return; 6409 6410 // Check if we have any if clause associated with the directive. 6411 const Expr *IfCond = nullptr; 6412 if (const auto *C = S.getSingleClause<OMPIfClause>()) 6413 IfCond = C->getCondition(); 6414 6415 // Check if we have any device clause associated with the directive. 6416 const Expr *Device = nullptr; 6417 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 6418 Device = C->getDevice(); 6419 6420 OMPLexicalScope Scope(*this, S, OMPD_task); 6421 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device); 6422 } 6423 6424 void CodeGenFunction::EmitOMPTargetExitDataDirective( 6425 const OMPTargetExitDataDirective &S) { 6426 // If we don't have target devices, don't bother emitting the data mapping 6427 // code. 6428 if (CGM.getLangOpts().OMPTargetTriples.empty()) 6429 return; 6430 6431 // Check if we have any if clause associated with the directive. 6432 const Expr *IfCond = nullptr; 6433 if (const auto *C = S.getSingleClause<OMPIfClause>()) 6434 IfCond = C->getCondition(); 6435 6436 // Check if we have any device clause associated with the directive. 6437 const Expr *Device = nullptr; 6438 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 6439 Device = C->getDevice(); 6440 6441 OMPLexicalScope Scope(*this, S, OMPD_task); 6442 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device); 6443 } 6444 6445 static void emitTargetParallelRegion(CodeGenFunction &CGF, 6446 const OMPTargetParallelDirective &S, 6447 PrePostActionTy &Action) { 6448 // Get the captured statement associated with the 'parallel' region. 6449 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel); 6450 Action.Enter(CGF); 6451 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) { 6452 Action.Enter(CGF); 6453 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 6454 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 6455 CGF.EmitOMPPrivateClause(S, PrivateScope); 6456 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6457 (void)PrivateScope.Privatize(); 6458 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 6459 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 6460 // TODO: Add support for clauses. 6461 CGF.EmitStmt(CS->getCapturedStmt()); 6462 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 6463 }; 6464 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen, 6465 emitEmptyBoundParameters); 6466 emitPostUpdateForReductionClause(CGF, S, 6467 [](CodeGenFunction &) { return nullptr; }); 6468 } 6469 6470 void CodeGenFunction::EmitOMPTargetParallelDeviceFunction( 6471 CodeGenModule &CGM, StringRef ParentName, 6472 const OMPTargetParallelDirective &S) { 6473 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6474 emitTargetParallelRegion(CGF, S, Action); 6475 }; 6476 llvm::Function *Fn; 6477 llvm::Constant *Addr; 6478 // Emit target region as a standalone region. 6479 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 6480 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 6481 assert(Fn && Addr && "Target device function emission failed."); 6482 } 6483 6484 void CodeGenFunction::EmitOMPTargetParallelDirective( 6485 const OMPTargetParallelDirective &S) { 6486 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6487 emitTargetParallelRegion(CGF, S, Action); 6488 }; 6489 emitCommonOMPTargetDirective(*this, S, CodeGen); 6490 } 6491 6492 static void emitTargetParallelForRegion(CodeGenFunction &CGF, 6493 const OMPTargetParallelForDirective &S, 6494 PrePostActionTy &Action) { 6495 Action.Enter(CGF); 6496 // Emit directive as a combined directive that consists of two implicit 6497 // directives: 'parallel' with 'for' directive. 6498 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6499 Action.Enter(CGF); 6500 CodeGenFunction::OMPCancelStackRAII CancelRegion( 6501 CGF, OMPD_target_parallel_for, S.hasCancel()); 6502 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds, 6503 emitDispatchForLoopBounds); 6504 }; 6505 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen, 6506 emitEmptyBoundParameters); 6507 } 6508 6509 void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction( 6510 CodeGenModule &CGM, StringRef ParentName, 6511 const OMPTargetParallelForDirective &S) { 6512 // Emit SPMD target parallel for region as a standalone region. 6513 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6514 emitTargetParallelForRegion(CGF, S, Action); 6515 }; 6516 llvm::Function *Fn; 6517 llvm::Constant *Addr; 6518 // Emit target region as a standalone region. 6519 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 6520 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 6521 assert(Fn && Addr && "Target device function emission failed."); 6522 } 6523 6524 void CodeGenFunction::EmitOMPTargetParallelForDirective( 6525 const OMPTargetParallelForDirective &S) { 6526 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6527 emitTargetParallelForRegion(CGF, S, Action); 6528 }; 6529 emitCommonOMPTargetDirective(*this, S, CodeGen); 6530 } 6531 6532 static void 6533 emitTargetParallelForSimdRegion(CodeGenFunction &CGF, 6534 const OMPTargetParallelForSimdDirective &S, 6535 PrePostActionTy &Action) { 6536 Action.Enter(CGF); 6537 // Emit directive as a combined directive that consists of two implicit 6538 // directives: 'parallel' with 'for' directive. 6539 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6540 Action.Enter(CGF); 6541 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds, 6542 emitDispatchForLoopBounds); 6543 }; 6544 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen, 6545 emitEmptyBoundParameters); 6546 } 6547 6548 void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction( 6549 CodeGenModule &CGM, StringRef ParentName, 6550 const OMPTargetParallelForSimdDirective &S) { 6551 // Emit SPMD target parallel for region as a standalone region. 6552 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6553 emitTargetParallelForSimdRegion(CGF, S, Action); 6554 }; 6555 llvm::Function *Fn; 6556 llvm::Constant *Addr; 6557 // Emit target region as a standalone region. 6558 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 6559 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 6560 assert(Fn && Addr && "Target device function emission failed."); 6561 } 6562 6563 void CodeGenFunction::EmitOMPTargetParallelForSimdDirective( 6564 const OMPTargetParallelForSimdDirective &S) { 6565 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6566 emitTargetParallelForSimdRegion(CGF, S, Action); 6567 }; 6568 emitCommonOMPTargetDirective(*this, S, CodeGen); 6569 } 6570 6571 /// Emit a helper variable and return corresponding lvalue. 6572 static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper, 6573 const ImplicitParamDecl *PVD, 6574 CodeGenFunction::OMPPrivateScope &Privates) { 6575 const auto *VDecl = cast<VarDecl>(Helper->getDecl()); 6576 Privates.addPrivate(VDecl, 6577 [&CGF, PVD]() { return CGF.GetAddrOfLocalVar(PVD); }); 6578 } 6579 6580 void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) { 6581 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind())); 6582 // Emit outlined function for task construct. 6583 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop); 6584 Address CapturedStruct = Address::invalid(); 6585 { 6586 OMPLexicalScope Scope(*this, S, OMPD_taskloop, /*EmitPreInitStmt=*/false); 6587 CapturedStruct = GenerateCapturedStmtArgument(*CS); 6588 } 6589 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 6590 const Expr *IfCond = nullptr; 6591 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 6592 if (C->getNameModifier() == OMPD_unknown || 6593 C->getNameModifier() == OMPD_taskloop) { 6594 IfCond = C->getCondition(); 6595 break; 6596 } 6597 } 6598 6599 OMPTaskDataTy Data; 6600 // Check if taskloop must be emitted without taskgroup. 6601 Data.Nogroup = S.getSingleClause<OMPNogroupClause>(); 6602 // TODO: Check if we should emit tied or untied task. 6603 Data.Tied = true; 6604 // Set scheduling for taskloop 6605 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) { 6606 // grainsize clause 6607 Data.Schedule.setInt(/*IntVal=*/false); 6608 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize())); 6609 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) { 6610 // num_tasks clause 6611 Data.Schedule.setInt(/*IntVal=*/true); 6612 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks())); 6613 } 6614 6615 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) { 6616 // if (PreCond) { 6617 // for (IV in 0..LastIteration) BODY; 6618 // <Final counter/linear vars updates>; 6619 // } 6620 // 6621 6622 // Emit: if (PreCond) - begin. 6623 // If the condition constant folds and can be elided, avoid emitting the 6624 // whole loop. 6625 bool CondConstant; 6626 llvm::BasicBlock *ContBlock = nullptr; 6627 OMPLoopScope PreInitScope(CGF, S); 6628 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 6629 if (!CondConstant) 6630 return; 6631 } else { 6632 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then"); 6633 ContBlock = CGF.createBasicBlock("taskloop.if.end"); 6634 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock, 6635 CGF.getProfileCount(&S)); 6636 CGF.EmitBlock(ThenBlock); 6637 CGF.incrementProfileCounter(&S); 6638 } 6639 6640 (void)CGF.EmitOMPLinearClauseInit(S); 6641 6642 OMPPrivateScope LoopScope(CGF); 6643 // Emit helper vars inits. 6644 enum { LowerBound = 5, UpperBound, Stride, LastIter }; 6645 auto *I = CS->getCapturedDecl()->param_begin(); 6646 auto *LBP = std::next(I, LowerBound); 6647 auto *UBP = std::next(I, UpperBound); 6648 auto *STP = std::next(I, Stride); 6649 auto *LIP = std::next(I, LastIter); 6650 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP, 6651 LoopScope); 6652 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP, 6653 LoopScope); 6654 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope); 6655 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP, 6656 LoopScope); 6657 CGF.EmitOMPPrivateLoopCounters(S, LoopScope); 6658 CGF.EmitOMPLinearClause(S, LoopScope); 6659 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 6660 (void)LoopScope.Privatize(); 6661 // Emit the loop iteration variable. 6662 const Expr *IVExpr = S.getIterationVariable(); 6663 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl()); 6664 CGF.EmitVarDecl(*IVDecl); 6665 CGF.EmitIgnoredExpr(S.getInit()); 6666 6667 // Emit the iterations count variable. 6668 // If it is not a variable, Sema decided to calculate iterations count on 6669 // each iteration (e.g., it is foldable into a constant). 6670 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 6671 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 6672 // Emit calculation of the iterations count. 6673 CGF.EmitIgnoredExpr(S.getCalcLastIteration()); 6674 } 6675 6676 { 6677 OMPLexicalScope Scope(CGF, S, OMPD_taskloop, /*EmitPreInitStmt=*/false); 6678 emitCommonSimdLoop( 6679 CGF, S, 6680 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6681 if (isOpenMPSimdDirective(S.getDirectiveKind())) 6682 CGF.EmitOMPSimdInit(S); 6683 }, 6684 [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) { 6685 CGF.EmitOMPInnerLoop( 6686 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(), 6687 [&S](CodeGenFunction &CGF) { 6688 emitOMPLoopBodyWithStopPoint(CGF, S, 6689 CodeGenFunction::JumpDest()); 6690 }, 6691 [](CodeGenFunction &) {}); 6692 }); 6693 } 6694 // Emit: if (PreCond) - end. 6695 if (ContBlock) { 6696 CGF.EmitBranch(ContBlock); 6697 CGF.EmitBlock(ContBlock, true); 6698 } 6699 // Emit final copy of the lastprivate variables if IsLastIter != 0. 6700 if (HasLastprivateClause) { 6701 CGF.EmitOMPLastprivateClauseFinal( 6702 S, isOpenMPSimdDirective(S.getDirectiveKind()), 6703 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar( 6704 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false, 6705 (*LIP)->getType(), S.getBeginLoc()))); 6706 } 6707 CGF.EmitOMPLinearClauseFinal(S, [LIP, &S](CodeGenFunction &CGF) { 6708 return CGF.Builder.CreateIsNotNull( 6709 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false, 6710 (*LIP)->getType(), S.getBeginLoc())); 6711 }); 6712 }; 6713 auto &&TaskGen = [&S, SharedsTy, CapturedStruct, 6714 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn, 6715 const OMPTaskDataTy &Data) { 6716 auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond, 6717 &Data](CodeGenFunction &CGF, PrePostActionTy &) { 6718 OMPLoopScope PreInitScope(CGF, S); 6719 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S, 6720 OutlinedFn, SharedsTy, 6721 CapturedStruct, IfCond, Data); 6722 }; 6723 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop, 6724 CodeGen); 6725 }; 6726 if (Data.Nogroup) { 6727 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data); 6728 } else { 6729 CGM.getOpenMPRuntime().emitTaskgroupRegion( 6730 *this, 6731 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF, 6732 PrePostActionTy &Action) { 6733 Action.Enter(CGF); 6734 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, 6735 Data); 6736 }, 6737 S.getBeginLoc()); 6738 } 6739 } 6740 6741 void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) { 6742 auto LPCRegion = 6743 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 6744 EmitOMPTaskLoopBasedDirective(S); 6745 } 6746 6747 void CodeGenFunction::EmitOMPTaskLoopSimdDirective( 6748 const OMPTaskLoopSimdDirective &S) { 6749 auto LPCRegion = 6750 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 6751 OMPLexicalScope Scope(*this, S); 6752 EmitOMPTaskLoopBasedDirective(S); 6753 } 6754 6755 void CodeGenFunction::EmitOMPMasterTaskLoopDirective( 6756 const OMPMasterTaskLoopDirective &S) { 6757 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6758 Action.Enter(CGF); 6759 EmitOMPTaskLoopBasedDirective(S); 6760 }; 6761 auto LPCRegion = 6762 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 6763 OMPLexicalScope Scope(*this, S, llvm::None, /*EmitPreInitStmt=*/false); 6764 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc()); 6765 } 6766 6767 void CodeGenFunction::EmitOMPMasterTaskLoopSimdDirective( 6768 const OMPMasterTaskLoopSimdDirective &S) { 6769 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6770 Action.Enter(CGF); 6771 EmitOMPTaskLoopBasedDirective(S); 6772 }; 6773 auto LPCRegion = 6774 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 6775 OMPLexicalScope Scope(*this, S); 6776 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc()); 6777 } 6778 6779 void CodeGenFunction::EmitOMPParallelMasterTaskLoopDirective( 6780 const OMPParallelMasterTaskLoopDirective &S) { 6781 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6782 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF, 6783 PrePostActionTy &Action) { 6784 Action.Enter(CGF); 6785 CGF.EmitOMPTaskLoopBasedDirective(S); 6786 }; 6787 OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false); 6788 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen, 6789 S.getBeginLoc()); 6790 }; 6791 auto LPCRegion = 6792 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 6793 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop, CodeGen, 6794 emitEmptyBoundParameters); 6795 } 6796 6797 void CodeGenFunction::EmitOMPParallelMasterTaskLoopSimdDirective( 6798 const OMPParallelMasterTaskLoopSimdDirective &S) { 6799 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6800 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF, 6801 PrePostActionTy &Action) { 6802 Action.Enter(CGF); 6803 CGF.EmitOMPTaskLoopBasedDirective(S); 6804 }; 6805 OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false); 6806 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen, 6807 S.getBeginLoc()); 6808 }; 6809 auto LPCRegion = 6810 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 6811 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop_simd, CodeGen, 6812 emitEmptyBoundParameters); 6813 } 6814 6815 // Generate the instructions for '#pragma omp target update' directive. 6816 void CodeGenFunction::EmitOMPTargetUpdateDirective( 6817 const OMPTargetUpdateDirective &S) { 6818 // If we don't have target devices, don't bother emitting the data mapping 6819 // code. 6820 if (CGM.getLangOpts().OMPTargetTriples.empty()) 6821 return; 6822 6823 // Check if we have any if clause associated with the directive. 6824 const Expr *IfCond = nullptr; 6825 if (const auto *C = S.getSingleClause<OMPIfClause>()) 6826 IfCond = C->getCondition(); 6827 6828 // Check if we have any device clause associated with the directive. 6829 const Expr *Device = nullptr; 6830 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 6831 Device = C->getDevice(); 6832 6833 OMPLexicalScope Scope(*this, S, OMPD_task); 6834 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device); 6835 } 6836 6837 void CodeGenFunction::EmitSimpleOMPExecutableDirective( 6838 const OMPExecutableDirective &D) { 6839 if (const auto *SD = dyn_cast<OMPScanDirective>(&D)) { 6840 EmitOMPScanDirective(*SD); 6841 return; 6842 } 6843 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt()) 6844 return; 6845 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) { 6846 OMPPrivateScope GlobalsScope(CGF); 6847 if (isOpenMPTaskingDirective(D.getDirectiveKind())) { 6848 // Capture global firstprivates to avoid crash. 6849 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) { 6850 for (const Expr *Ref : C->varlists()) { 6851 const auto *DRE = cast<DeclRefExpr>(Ref->IgnoreParenImpCasts()); 6852 if (!DRE) 6853 continue; 6854 const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); 6855 if (!VD || VD->hasLocalStorage()) 6856 continue; 6857 if (!CGF.LocalDeclMap.count(VD)) { 6858 LValue GlobLVal = CGF.EmitLValue(Ref); 6859 GlobalsScope.addPrivate( 6860 VD, [&GlobLVal, &CGF]() { return GlobLVal.getAddress(CGF); }); 6861 } 6862 } 6863 } 6864 } 6865 if (isOpenMPSimdDirective(D.getDirectiveKind())) { 6866 (void)GlobalsScope.Privatize(); 6867 ParentLoopDirectiveForScanRegion ScanRegion(CGF, D); 6868 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action); 6869 } else { 6870 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) { 6871 for (const Expr *E : LD->counters()) { 6872 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 6873 if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) { 6874 LValue GlobLVal = CGF.EmitLValue(E); 6875 GlobalsScope.addPrivate( 6876 VD, [&GlobLVal, &CGF]() { return GlobLVal.getAddress(CGF); }); 6877 } 6878 if (isa<OMPCapturedExprDecl>(VD)) { 6879 // Emit only those that were not explicitly referenced in clauses. 6880 if (!CGF.LocalDeclMap.count(VD)) 6881 CGF.EmitVarDecl(*VD); 6882 } 6883 } 6884 for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) { 6885 if (!C->getNumForLoops()) 6886 continue; 6887 for (unsigned I = LD->getLoopsNumber(), 6888 E = C->getLoopNumIterations().size(); 6889 I < E; ++I) { 6890 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>( 6891 cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) { 6892 // Emit only those that were not explicitly referenced in clauses. 6893 if (!CGF.LocalDeclMap.count(VD)) 6894 CGF.EmitVarDecl(*VD); 6895 } 6896 } 6897 } 6898 } 6899 (void)GlobalsScope.Privatize(); 6900 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt()); 6901 } 6902 }; 6903 if (D.getDirectiveKind() == OMPD_atomic || 6904 D.getDirectiveKind() == OMPD_critical || 6905 D.getDirectiveKind() == OMPD_section || 6906 D.getDirectiveKind() == OMPD_master) { 6907 EmitStmt(D.getAssociatedStmt()); 6908 } else { 6909 auto LPCRegion = 6910 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, D); 6911 OMPSimdLexicalScope Scope(*this, D); 6912 CGM.getOpenMPRuntime().emitInlinedDirective( 6913 *this, 6914 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd 6915 : D.getDirectiveKind(), 6916 CodeGen); 6917 } 6918 // Check for outer lastprivate conditional update. 6919 checkForLastprivateConditionalUpdate(*this, D); 6920 } 6921