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