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