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