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