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