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