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