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