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