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