blob: e2c055f549e02a2e5535816ef3d2818502dea67f [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alexey Bataev9959db52014-05-06 10:08:46 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit OpenMP nodes as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
Alexey Bataev3392d762016-02-16 11:18:12 +000013#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000014#include "CGOpenMPRuntime.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000017#include "TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000018#include "clang/AST/Stmt.h"
19#include "clang/AST/StmtOpenMP.h"
Alexey Bataev2bbf7212016-03-03 03:52:24 +000020#include "clang/AST/DeclOpenMP.h"
Alexey Bataev8bbf2e32019-11-04 09:59:11 -050021#include "clang/Basic/PrettyStackTrace.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000022using namespace clang;
23using namespace CodeGen;
24
Alexey Bataev3392d762016-02-16 11:18:12 +000025namespace {
26/// Lexical scope for OpenMP executable constructs, that handles correct codegen
27/// for captured expressions.
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000028class OMPLexicalScope : public CodeGenFunction::LexicalScope {
Alexey Bataev3392d762016-02-16 11:18:12 +000029 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
30 for (const auto *C : S.clauses()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +000031 if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
32 if (const auto *PreInit =
33 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000034 for (const auto *I : PreInit->decls()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +000035 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000036 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataevddf3db92018-04-13 17:31:06 +000037 } else {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000038 CodeGenFunction::AutoVarEmission Emission =
39 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
40 CGF.EmitAutoVarCleanups(Emission);
41 }
42 }
Alexey Bataev3392d762016-02-16 11:18:12 +000043 }
44 }
45 }
46 }
Alexey Bataev4ba78a42016-04-27 07:56:03 +000047 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 }
Alexey Bataev3392d762016-02-16 11:18:12 +000054
Alexey Bataev3392d762016-02-16 11:18:12 +000055public:
Alexey Bataev475a7442018-01-12 19:39:11 +000056 OMPLexicalScope(
57 CodeGenFunction &CGF, const OMPExecutableDirective &S,
58 const llvm::Optional<OpenMPDirectiveKind> CapturedRegion = llvm::None,
59 const bool EmitPreInitStmt = true)
Alexey Bataev4ba78a42016-04-27 07:56:03 +000060 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
61 InlinedShareds(CGF) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000062 if (EmitPreInitStmt)
63 emitPreInitStmt(CGF, S);
Alexey Bataev475a7442018-01-12 19:39:11 +000064 if (!CapturedRegion.hasValue())
65 return;
66 assert(S.hasAssociatedStmt() &&
67 "Expected associated statement for inlined directive.");
68 const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion);
Alexey Bataevddf3db92018-04-13 17:31:06 +000069 for (const auto &C : CS->captures()) {
Alexey Bataev475a7442018-01-12 19:39:11 +000070 if (C.capturesVariable() || C.capturesVariableByCopy()) {
71 auto *VD = C.getCapturedVar();
72 assert(VD == VD->getCanonicalDecl() &&
73 "Canonical decl must be captured.");
74 DeclRefExpr DRE(
Bruno Ricci5fc4db72018-12-21 14:10:18 +000075 CGF.getContext(), const_cast<VarDecl *>(VD),
Alexey Bataev475a7442018-01-12 19:39:11 +000076 isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo &&
77 InlinedShareds.isGlobalVarCaptured(VD)),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +000078 VD->getType().getNonReferenceType(), VK_LValue, C.getLocation());
Alexey Bataev475a7442018-01-12 19:39:11 +000079 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -080080 return CGF.EmitLValue(&DRE).getAddress();
Alexey Bataev475a7442018-01-12 19:39:11 +000081 });
Alexey Bataev4ba78a42016-04-27 07:56:03 +000082 }
83 }
Alexey Bataev475a7442018-01-12 19:39:11 +000084 (void)InlinedShareds.Privatize();
Alexey Bataev3392d762016-02-16 11:18:12 +000085 }
86};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000087
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000088/// Lexical scope for OpenMP parallel construct, that handles correct codegen
89/// for captured expressions.
90class OMPParallelScope final : public OMPLexicalScope {
91 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
92 OpenMPDirectiveKind Kind = S.getDirectiveKind();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +000093 return !(isOpenMPTargetExecutionDirective(Kind) ||
94 isOpenMPLoopBoundSharingDirective(Kind)) &&
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000095 isOpenMPParallelDirective(Kind);
96 }
97
98public:
99 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +0000100 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
101 EmitPreInitStmt(S)) {}
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +0000102};
103
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000104/// Lexical scope for OpenMP teams construct, that handles correct codegen
105/// for captured expressions.
106class OMPTeamsScope final : public OMPLexicalScope {
107 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
108 OpenMPDirectiveKind Kind = S.getDirectiveKind();
109 return !isOpenMPTargetExecutionDirective(Kind) &&
110 isOpenMPTeamsDirective(Kind);
111 }
112
113public:
114 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +0000115 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
116 EmitPreInitStmt(S)) {}
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000117};
118
Alexey Bataev5a3af132016-03-29 08:58:54 +0000119/// Private scope for OpenMP loop-based directives, that supports capturing
120/// of used expression from loop statement.
121class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
122 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
Alexey Bataevab4ea222018-03-07 18:17:06 +0000123 CodeGenFunction::OMPMapVars PreCondVars;
Alexey Bataevf71939c2019-09-18 19:24:07 +0000124 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000125 for (const auto *E : S.counters()) {
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000126 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf71939c2019-09-18 19:24:07 +0000127 EmittedAsPrivate.insert(VD->getCanonicalDecl());
Alexey Bataevab4ea222018-03-07 18:17:06 +0000128 (void)PreCondVars.setVarAddr(
129 CGF, VD, CGF.CreateMemTemp(VD->getType().getNonReferenceType()));
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000130 }
Alexey Bataevf71939c2019-09-18 19:24:07 +0000131 // Mark private vars as undefs.
132 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
133 for (const Expr *IRef : C->varlists()) {
134 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
135 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
136 (void)PreCondVars.setVarAddr(
137 CGF, OrigVD,
138 Address(llvm::UndefValue::get(
139 CGF.ConvertTypeForMem(CGF.getContext().getPointerType(
140 OrigVD->getType().getNonReferenceType()))),
141 CGF.getContext().getDeclAlign(OrigVD)));
142 }
143 }
144 }
Alexey Bataevab4ea222018-03-07 18:17:06 +0000145 (void)PreCondVars.apply(CGF);
Alexey Bataevbef93a92019-10-07 18:54:57 +0000146 // Emit init, __range and __end variables for C++ range loops.
147 const Stmt *Body =
148 S.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers();
149 for (unsigned Cnt = 0; Cnt < S.getCollapsedNumber(); ++Cnt) {
Alexey Bataev8bbf2e32019-11-04 09:59:11 -0500150 Body = OMPLoopDirective::tryToFindNextInnerLoop(
151 Body, /*TryImperfectlyNestedLoops=*/true);
Alexey Bataevbef93a92019-10-07 18:54:57 +0000152 if (auto *For = dyn_cast<ForStmt>(Body)) {
153 Body = For->getBody();
154 } else {
155 assert(isa<CXXForRangeStmt>(Body) &&
Alexey Bataevd457f7e2019-10-07 19:57:40 +0000156 "Expected canonical for loop or range-based for loop.");
Alexey Bataevbef93a92019-10-07 18:54:57 +0000157 auto *CXXFor = cast<CXXForRangeStmt>(Body);
158 if (const Stmt *Init = CXXFor->getInit())
159 CGF.EmitStmt(Init);
160 CGF.EmitStmt(CXXFor->getRangeStmt());
161 CGF.EmitStmt(CXXFor->getEndStmt());
162 Body = CXXFor->getBody();
163 }
164 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000165 if (const auto *PreInits = cast_or_null<DeclStmt>(S.getPreInits())) {
George Burgess IV00f70bd2018-03-01 05:43:23 +0000166 for (const auto *I : PreInits->decls())
167 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataev5a3af132016-03-29 08:58:54 +0000168 }
Alexey Bataevab4ea222018-03-07 18:17:06 +0000169 PreCondVars.restore(CGF);
Alexey Bataev5a3af132016-03-29 08:58:54 +0000170 }
171
172public:
173 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
174 : CodeGenFunction::RunCleanupsScope(CGF) {
175 emitPreInitStmt(CGF, S);
176 }
177};
178
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000179class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
180 CodeGenFunction::OMPPrivateScope InlinedShareds;
181
182 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
183 return CGF.LambdaCaptureFields.lookup(VD) ||
184 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
185 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
186 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
187 }
188
189public:
190 OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
191 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
192 InlinedShareds(CGF) {
193 for (const auto *C : S.clauses()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000194 if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
195 if (const auto *PreInit =
196 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000197 for (const auto *I : PreInit->decls()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000198 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000199 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataevddf3db92018-04-13 17:31:06 +0000200 } else {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000201 CodeGenFunction::AutoVarEmission Emission =
202 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
203 CGF.EmitAutoVarCleanups(Emission);
204 }
205 }
206 }
207 } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
208 for (const Expr *E : UDP->varlists()) {
209 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
210 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
211 CGF.EmitVarDecl(*OED);
212 }
213 }
214 }
215 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
216 CGF.EmitOMPPrivateClause(S, InlinedShareds);
217 if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
218 if (const Expr *E = TG->getReductionRef())
219 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
220 }
221 const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
222 while (CS) {
223 for (auto &C : CS->captures()) {
224 if (C.capturesVariable() || C.capturesVariableByCopy()) {
225 auto *VD = C.getCapturedVar();
226 assert(VD == VD->getCanonicalDecl() &&
227 "Canonical decl must be captured.");
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000228 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD),
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000229 isCapturedVar(CGF, VD) ||
230 (CGF.CapturedStmtInfo &&
231 InlinedShareds.isGlobalVarCaptured(VD)),
232 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000233 C.getLocation());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000234 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -0800235 return CGF.EmitLValue(&DRE).getAddress();
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000236 });
237 }
238 }
239 CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
240 }
241 (void)InlinedShareds.Privatize();
242 }
243};
244
Alexey Bataev3392d762016-02-16 11:18:12 +0000245} // namespace
246
Alexey Bataevf8365372017-11-17 17:57:25 +0000247static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
248 const OMPExecutableDirective &S,
249 const RegionCodeGenTy &CodeGen);
250
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000251LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000252 if (const auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
253 if (const auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000254 OrigVD = OrigVD->getCanonicalDecl();
255 bool IsCaptured =
256 LambdaCaptureFields.lookup(OrigVD) ||
257 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
258 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000259 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), IsCaptured,
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000260 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
261 return EmitLValue(&DRE);
262 }
263 }
264 return EmitLValue(E);
265}
266
Alexey Bataev1189bd02016-01-26 12:20:39 +0000267llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000268 ASTContext &C = getContext();
Alexey Bataev1189bd02016-01-26 12:20:39 +0000269 llvm::Value *Size = nullptr;
270 auto SizeInChars = C.getTypeSizeInChars(Ty);
271 if (SizeInChars.isZero()) {
272 // getTypeSizeInChars() returns 0 for a VLA.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000273 while (const VariableArrayType *VAT = C.getAsVariableArrayType(Ty)) {
274 VlaSizePair VlaSize = getVLASize(VAT);
Sander de Smalen891af03a2018-02-03 13:55:59 +0000275 Ty = VlaSize.Type;
276 Size = Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts)
277 : VlaSize.NumElts;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000278 }
279 SizeInChars = C.getTypeSizeInChars(Ty);
280 if (SizeInChars.isZero())
281 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000282 return Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
283 }
284 return CGM.getSize(SizeInChars);
Alexey Bataev1189bd02016-01-26 12:20:39 +0000285}
286
Alexey Bataev2377fe92015-09-10 08:12:02 +0000287void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000288 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000289 const RecordDecl *RD = S.getCapturedRecordDecl();
290 auto CurField = RD->field_begin();
291 auto CurCap = S.captures().begin();
292 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
293 E = S.capture_init_end();
294 I != E; ++I, ++CurField, ++CurCap) {
295 if (CurField->hasCapturedVLAType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000296 const VariableArrayType *VAT = CurField->getCapturedVLAType();
297 llvm::Value *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000298 CapturedVars.push_back(Val);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000299 } else if (CurCap->capturesThis()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000300 CapturedVars.push_back(CXXThisValue);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000301 } else if (CurCap->capturesVariableByCopy()) {
Alexey Bataev1e491372018-01-23 18:44:14 +0000302 llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000303
304 // If the field is not a pointer, we need to save the actual value
305 // and load it as a void pointer.
306 if (!CurField->getType()->isAnyPointerType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000307 ASTContext &Ctx = getContext();
308 Address DstAddr = CreateMemTemp(
Samuel Antao6d004262016-06-16 18:39:34 +0000309 Ctx.getUIntPtrType(),
Alexey Bataevddf3db92018-04-13 17:31:06 +0000310 Twine(CurCap->getCapturedVar()->getName(), ".casted"));
Samuel Antao6d004262016-06-16 18:39:34 +0000311 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
312
Alexey Bataevddf3db92018-04-13 17:31:06 +0000313 llvm::Value *SrcAddrVal = EmitScalarConversion(
Samuel Antao6d004262016-06-16 18:39:34 +0000314 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000315 Ctx.getPointerType(CurField->getType()), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000316 LValue SrcLV =
317 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
318
319 // Store the value using the source type pointer.
320 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
321
322 // Load the value using the destination type pointer.
Alexey Bataev1e491372018-01-23 18:44:14 +0000323 CV = EmitLoadOfScalar(DstLV, CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000324 }
325 CapturedVars.push_back(CV);
326 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000327 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -0800328 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000329 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000330 }
331}
332
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000333static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc,
334 QualType DstType, StringRef Name,
Alexey Bataev06e80f62019-05-23 18:19:54 +0000335 LValue AddrLV) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000336 ASTContext &Ctx = CGF.getContext();
337
Alexey Bataevddf3db92018-04-13 17:31:06 +0000338 llvm::Value *CastedPtr = CGF.EmitScalarConversion(
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -0800339 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
Alexey Bataevddf3db92018-04-13 17:31:06 +0000340 Ctx.getPointerType(DstType), Loc);
341 Address TmpAddr =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000342 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -0800343 .getAddress();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000344 return TmpAddr;
345}
346
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000347static QualType getCanonicalParamType(ASTContext &C, QualType T) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000348 if (T->isLValueReferenceType())
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000349 return C.getLValueReferenceType(
350 getCanonicalParamType(C, T.getNonReferenceType()),
351 /*SpelledAsLValue=*/false);
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000352 if (T->isPointerType())
353 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
Alexey Bataevddf3db92018-04-13 17:31:06 +0000354 if (const ArrayType *A = T->getAsArrayTypeUnsafe()) {
355 if (const auto *VLA = dyn_cast<VariableArrayType>(A))
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000356 return getCanonicalParamType(C, VLA->getElementType());
Alexey Bataevddf3db92018-04-13 17:31:06 +0000357 if (!A->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000358 return C.getCanonicalType(T);
359 }
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000360 return C.getCanonicalParamType(T);
361}
362
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000363namespace {
364 /// Contains required data for proper outlined function codegen.
365 struct FunctionOptions {
366 /// Captured statement for which the function is generated.
367 const CapturedStmt *S = nullptr;
368 /// true if cast to/from UIntPtr is required for variables captured by
369 /// value.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000370 const bool UIntPtrCastRequired = true;
Alexey Bataeve754b182017-08-09 19:38:53 +0000371 /// true if only casted arguments must be registered as local args or VLA
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000372 /// sizes.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000373 const bool RegisterCastedArgsOnly = false;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000374 /// Name of the generated function.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000375 const StringRef FunctionName;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000376 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
377 bool RegisterCastedArgsOnly,
Alexey Bataev4aa19052017-08-08 16:45:36 +0000378 StringRef FunctionName)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000379 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
380 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
Alexey Bataev4aa19052017-08-08 16:45:36 +0000381 FunctionName(FunctionName) {}
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000382 };
383}
384
Alexey Bataeve754b182017-08-09 19:38:53 +0000385static llvm::Function *emitOutlinedFunctionPrologue(
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000386 CodeGenFunction &CGF, FunctionArgList &Args,
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000387 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000388 &LocalAddrs,
389 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
390 &VLASizes,
391 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
392 const CapturedDecl *CD = FO.S->getCapturedDecl();
393 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000394 assert(CD->hasBody() && "missing CapturedDecl body");
395
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000396 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000397 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000398 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000399 ASTContext &Ctx = CGM.getContext();
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000400 FunctionArgList TargetArgs;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000401 Args.append(CD->param_begin(),
402 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000403 TargetArgs.append(
404 CD->param_begin(),
405 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000406 auto I = FO.S->captures().begin();
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000407 FunctionDecl *DebugFunctionDecl = nullptr;
408 if (!FO.UIntPtrCastRequired) {
409 FunctionProtoType::ExtProtoInfo EPI;
Jonas Devlieghere64a26302018-11-11 00:56:15 +0000410 QualType FunctionTy = Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000411 DebugFunctionDecl = FunctionDecl::Create(
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000412 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getBeginLoc(),
Jonas Devlieghere64a26302018-11-11 00:56:15 +0000413 SourceLocation(), DeclarationName(), FunctionTy,
414 Ctx.getTrivialTypeSourceInfo(FunctionTy), SC_Static,
415 /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000416 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000417 for (const FieldDecl *FD : RD->fields()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000418 QualType ArgType = FD->getType();
419 IdentifierInfo *II = nullptr;
420 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000421
422 // If this is a capture by copy and the type is not a pointer, the outlined
423 // function argument type should be uintptr and the value properly casted to
424 // uintptr. This is necessary given that the runtime library is only able to
425 // deal with pointers. We can pass in the same way the VLA type sizes to the
426 // outlined function.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000427 if (FO.UIntPtrCastRequired &&
428 ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
429 I->capturesVariableArrayType()))
430 ArgType = Ctx.getUIntPtrType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000431
432 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000433 CapVar = I->getCapturedVar();
434 II = CapVar->getIdentifier();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000435 } else if (I->capturesThis()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000436 II = &Ctx.Idents.get("this");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000437 } else {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000438 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000439 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000440 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000441 if (ArgType->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000442 ArgType = getCanonicalParamType(Ctx, ArgType);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000443 VarDecl *Arg;
444 if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
445 Arg = ParmVarDecl::Create(
446 Ctx, DebugFunctionDecl,
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000447 CapVar ? CapVar->getBeginLoc() : FD->getBeginLoc(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000448 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
449 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
450 } else {
451 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
452 II, ArgType, ImplicitParamDecl::Other);
453 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000454 Args.emplace_back(Arg);
455 // Do not cast arguments if we emit function with non-original types.
456 TargetArgs.emplace_back(
457 FO.UIntPtrCastRequired
458 ? Arg
459 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000460 ++I;
461 }
462 Args.append(
463 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
464 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000465 TargetArgs.append(
466 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
467 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000468
469 // Create the function declaration.
Alexey Bataev2377fe92015-09-10 08:12:02 +0000470 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000471 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000472 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
473
Alexey Bataevddf3db92018-04-13 17:31:06 +0000474 auto *F =
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000475 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
476 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000477 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
478 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000479 F->setDoesNotThrow();
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000480 F->setDoesNotRecurse();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000481
482 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000483 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000484 FO.S->getBeginLoc(), CD->getBody()->getBeginLoc());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000485 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000486 I = FO.S->captures().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000487 for (const FieldDecl *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000488 // Do not map arguments if we emit function with non-original types.
489 Address LocalAddr(Address::invalid());
490 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
491 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
492 TargetArgs[Cnt]);
493 } else {
494 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
495 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000496 // If we are capturing a pointer by copy we don't need to do anything, just
497 // use the value that we get from the arguments.
498 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000499 const VarDecl *CurVD = I->getCapturedVar();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000500 if (!FO.RegisterCastedArgsOnly)
501 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000502 ++Cnt;
503 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000504 continue;
505 }
506
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000507 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
508 AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000509 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000510 if (FO.UIntPtrCastRequired) {
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000511 ArgLVal = CGF.MakeAddrLValue(
512 castValueFromUintptr(CGF, I->getLocation(), FD->getType(),
513 Args[Cnt]->getName(), ArgLVal),
514 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000515 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000516 llvm::Value *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
517 const VariableArrayType *VAT = FD->getCapturedVLAType();
518 VLASizes.try_emplace(Args[Cnt], VAT->getSizeExpr(), ExprArg);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000519 } else if (I->capturesVariable()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000520 const VarDecl *Var = I->getCapturedVar();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000521 QualType VarTy = Var->getType();
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -0800522 Address ArgAddr = ArgLVal.getAddress();
Alexey Bataev06e80f62019-05-23 18:19:54 +0000523 if (ArgLVal.getType()->isLValueReferenceType()) {
524 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
525 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
526 assert(ArgLVal.getType()->isPointerType());
527 ArgAddr = CGF.EmitLoadOfPointer(
528 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000529 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000530 if (!FO.RegisterCastedArgsOnly) {
531 LocalAddrs.insert(
532 {Args[Cnt],
533 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
534 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000535 } else if (I->capturesVariableByCopy()) {
536 assert(!FD->getType()->isAnyPointerType() &&
537 "Not expecting a captured pointer.");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000538 const VarDecl *Var = I->getCapturedVar();
Alexey Bataev06e80f62019-05-23 18:19:54 +0000539 LocalAddrs.insert({Args[Cnt],
540 {Var, FO.UIntPtrCastRequired
541 ? castValueFromUintptr(
542 CGF, I->getLocation(), FD->getType(),
543 Args[Cnt]->getName(), ArgLVal)
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -0800544 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000545 } else {
546 // If 'this' is captured, load it into CXXThisValue.
547 assert(I->capturesThis());
Alexey Bataev1e491372018-01-23 18:44:14 +0000548 CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -0800549 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000550 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000551 ++Cnt;
552 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000553 }
554
Alexey Bataeve754b182017-08-09 19:38:53 +0000555 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000556}
557
558llvm::Function *
559CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
560 assert(
561 CapturedStmtInfo &&
562 "CapturedStmtInfo should be set when generating the captured function");
563 const CapturedDecl *CD = S.getCapturedDecl();
564 // Build the argument list.
565 bool NeedWrapperFunction =
566 getDebugInfo() &&
567 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
568 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000569 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000570 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000571 SmallString<256> Buffer;
572 llvm::raw_svector_ostream Out(Buffer);
573 Out << CapturedStmtInfo->getHelperName();
574 if (NeedWrapperFunction)
575 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000576 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataeve754b182017-08-09 19:38:53 +0000577 Out.str());
578 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
579 VLASizes, CXXThisValue, FO);
Alexey Bataev06e80f62019-05-23 18:19:54 +0000580 CodeGenFunction::OMPPrivateScope LocalScope(*this);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000581 for (const auto &LocalAddrPair : LocalAddrs) {
582 if (LocalAddrPair.second.first) {
Alexey Bataev06e80f62019-05-23 18:19:54 +0000583 LocalScope.addPrivate(LocalAddrPair.second.first, [&LocalAddrPair]() {
584 return LocalAddrPair.second.second;
585 });
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000586 }
587 }
Alexey Bataev06e80f62019-05-23 18:19:54 +0000588 (void)LocalScope.Privatize();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000589 for (const auto &VLASizePair : VLASizes)
590 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000591 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000592 CapturedStmtInfo->EmitBody(*this, CD->getBody());
Alexey Bataev06e80f62019-05-23 18:19:54 +0000593 (void)LocalScope.ForceCleanup();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000594 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000595 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000596 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000597
Alexey Bataevefd884d2017-08-04 21:26:25 +0000598 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000599 /*RegisterCastedArgsOnly=*/true,
600 CapturedStmtInfo->getHelperName());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000601 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000602 WrapperCGF.CapturedStmtInfo = CapturedStmtInfo;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000603 Args.clear();
604 LocalAddrs.clear();
605 VLASizes.clear();
606 llvm::Function *WrapperF =
607 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000608 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000609 llvm::SmallVector<llvm::Value *, 4> CallArgs;
610 for (const auto *Arg : Args) {
611 llvm::Value *CallArg;
612 auto I = LocalAddrs.find(Arg);
613 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000614 LValue LV = WrapperCGF.MakeAddrLValue(
615 I->second.second,
616 I->second.first ? I->second.first->getType() : Arg->getType(),
617 AlignmentSource::Decl);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000618 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000619 } else {
620 auto EI = VLASizes.find(Arg);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000621 if (EI != VLASizes.end()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000622 CallArg = EI->second.second;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000623 } else {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000624 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000625 Arg->getType(),
626 AlignmentSource::Decl);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000627 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000628 }
629 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000630 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000631 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000632 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getBeginLoc(),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000633 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000634 WrapperCGF.FinishFunction();
635 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000636}
637
Alexey Bataev9959db52014-05-06 10:08:46 +0000638//===----------------------------------------------------------------------===//
639// OpenMP Directive Emission
640//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000641void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000642 Address DestAddr, Address SrcAddr, QualType OriginalType,
Alexey Bataevddf3db92018-04-13 17:31:06 +0000643 const llvm::function_ref<void(Address, Address)> CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000644 // Perform element-by-element initialization.
645 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000646
647 // Drill down to the base element type on both arrays.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000648 const ArrayType *ArrayTy = OriginalType->getAsArrayTypeUnsafe();
649 llvm::Value *NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
John McCall7f416cc2015-09-08 08:05:57 +0000650 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
651
Alexey Bataevddf3db92018-04-13 17:31:06 +0000652 llvm::Value *SrcBegin = SrcAddr.getPointer();
653 llvm::Value *DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000654 // Cast from pointer to array type to pointer to single element.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000655 llvm::Value *DestEnd = Builder.CreateGEP(DestBegin, NumElements);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000656 // The basic structure here is a while-do loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000657 llvm::BasicBlock *BodyBB = createBasicBlock("omp.arraycpy.body");
658 llvm::BasicBlock *DoneBB = createBasicBlock("omp.arraycpy.done");
659 llvm::Value *IsEmpty =
Alexey Bataev420d45b2015-04-14 05:11:24 +0000660 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
661 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000662
Alexey Bataev420d45b2015-04-14 05:11:24 +0000663 // Enter the loop body, making that address the current address.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000664 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000665 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000666
667 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
668
669 llvm::PHINode *SrcElementPHI =
670 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
671 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
672 Address SrcElementCurrent =
673 Address(SrcElementPHI,
674 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
675
676 llvm::PHINode *DestElementPHI =
677 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
678 DestElementPHI->addIncoming(DestBegin, EntryBB);
679 Address DestElementCurrent =
680 Address(DestElementPHI,
681 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000682
Alexey Bataev420d45b2015-04-14 05:11:24 +0000683 // Emit copy.
684 CopyGen(DestElementCurrent, SrcElementCurrent);
685
686 // Shift the address forward by one element.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000687 llvm::Value *DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000688 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000689 llvm::Value *SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000690 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000691 // Check whether we've reached the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000692 llvm::Value *Done =
Alexey Bataev420d45b2015-04-14 05:11:24 +0000693 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
694 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000695 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
696 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000697
698 // Done.
699 EmitBlock(DoneBB, /*IsFinished=*/true);
700}
701
John McCall7f416cc2015-09-08 08:05:57 +0000702void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
703 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000704 const VarDecl *SrcVD, const Expr *Copy) {
705 if (OriginalType->isArrayType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000706 const auto *BO = dyn_cast<BinaryOperator>(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000707 if (BO && BO->getOpcode() == BO_Assign) {
708 // Perform simple memcpy for simple copying.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000709 LValue Dest = MakeAddrLValue(DestAddr, OriginalType);
710 LValue Src = MakeAddrLValue(SrcAddr, OriginalType);
711 EmitAggregateAssign(Dest, Src, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000712 } else {
713 // For arrays with complex element types perform element by element
714 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000715 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000716 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000717 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000718 // Working with the single array element, so have to remap
719 // destination and source variables to corresponding array
720 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000721 CodeGenFunction::OMPPrivateScope Remap(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000722 Remap.addPrivate(DestVD, [DestElement]() { return DestElement; });
723 Remap.addPrivate(SrcVD, [SrcElement]() { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000724 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000725 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000726 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000727 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000728 } else {
729 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000730 CodeGenFunction::OMPPrivateScope Remap(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000731 Remap.addPrivate(SrcVD, [SrcAddr]() { return SrcAddr; });
732 Remap.addPrivate(DestVD, [DestAddr]() { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000733 (void)Remap.Privatize();
734 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000735 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000736 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000737}
738
Alexey Bataev69c62a92015-04-15 04:52:20 +0000739bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
740 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000741 if (!HaveInsertPoint())
742 return false;
Alexey Bataev1af5bd52019-03-05 17:47:18 +0000743 bool DeviceConstTarget =
744 getLangOpts().OpenMPIsDevice &&
745 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000746 bool FirstprivateIsLastprivate = false;
747 llvm::DenseSet<const VarDecl *> Lastprivates;
748 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
749 for (const auto *D : C->varlists())
750 Lastprivates.insert(
751 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
752 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000753 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev475a7442018-01-12 19:39:11 +0000754 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
755 getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind());
756 // Force emission of the firstprivate copy if the directive does not emit
757 // outlined function, like omp for, omp simd, omp distribute etc.
758 bool MustEmitFirstprivateCopy =
759 CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000760 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000761 auto IRef = C->varlist_begin();
762 auto InitsRef = C->inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000763 for (const Expr *IInit : C->private_copies()) {
764 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000765 bool ThisFirstprivateIsLastprivate =
766 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000767 const FieldDecl *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9c397812019-04-03 17:57:06 +0000768 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataev475a7442018-01-12 19:39:11 +0000769 if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
Alexey Bataev9c397812019-04-03 17:57:06 +0000770 !FD->getType()->isReferenceType() &&
771 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000772 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
773 ++IRef;
774 ++InitsRef;
775 continue;
776 }
Alexey Bataev1af5bd52019-03-05 17:47:18 +0000777 // Do not emit copy for firstprivate constant variables in target regions,
778 // captured by reference.
779 if (DeviceConstTarget && OrigVD->getType().isConstant(getContext()) &&
Alexey Bataev9c397812019-04-03 17:57:06 +0000780 FD && FD->getType()->isReferenceType() &&
781 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
Alexey Bataev1af5bd52019-03-05 17:47:18 +0000782 (void)CGM.getOpenMPRuntime().registerTargetFirstprivateCopy(*this,
783 OrigVD);
784 ++IRef;
785 ++InitsRef;
786 continue;
787 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000788 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000789 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000790 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000791 const auto *VDInit =
792 cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000793 bool IsRegistered;
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000794 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000795 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
796 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Alexey Bataeve0ef04f2019-05-23 22:30:43 +0000797 LValue OriginalLVal;
798 if (!FD) {
799 // Check if the firstprivate variable is just a constant value.
800 ConstantEmission CE = tryEmitAsConstant(&DRE);
801 if (CE && !CE.isReference()) {
802 // Constant value, no need to create a copy.
803 ++IRef;
804 ++InitsRef;
805 continue;
806 }
807 if (CE && CE.isReference()) {
808 OriginalLVal = CE.getReferenceLValue(*this, &DRE);
809 } else {
810 assert(!CE && "Expected non-constant firstprivate.");
811 OriginalLVal = EmitLValue(&DRE);
812 }
813 } else {
814 OriginalLVal = EmitLValue(&DRE);
815 }
Alexey Bataevfeddd642016-04-22 09:05:03 +0000816 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000817 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000818 // Emit VarDecl with copy init for arrays.
819 // Get the address of the original variable captured in current
820 // captured region.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000821 IsRegistered = PrivateScope.addPrivate(
822 OrigVD, [this, VD, Type, OriginalLVal, VDInit]() {
823 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
824 const Expr *Init = VD->getInit();
825 if (!isa<CXXConstructExpr>(Init) ||
826 isTrivialInitializer(Init)) {
827 // Perform simple memcpy.
828 LValue Dest =
829 MakeAddrLValue(Emission.getAllocatedAddress(), Type);
830 EmitAggregateAssign(Dest, OriginalLVal, Type);
831 } else {
832 EmitOMPAggregateAssign(
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -0800833 Emission.getAllocatedAddress(), OriginalLVal.getAddress(),
834 Type,
Alexey Bataevddf3db92018-04-13 17:31:06 +0000835 [this, VDInit, Init](Address DestElement,
836 Address SrcElement) {
837 // Clean up any temporaries needed by the
838 // initialization.
839 RunCleanupsScope InitScope(*this);
840 // Emit initialization for single element.
841 setAddrOfLocalVar(VDInit, SrcElement);
842 EmitAnyExprToMem(Init, DestElement,
843 Init->getType().getQualifiers(),
844 /*IsInitializer*/ false);
845 LocalDeclMap.erase(VDInit);
846 });
847 }
848 EmitAutoVarCleanups(Emission);
849 return Emission.getAllocatedAddress();
850 });
Alexey Bataev69c62a92015-04-15 04:52:20 +0000851 } else {
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -0800852 Address OriginalAddr = OriginalLVal.getAddress();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000853 IsRegistered = PrivateScope.addPrivate(
854 OrigVD, [this, VDInit, OriginalAddr, VD]() {
855 // Emit private VarDecl with copy init.
856 // Remap temp VDInit variable to the address of the original
857 // variable (for proper handling of captured global variables).
858 setAddrOfLocalVar(VDInit, OriginalAddr);
859 EmitDecl(*VD);
860 LocalDeclMap.erase(VDInit);
861 return GetAddrOfLocalVar(VD);
862 });
Alexey Bataev69c62a92015-04-15 04:52:20 +0000863 }
864 assert(IsRegistered &&
865 "firstprivate var already registered as private");
866 // Silence the warning about unused variable.
867 (void)IsRegistered;
868 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000869 ++IRef;
870 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000871 }
872 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000873 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000874}
875
Alexey Bataev03b340a2014-10-21 03:16:40 +0000876void CodeGenFunction::EmitOMPPrivateClause(
877 const OMPExecutableDirective &D,
878 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000879 if (!HaveInsertPoint())
880 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000881 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000882 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000883 auto IRef = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000884 for (const Expr *IInit : C->private_copies()) {
885 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000886 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000887 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
888 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() {
889 // Emit private VarDecl with copy init.
890 EmitDecl(*VD);
891 return GetAddrOfLocalVar(VD);
892 });
Alexey Bataev50a64582015-04-22 12:24:45 +0000893 assert(IsRegistered && "private var already registered as private");
894 // Silence the warning about unused variable.
895 (void)IsRegistered;
896 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000897 ++IRef;
898 }
899 }
900}
901
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000902bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000903 if (!HaveInsertPoint())
904 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000905 // threadprivate_var1 = master_threadprivate_var1;
906 // operator=(threadprivate_var2, master_threadprivate_var2);
907 // ...
908 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000909 llvm::DenseSet<const VarDecl *> CopiedVars;
910 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000911 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000912 auto IRef = C->varlist_begin();
913 auto ISrcRef = C->source_exprs().begin();
914 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000915 for (const Expr *AssignOp : C->assignment_ops()) {
916 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000917 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000918 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000919 // Get the address of the master variable. If we are emitting code with
920 // TLS support, the address is passed from the master as field in the
921 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000922 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000923 if (getLangOpts().OpenMPUseTLS &&
924 getContext().getTargetInfo().isTLSSupported()) {
925 assert(CapturedStmtInfo->lookup(VD) &&
926 "Copyin threadprivates should have been captured!");
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000927 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), true,
928 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -0800929 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000930 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000931 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000932 MasterAddr =
933 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
934 : CGM.GetAddrOfGlobal(VD),
935 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000936 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000937 // Get the address of the threadprivate variable.
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -0800938 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000939 if (CopiedVars.size() == 1) {
940 // At first check if current thread is a master thread. If it is, no
941 // need to copy data.
942 CopyBegin = createBasicBlock("copyin.not.master");
943 CopyEnd = createBasicBlock("copyin.not.master.end");
944 Builder.CreateCondBr(
945 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000946 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
Alexey Bataevddf3db92018-04-13 17:31:06 +0000947 Builder.CreatePtrToInt(PrivateAddr.getPointer(),
948 CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000949 CopyBegin, CopyEnd);
950 EmitBlock(CopyBegin);
951 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000952 const auto *SrcVD =
953 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
954 const auto *DestVD =
955 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000956 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000957 }
958 ++IRef;
959 ++ISrcRef;
960 ++IDestRef;
961 }
962 }
963 if (CopyEnd) {
964 // Exit out of copying procedure for non-master thread.
965 EmitBlock(CopyEnd, /*IsFinished=*/true);
966 return true;
967 }
968 return false;
969}
970
Alexey Bataev38e89532015-04-16 04:54:05 +0000971bool CodeGenFunction::EmitOMPLastprivateClauseInit(
972 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000973 if (!HaveInsertPoint())
974 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000975 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000976 llvm::DenseSet<const VarDecl *> SIMDLCVs;
977 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000978 const auto *LoopDirective = cast<OMPLoopDirective>(&D);
979 for (const Expr *C : LoopDirective->counters()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000980 SIMDLCVs.insert(
981 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
982 }
983 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000984 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000985 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000986 HasAtLeastOneLastprivate = true;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000987 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
988 !getLangOpts().OpenMPSimd)
Alexey Bataevf93095a2016-05-05 08:46:22 +0000989 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000990 auto IRef = C->varlist_begin();
991 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000992 for (const Expr *IInit : C->private_copies()) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000993 // Keep the address of the original variable for future update at the end
994 // of the loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000995 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000996 // Taskloops do not require additional initialization, it is done in
997 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000998 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000999 const auto *DestVD =
1000 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1001 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() {
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001002 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
1003 /*RefersToEnclosingVariableOrCapture=*/
1004 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1005 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08001006 return EmitLValue(&DRE).getAddress();
Alexey Bataev38e89532015-04-16 04:54:05 +00001007 });
1008 // Check if the variable is also a firstprivate: in this case IInit is
1009 // not generated. Initialization of this variable will happen in codegen
1010 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001011 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001012 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
1013 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() {
Alexey Bataevf93095a2016-05-05 08:46:22 +00001014 // Emit private VarDecl with copy init.
1015 EmitDecl(*VD);
1016 return GetAddrOfLocalVar(VD);
1017 });
Alexey Bataevd130fd12015-05-13 10:23:02 +00001018 assert(IsRegistered &&
1019 "lastprivate var already registered as private");
1020 (void)IsRegistered;
1021 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001022 }
Richard Trieucc3949d2016-02-18 22:34:54 +00001023 ++IRef;
1024 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +00001025 }
1026 }
1027 return HasAtLeastOneLastprivate;
1028}
1029
1030void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001031 const OMPExecutableDirective &D, bool NoFinals,
1032 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001033 if (!HaveInsertPoint())
1034 return;
Alexey Bataev38e89532015-04-16 04:54:05 +00001035 // Emit following code:
1036 // if (<IsLastIterCond>) {
1037 // orig_var1 = private_orig_var1;
1038 // ...
1039 // orig_varn = private_orig_varn;
1040 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001041 llvm::BasicBlock *ThenBB = nullptr;
1042 llvm::BasicBlock *DoneBB = nullptr;
1043 if (IsLastIterCond) {
1044 ThenBB = createBasicBlock(".omp.lastprivate.then");
1045 DoneBB = createBasicBlock(".omp.lastprivate.done");
1046 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
1047 EmitBlock(ThenBB);
1048 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001049 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
1050 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001051 if (const auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001052 auto IC = LoopDirective->counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001053 for (const Expr *F : LoopDirective->finals()) {
1054 const auto *D =
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001055 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1056 if (NoFinals)
1057 AlreadyEmittedVars.insert(D);
1058 else
1059 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001060 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001061 }
1062 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001063 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1064 auto IRef = C->varlist_begin();
1065 auto ISrcRef = C->source_exprs().begin();
1066 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001067 for (const Expr *AssignOp : C->assignment_ops()) {
1068 const auto *PrivateVD =
1069 cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001070 QualType Type = PrivateVD->getType();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001071 const auto *CanonicalVD = PrivateVD->getCanonicalDecl();
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001072 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1073 // If lastprivate variable is a loop control variable for loop-based
1074 // directive, update its value before copyin back to original
1075 // variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001076 if (const Expr *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001077 EmitIgnoredExpr(FinalExpr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001078 const auto *SrcVD =
1079 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1080 const auto *DestVD =
1081 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001082 // Get the address of the original variable.
1083 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
1084 // Get the address of the private variable.
1085 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001086 if (const auto *RefTy = PrivateVD->getType()->getAs<ReferenceType>())
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001087 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +00001088 Address(Builder.CreateLoad(PrivateAddr),
1089 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001090 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +00001091 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001092 ++IRef;
1093 ++ISrcRef;
1094 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +00001095 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001096 if (const Expr *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00001097 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001098 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001099 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001100 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +00001101}
1102
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001103void CodeGenFunction::EmitOMPReductionClauseInit(
1104 const OMPExecutableDirective &D,
1105 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001106 if (!HaveInsertPoint())
1107 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001108 SmallVector<const Expr *, 4> Shareds;
1109 SmallVector<const Expr *, 4> Privates;
1110 SmallVector<const Expr *, 4> ReductionOps;
1111 SmallVector<const Expr *, 4> LHSs;
1112 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001113 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001114 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001115 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001116 auto ILHS = C->lhs_exprs().begin();
1117 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001118 for (const Expr *Ref : C->varlists()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001119 Shareds.emplace_back(Ref);
1120 Privates.emplace_back(*IPriv);
1121 ReductionOps.emplace_back(*IRed);
1122 LHSs.emplace_back(*ILHS);
1123 RHSs.emplace_back(*IRHS);
1124 std::advance(IPriv, 1);
1125 std::advance(IRed, 1);
1126 std::advance(ILHS, 1);
1127 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001128 }
1129 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001130 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1131 unsigned Count = 0;
1132 auto ILHS = LHSs.begin();
1133 auto IRHS = RHSs.begin();
1134 auto IPriv = Privates.begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001135 for (const Expr *IRef : Shareds) {
1136 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001137 // Emit private VarDecl with reduction init.
1138 RedCG.emitSharedLValue(*this, Count);
1139 RedCG.emitAggregateType(*this, Count);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001140 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001141 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1142 RedCG.getSharedLValue(Count),
1143 [&Emission](CodeGenFunction &CGF) {
1144 CGF.EmitAutoVarInit(Emission);
1145 return true;
1146 });
1147 EmitAutoVarCleanups(Emission);
1148 Address BaseAddr = RedCG.adjustPrivateAddress(
1149 *this, Count, Emission.getAllocatedAddress());
1150 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataevddf3db92018-04-13 17:31:06 +00001151 RedCG.getBaseDecl(Count), [BaseAddr]() { return BaseAddr; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001152 assert(IsRegistered && "private var already registered as private");
1153 // Silence the warning about unused variable.
1154 (void)IsRegistered;
1155
Alexey Bataevddf3db92018-04-13 17:31:06 +00001156 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1157 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001158 QualType Type = PrivateVD->getType();
1159 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1160 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001161 // Store the address of the original variable associated with the LHS
1162 // implicit variable.
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08001163 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() {
1164 return RedCG.getSharedLValue(Count).getAddress();
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001165 });
Alexey Bataevddf3db92018-04-13 17:31:06 +00001166 PrivateScope.addPrivate(
1167 RHSVD, [this, PrivateVD]() { return GetAddrOfLocalVar(PrivateVD); });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001168 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1169 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001170 // Store the address of the original variable associated with the LHS
1171 // implicit variable.
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08001172 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() {
1173 return RedCG.getSharedLValue(Count).getAddress();
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001174 });
Alexey Bataevddf3db92018-04-13 17:31:06 +00001175 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001176 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1177 ConvertTypeForMem(RHSVD->getType()),
1178 "rhs.begin");
1179 });
1180 } else {
1181 QualType Type = PrivateVD->getType();
1182 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08001183 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001184 // Store the address of the original variable associated with the LHS
1185 // implicit variable.
1186 if (IsArray) {
1187 OriginalAddr = Builder.CreateElementBitCast(
1188 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1189 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001190 PrivateScope.addPrivate(LHSVD, [OriginalAddr]() { return OriginalAddr; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001191 PrivateScope.addPrivate(
Alexey Bataevddf3db92018-04-13 17:31:06 +00001192 RHSVD, [this, PrivateVD, RHSVD, IsArray]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001193 return IsArray
1194 ? Builder.CreateElementBitCast(
1195 GetAddrOfLocalVar(PrivateVD),
1196 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1197 : GetAddrOfLocalVar(PrivateVD);
1198 });
1199 }
1200 ++ILHS;
1201 ++IRHS;
1202 ++IPriv;
1203 ++Count;
1204 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001205}
1206
1207void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001208 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001209 if (!HaveInsertPoint())
1210 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001211 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001212 llvm::SmallVector<const Expr *, 8> LHSExprs;
1213 llvm::SmallVector<const Expr *, 8> RHSExprs;
1214 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001215 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001216 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001217 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001218 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001219 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1220 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1221 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1222 }
1223 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001224 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1225 isOpenMPParallelDirective(D.getDirectiveKind()) ||
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001226 ReductionKind == OMPD_simd;
1227 bool SimpleReduction = ReductionKind == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001228 // Emit nowait reduction if nowait clause is present or directive is a
1229 // parallel directive (it always has implicit barrier).
1230 CGM.getOpenMPRuntime().emitReduction(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001231 *this, D.getEndLoc(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001232 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001233 }
1234}
1235
Alexey Bataev61205072016-03-02 04:57:40 +00001236static void emitPostUpdateForReductionClause(
1237 CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001238 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev61205072016-03-02 04:57:40 +00001239 if (!CGF.HaveInsertPoint())
1240 return;
1241 llvm::BasicBlock *DoneBB = nullptr;
1242 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001243 if (const Expr *PostUpdate = C->getPostUpdateExpr()) {
Alexey Bataev61205072016-03-02 04:57:40 +00001244 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001245 if (llvm::Value *Cond = CondGen(CGF)) {
Alexey Bataev61205072016-03-02 04:57:40 +00001246 // If the first post-update expression is found, emit conditional
1247 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001248 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
Alexey Bataev61205072016-03-02 04:57:40 +00001249 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1250 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1251 CGF.EmitBlock(ThenBB);
1252 }
1253 }
1254 CGF.EmitIgnoredExpr(PostUpdate);
1255 }
1256 }
1257 if (DoneBB)
1258 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1259}
1260
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001261namespace {
1262/// Codegen lambda for appending distribute lower and upper bounds to outlined
1263/// parallel function. This is necessary for combined constructs such as
1264/// 'distribute parallel for'
1265typedef llvm::function_ref<void(CodeGenFunction &,
1266 const OMPExecutableDirective &,
1267 llvm::SmallVectorImpl<llvm::Value *> &)>
1268 CodeGenBoundParametersTy;
1269} // anonymous namespace
1270
1271static void emitCommonOMPParallelDirective(
1272 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1273 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1274 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001275 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
James Y Knight9871db02019-02-05 16:42:33 +00001276 llvm::Function *OutlinedFn =
Alexey Bataevddf3db92018-04-13 17:31:06 +00001277 CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1278 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001279 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001280 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001281 llvm::Value *NumThreads =
1282 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1283 /*IgnoreResultAssign=*/true);
Alexey Bataev1d677132015-04-22 13:57:31 +00001284 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001285 CGF, NumThreads, NumThreadsClause->getBeginLoc());
Alexey Bataev1d677132015-04-22 13:57:31 +00001286 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001287 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001288 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001289 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001290 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getBeginLoc());
Alexey Bataev7f210c62015-06-18 13:40:03 +00001291 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001292 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001293 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1294 if (C->getNameModifier() == OMPD_unknown ||
1295 C->getNameModifier() == OMPD_parallel) {
1296 IfCond = C->getCondition();
1297 break;
1298 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001299 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001300
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001301 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001302 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001303 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1304 // lower and upper bounds with the pragma 'for' chunking mechanism.
1305 // The following lambda takes care of appending the lower and upper bound
1306 // parameters when necessary
1307 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001308 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001309 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getBeginLoc(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001310 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001311}
1312
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001313static void emitEmptyBoundParameters(CodeGenFunction &,
1314 const OMPExecutableDirective &,
1315 llvm::SmallVectorImpl<llvm::Value *> &) {}
1316
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001317void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001318 // Emit parallel region as a standalone region.
Alexey Bataevc99042b2018-03-15 18:10:54 +00001319 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001320 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001321 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001322 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001323 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1324 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001325 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001326 // propagation master's thread values of threadprivate variables to local
1327 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001328 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001329 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev25e5b442015-09-15 12:52:43 +00001330 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001331 }
1332 CGF.EmitOMPPrivateClause(S, PrivateScope);
1333 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1334 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00001335 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001336 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001337 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001338 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1339 emitEmptyBoundParameters);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001340 emitPostUpdateForReductionClause(*this, S,
1341 [](CodeGenFunction &) { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001342}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001343
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05001344static void emitBody(CodeGenFunction &CGF, const Stmt *S, const Stmt *NextLoop,
1345 int MaxLevel, int Level = 0) {
1346 assert(Level < MaxLevel && "Too deep lookup during loop body codegen.");
1347 const Stmt *SimplifiedS = S->IgnoreContainers();
1348 if (const auto *CS = dyn_cast<CompoundStmt>(SimplifiedS)) {
1349 PrettyStackTraceLoc CrashInfo(
1350 CGF.getContext().getSourceManager(), CS->getLBracLoc(),
1351 "LLVM IR generation of compound statement ('{}')");
1352
1353 // Keep track of the current cleanup stack depth, including debug scopes.
1354 CodeGenFunction::LexicalScope Scope(CGF, S->getSourceRange());
1355 for (const Stmt *CurStmt : CS->body())
1356 emitBody(CGF, CurStmt, NextLoop, MaxLevel, Level);
1357 return;
1358 }
1359 if (SimplifiedS == NextLoop) {
1360 if (const auto *For = dyn_cast<ForStmt>(SimplifiedS)) {
1361 S = For->getBody();
1362 } else {
1363 assert(isa<CXXForRangeStmt>(SimplifiedS) &&
1364 "Expected canonical for loop or range-based for loop.");
1365 const auto *CXXFor = cast<CXXForRangeStmt>(SimplifiedS);
1366 CGF.EmitStmt(CXXFor->getLoopVarStmt());
1367 S = CXXFor->getBody();
1368 }
1369 if (Level + 1 < MaxLevel) {
1370 NextLoop = OMPLoopDirective::tryToFindNextInnerLoop(
1371 S, /*TryImperfectlyNestedLoops=*/true);
1372 emitBody(CGF, S, NextLoop, MaxLevel, Level + 1);
1373 return;
1374 }
1375 }
1376 CGF.EmitStmt(S);
1377}
1378
Alexey Bataev0f34da12015-07-02 04:17:07 +00001379void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1380 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001381 RunCleanupsScope BodyScope(*this);
1382 // Update counters values on current iteration.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001383 for (const Expr *UE : D.updates())
1384 EmitIgnoredExpr(UE);
Alexander Musman3276a272015-03-21 10:12:56 +00001385 // Update the linear variables.
Alexey Bataev617db5f2017-12-04 15:38:33 +00001386 // In distribute directives only loop counters may be marked as linear, no
1387 // need to generate the code for them.
1388 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1389 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001390 for (const Expr *UE : C->updates())
1391 EmitIgnoredExpr(UE);
Alexey Bataev617db5f2017-12-04 15:38:33 +00001392 }
Alexander Musman3276a272015-03-21 10:12:56 +00001393 }
1394
Alexander Musmana5f070a2014-10-01 06:03:56 +00001395 // On a continue in the body, jump to the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001396 JumpDest Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001397 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexey Bataevf8be4762019-08-14 19:30:06 +00001398 for (const Expr *E : D.finals_conditions()) {
1399 if (!E)
1400 continue;
1401 // Check that loop counter in non-rectangular nest fits into the iteration
1402 // space.
1403 llvm::BasicBlock *NextBB = createBasicBlock("omp.body.next");
1404 EmitBranchOnBoolExpr(E, NextBB, Continue.getBlock(),
1405 getProfileCount(D.getBody()));
1406 EmitBlock(NextBB);
1407 }
Alexey Bataevbef93a92019-10-07 18:54:57 +00001408 // Emit loop variables for C++ range loops.
1409 const Stmt *Body =
1410 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001411 // Emit loop body.
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05001412 emitBody(*this, Body,
1413 OMPLoopDirective::tryToFindNextInnerLoop(
1414 Body, /*TryImperfectlyNestedLoops=*/true),
1415 D.getCollapsedNumber());
1416
Alexander Musmana5f070a2014-10-01 06:03:56 +00001417 // The end (updates/cleanups).
1418 EmitBlock(Continue.getBlock());
1419 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001420}
1421
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001422void CodeGenFunction::EmitOMPInnerLoop(
1423 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1424 const Expr *IncExpr,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001425 const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
1426 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001427 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001428
1429 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001430 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001431 EmitBlock(CondBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001432 const SourceRange R = S.getSourceRange();
Amara Emerson652795d2016-11-10 14:44:30 +00001433 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1434 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001435
1436 // If there are any cleanups between here and the loop-exit scope,
1437 // create a block to stage a loop exit along.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001438 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001439 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001440 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001441
Alexey Bataevddf3db92018-04-13 17:31:06 +00001442 llvm::BasicBlock *LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001443
Alexey Bataev2df54a02015-03-12 08:53:29 +00001444 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001445 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001446 if (ExitBlock != LoopExit.getBlock()) {
1447 EmitBlock(ExitBlock);
1448 EmitBranchThroughCleanup(LoopExit);
1449 }
1450
1451 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001452 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001453
1454 // Create a block for the increment.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001455 JumpDest Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001456 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1457
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001458 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001459
1460 // Emit "IV = IV + 1" and a back-edge to the condition block.
1461 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001462 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001463 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001464 BreakContinueStack.pop_back();
1465 EmitBranch(CondBlock);
1466 LoopStack.pop();
1467 // Emit the fall-through block.
1468 EmitBlock(LoopExit.getBlock());
1469}
1470
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001471bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001472 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001473 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001474 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001475 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001476 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001477 for (const Expr *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001478 HasLinears = true;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001479 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
1480 if (const auto *Ref =
1481 dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001482 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001483 const auto *OrigVD = cast<VarDecl>(Ref->getDecl());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001484 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
Alexey Bataevef549a82016-03-09 09:49:09 +00001485 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1486 VD->getInit()->getType(), VK_LValue,
1487 VD->getInit()->getExprLoc());
1488 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1489 VD->getType()),
1490 /*capturedByInit=*/false);
1491 EmitAutoVarCleanups(Emission);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001492 } else {
Alexey Bataevef549a82016-03-09 09:49:09 +00001493 EmitVarDecl(*VD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001494 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001495 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001496 // Emit the linear steps for the linear clauses.
1497 // If a step is not constant, it is pre-calculated before the loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001498 if (const auto *CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1499 if (const auto *SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001500 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001501 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001502 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001503 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001504 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001505 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001506}
1507
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001508void CodeGenFunction::EmitOMPLinearClauseFinal(
1509 const OMPLoopDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001510 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001511 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001512 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001513 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001514 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001515 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001516 auto IC = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001517 for (const Expr *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001518 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001519 if (llvm::Value *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001520 // If the first post-update expression is found, emit conditional
1521 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001522 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.linear.pu");
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001523 DoneBB = createBasicBlock(".omp.linear.pu.done");
1524 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1525 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001526 }
1527 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001528 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001529 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001530 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001531 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08001532 Address OrigAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001533 CodeGenFunction::OMPPrivateScope VarScope(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001534 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001535 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001536 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001537 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001538 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001539 if (const Expr *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001540 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001541 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001542 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001543 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001544}
1545
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001546static void emitAlignedClause(CodeGenFunction &CGF,
1547 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001548 if (!CGF.HaveInsertPoint())
1549 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001550 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Erich Keanef7593952019-10-11 14:59:44 +00001551 llvm::APInt ClauseAlignment(64, 0);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001552 if (const Expr *AlignmentExpr = Clause->getAlignment()) {
1553 auto *AlignmentCI =
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001554 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
Erich Keanef7593952019-10-11 14:59:44 +00001555 ClauseAlignment = AlignmentCI->getValue();
Alexander Musman09184fe2014-09-30 05:29:28 +00001556 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001557 for (const Expr *E : Clause->varlists()) {
Erich Keanef7593952019-10-11 14:59:44 +00001558 llvm::APInt Alignment(ClauseAlignment);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001559 if (Alignment == 0) {
1560 // OpenMP [2.8.1, Description]
1561 // If no optional parameter is specified, implementation-defined default
1562 // alignments for SIMD instructions on the target platforms are assumed.
1563 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001564 CGF.getContext()
1565 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1566 E->getType()->getPointeeType()))
1567 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001568 }
Erich Keanef7593952019-10-11 14:59:44 +00001569 assert((Alignment == 0 || Alignment.isPowerOf2()) &&
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001570 "alignment is not power of 2");
1571 if (Alignment != 0) {
1572 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
Roman Lebedevbd1c0872019-01-15 09:44:25 +00001573 CGF.EmitAlignmentAssumption(
Erich Keanef7593952019-10-11 14:59:44 +00001574 PtrValue, E, /*No second loc needed*/ SourceLocation(),
1575 llvm::ConstantInt::get(CGF.getLLVMContext(), Alignment));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001576 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001577 }
1578 }
1579}
1580
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001581void CodeGenFunction::EmitOMPPrivateLoopCounters(
1582 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1583 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001584 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001585 auto I = S.private_counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001586 for (const Expr *E : S.counters()) {
1587 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1588 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataevab4ea222018-03-07 18:17:06 +00001589 // Emit var without initialization.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001590 AutoVarEmission VarEmission = EmitAutoVarAlloca(*PrivateVD);
Alexey Bataevab4ea222018-03-07 18:17:06 +00001591 EmitAutoVarCleanups(VarEmission);
1592 LocalDeclMap.erase(PrivateVD);
1593 (void)LoopScope.addPrivate(VD, [&VarEmission]() {
1594 return VarEmission.getAllocatedAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001595 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001596 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1597 VD->hasGlobalStorage()) {
Alexey Bataevab4ea222018-03-07 18:17:06 +00001598 (void)LoopScope.addPrivate(PrivateVD, [this, VD, E]() {
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001599 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001600 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1601 E->getType(), VK_LValue, E->getExprLoc());
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08001602 return EmitLValue(&DRE).getAddress();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001603 });
Alexey Bataevab4ea222018-03-07 18:17:06 +00001604 } else {
1605 (void)LoopScope.addPrivate(PrivateVD, [&VarEmission]() {
1606 return VarEmission.getAllocatedAddress();
1607 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001608 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001609 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001610 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00001611 // Privatize extra loop counters used in loops for ordered(n) clauses.
1612 for (const auto *C : S.getClausesOfKind<OMPOrderedClause>()) {
1613 if (!C->getNumForLoops())
1614 continue;
1615 for (unsigned I = S.getCollapsedNumber(),
1616 E = C->getLoopNumIterations().size();
1617 I < E; ++I) {
Mike Rice0ed46662018-09-20 17:19:41 +00001618 const auto *DRE = cast<DeclRefExpr>(C->getLoopCounter(I));
Alexey Bataevf138fda2018-08-13 19:04:24 +00001619 const auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00001620 // Override only those variables that can be captured to avoid re-emission
1621 // of the variables declared within the loops.
1622 if (DRE->refersToEnclosingVariableOrCapture()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00001623 (void)LoopScope.addPrivate(VD, [this, DRE, VD]() {
1624 return CreateMemTemp(DRE->getType(), VD->getName());
1625 });
1626 }
1627 }
1628 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001629}
1630
Alexey Bataev62dbb972015-04-22 11:59:37 +00001631static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1632 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1633 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001634 if (!CGF.HaveInsertPoint())
1635 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001636 {
1637 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001638 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001639 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001640 // Get initial values of real counters.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001641 for (const Expr *I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001642 CGF.EmitIgnoredExpr(I);
1643 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001644 }
Alexey Bataevf8be4762019-08-14 19:30:06 +00001645 // Create temp loop control variables with their init values to support
1646 // non-rectangular loops.
1647 CodeGenFunction::OMPMapVars PreCondVars;
1648 for (const Expr * E: S.dependent_counters()) {
1649 if (!E)
1650 continue;
1651 assert(!E->getType().getNonReferenceType()->isRecordType() &&
1652 "dependent counter must not be an iterator.");
1653 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1654 Address CounterAddr =
1655 CGF.CreateMemTemp(VD->getType().getNonReferenceType());
1656 (void)PreCondVars.setVarAddr(CGF, VD, CounterAddr);
1657 }
1658 (void)PreCondVars.apply(CGF);
1659 for (const Expr *E : S.dependent_inits()) {
1660 if (!E)
1661 continue;
1662 CGF.EmitIgnoredExpr(E);
1663 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001664 // Check that loop is executed at least one time.
1665 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
Alexey Bataevf8be4762019-08-14 19:30:06 +00001666 PreCondVars.restore(CGF);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001667}
1668
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001669void CodeGenFunction::EmitOMPLinearClause(
1670 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1671 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001672 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001673 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1674 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001675 const auto *LoopDirective = cast<OMPLoopDirective>(&D);
1676 for (const Expr *C : LoopDirective->counters()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001677 SIMDLCVs.insert(
1678 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1679 }
1680 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001681 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001682 auto CurPrivate = C->privates().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001683 for (const Expr *E : C->varlists()) {
1684 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1685 const auto *PrivateVD =
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001686 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001687 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001688 bool IsRegistered = PrivateScope.addPrivate(VD, [this, PrivateVD]() {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001689 // Emit private VarDecl with copy init.
1690 EmitVarDecl(*PrivateVD);
1691 return GetAddrOfLocalVar(PrivateVD);
1692 });
1693 assert(IsRegistered && "linear var already registered as private");
1694 // Silence the warning about unused variable.
1695 (void)IsRegistered;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001696 } else {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001697 EmitVarDecl(*PrivateVD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001698 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001699 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001700 }
1701 }
1702}
1703
Alexey Bataev45bfad52015-08-21 12:19:04 +00001704static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001705 const OMPExecutableDirective &D,
1706 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001707 if (!CGF.HaveInsertPoint())
1708 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001709 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001710 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1711 /*ignoreResult=*/true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001712 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Alexey Bataev45bfad52015-08-21 12:19:04 +00001713 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1714 // In presence of finite 'safelen', it may be unsafe to mark all
1715 // the memory instructions parallel, because loop-carried
1716 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001717 if (!IsMonotonic)
1718 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001719 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001720 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1721 /*ignoreResult=*/true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001722 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001723 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001724 // In presence of finite 'safelen', it may be unsafe to mark all
1725 // the memory instructions parallel, because loop-carried
1726 // dependences of 'safelen' iterations are possible.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001727 CGF.LoopStack.setParallel(/*Enable=*/false);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001728 }
1729}
1730
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001731void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1732 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001733 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001734 LoopStack.setParallel(!IsMonotonic);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001735 LoopStack.setVectorizeEnable();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001736 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001737}
1738
Alexey Bataevef549a82016-03-09 09:49:09 +00001739void CodeGenFunction::EmitOMPSimdFinal(
1740 const OMPLoopDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001741 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001742 if (!HaveInsertPoint())
1743 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001744 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001745 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001746 auto IPC = D.private_counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001747 for (const Expr *F : D.finals()) {
1748 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
1749 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1750 const auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001751 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1752 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001753 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001754 if (llvm::Value *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001755 // If the first post-update expression is found, emit conditional
1756 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001757 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.final.then");
Alexey Bataevef549a82016-03-09 09:49:09 +00001758 DoneBB = createBasicBlock(".omp.final.done");
1759 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1760 EmitBlock(ThenBB);
1761 }
1762 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001763 Address OrigAddr = Address::invalid();
Alexey Bataevab4ea222018-03-07 18:17:06 +00001764 if (CED) {
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08001765 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
Alexey Bataevab4ea222018-03-07 18:17:06 +00001766 } else {
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001767 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(PrivateVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001768 /*RefersToEnclosingVariableOrCapture=*/false,
1769 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08001770 OrigAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001771 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001772 OMPPrivateScope VarScope(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001773 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001774 (void)VarScope.Privatize();
1775 EmitIgnoredExpr(F);
1776 }
1777 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001778 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001779 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001780 if (DoneBB)
1781 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001782}
1783
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001784static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1785 const OMPLoopDirective &S,
1786 CodeGenFunction::JumpDest LoopExit) {
1787 CGF.EmitOMPLoopBody(S, LoopExit);
1788 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001789}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001790
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001791/// Emit a helper variable and return corresponding lvalue.
1792static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1793 const DeclRefExpr *Helper) {
1794 auto VDecl = cast<VarDecl>(Helper->getDecl());
1795 CGF.EmitVarDecl(*VDecl);
1796 return CGF.EmitLValue(Helper);
1797}
1798
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05001799static void emitCommonSimdLoop(CodeGenFunction &CGF, const OMPLoopDirective &S,
1800 const RegionCodeGenTy &SimdInitGen,
1801 const RegionCodeGenTy &BodyCodeGen) {
1802 auto &&ThenGen = [&SimdInitGen, &BodyCodeGen](CodeGenFunction &CGF,
1803 PrePostActionTy &) {
1804 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
1805 SimdInitGen(CGF);
1806
1807 BodyCodeGen(CGF);
1808 };
1809 auto &&ElseGen = [&BodyCodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
1810 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
1811 CGF.LoopStack.setVectorizeEnable(/*Enable=*/false);
1812
1813 BodyCodeGen(CGF);
1814 };
1815 const Expr *IfCond = nullptr;
1816 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1817 if (CGF.getLangOpts().OpenMP >= 50 &&
1818 (C->getNameModifier() == OMPD_unknown ||
1819 C->getNameModifier() == OMPD_simd)) {
1820 IfCond = C->getCondition();
1821 break;
1822 }
1823 }
1824 if (IfCond) {
1825 CGF.CGM.getOpenMPRuntime().emitIfClause(CGF, IfCond, ThenGen, ElseGen);
1826 } else {
1827 RegionCodeGenTy ThenRCG(ThenGen);
1828 ThenRCG(CGF);
1829 }
1830}
1831
Alexey Bataevf8365372017-11-17 17:57:25 +00001832static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1833 PrePostActionTy &Action) {
1834 Action.Enter(CGF);
1835 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1836 "Expected simd directive");
1837 OMPLoopScope PreInitScope(CGF, S);
1838 // if (PreCond) {
1839 // for (IV in 0..LastIteration) BODY;
1840 // <Final counter/linear vars updates>;
1841 // }
1842 //
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001843 if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
1844 isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
1845 isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
1846 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1847 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1848 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001849
Alexey Bataevf8365372017-11-17 17:57:25 +00001850 // Emit: if (PreCond) - begin.
1851 // If the condition constant folds and can be elided, avoid emitting the
1852 // whole loop.
1853 bool CondConstant;
1854 llvm::BasicBlock *ContBlock = nullptr;
1855 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1856 if (!CondConstant)
1857 return;
1858 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001859 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("simd.if.then");
Alexey Bataevf8365372017-11-17 17:57:25 +00001860 ContBlock = CGF.createBasicBlock("simd.if.end");
1861 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1862 CGF.getProfileCount(&S));
1863 CGF.EmitBlock(ThenBlock);
1864 CGF.incrementProfileCounter(&S);
1865 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001866
Alexey Bataevf8365372017-11-17 17:57:25 +00001867 // Emit the loop iteration variable.
1868 const Expr *IVExpr = S.getIterationVariable();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001869 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
Alexey Bataevf8365372017-11-17 17:57:25 +00001870 CGF.EmitVarDecl(*IVDecl);
1871 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001872
Alexey Bataevf8365372017-11-17 17:57:25 +00001873 // Emit the iterations count variable.
1874 // If it is not a variable, Sema decided to calculate iterations count on
1875 // each iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00001876 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexey Bataevf8365372017-11-17 17:57:25 +00001877 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1878 // Emit calculation of the iterations count.
1879 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1880 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001881
Alexey Bataevf8365372017-11-17 17:57:25 +00001882 emitAlignedClause(CGF, S);
1883 (void)CGF.EmitOMPLinearClauseInit(S);
1884 {
1885 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1886 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1887 CGF.EmitOMPLinearClause(S, LoopScope);
1888 CGF.EmitOMPPrivateClause(S, LoopScope);
1889 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1890 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1891 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00001892 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
1893 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Alexey Bataevd08c0562019-11-19 12:07:54 -05001894
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05001895 emitCommonSimdLoop(
1896 CGF, S,
1897 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1898 CGF.EmitOMPSimdInit(S);
1899 },
1900 [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
1901 CGF.EmitOMPInnerLoop(
1902 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1903 [&S](CodeGenFunction &CGF) {
1904 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1905 CGF.EmitStopPoint(&S);
1906 },
1907 [](CodeGenFunction &) {});
1908 });
Alexey Bataevddf3db92018-04-13 17:31:06 +00001909 CGF.EmitOMPSimdFinal(S, [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001910 // Emit final copy of the lastprivate variables at the end of loops.
1911 if (HasLastprivateClause)
1912 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1913 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001914 emitPostUpdateForReductionClause(CGF, S,
1915 [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001916 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001917 CGF.EmitOMPLinearClauseFinal(S, [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001918 // Emit: if (PreCond) - end.
1919 if (ContBlock) {
1920 CGF.EmitBranch(ContBlock);
1921 CGF.EmitBlock(ContBlock, true);
1922 }
1923}
1924
1925void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1926 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1927 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001928 };
Alexey Bataev475a7442018-01-12 19:39:11 +00001929 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001930 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001931}
1932
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001933void CodeGenFunction::EmitOMPOuterLoop(
1934 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1935 CodeGenFunction::OMPPrivateScope &LoopScope,
1936 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1937 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1938 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001939 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001940
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001941 const Expr *IVExpr = S.getIterationVariable();
1942 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1943 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1944
Alexey Bataevddf3db92018-04-13 17:31:06 +00001945 JumpDest LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001946
1947 // Start the loop with a block that tests the condition.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001948 llvm::BasicBlock *CondBlock = createBasicBlock("omp.dispatch.cond");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001949 EmitBlock(CondBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001950 const SourceRange R = S.getSourceRange();
Amara Emerson652795d2016-11-10 14:44:30 +00001951 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1952 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001953
1954 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001955 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001956 // UB = min(UB, GlobalUB) or
1957 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1958 // 'distribute parallel for')
1959 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001960 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001961 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001962 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001963 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001964 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001965 BoolCondVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001966 RT.emitForNext(*this, S.getBeginLoc(), IVSize, IVSigned, LoopArgs.IL,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001967 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001968 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001969
1970 // If there are any cleanups between here and the loop-exit scope,
1971 // create a block to stage a loop exit along.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001972 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001973 if (LoopScope.requiresCleanups())
1974 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1975
Alexey Bataevddf3db92018-04-13 17:31:06 +00001976 llvm::BasicBlock *LoopBody = createBasicBlock("omp.dispatch.body");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001977 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1978 if (ExitBlock != LoopExit.getBlock()) {
1979 EmitBlock(ExitBlock);
1980 EmitBranchThroughCleanup(LoopExit);
1981 }
1982 EmitBlock(LoopBody);
1983
Alexander Musman92bdaab2015-03-12 13:37:50 +00001984 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1985 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001986 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001987 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001988
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001989 // Create a block for the increment.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001990 JumpDest Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001991 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1992
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05001993 emitCommonSimdLoop(
1994 *this, S,
1995 [&S, IsMonotonic](CodeGenFunction &CGF, PrePostActionTy &) {
1996 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1997 // with dynamic/guided scheduling and without ordered clause.
1998 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1999 CGF.LoopStack.setParallel(!IsMonotonic);
2000 else
2001 CGF.EmitOMPSimdInit(S, IsMonotonic);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002002 },
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002003 [&S, &LoopArgs, LoopExit, &CodeGenLoop, IVSize, IVSigned, &CodeGenOrdered,
2004 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
2005 SourceLocation Loc = S.getBeginLoc();
2006 // when 'distribute' is not combined with a 'for':
2007 // while (idx <= UB) { BODY; ++idx; }
2008 // when 'distribute' is combined with a 'for'
2009 // (e.g. 'distribute parallel for')
2010 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
2011 CGF.EmitOMPInnerLoop(
2012 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
2013 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
2014 CodeGenLoop(CGF, S, LoopExit);
2015 },
2016 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
2017 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
2018 });
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002019 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002020
2021 EmitBlock(Continue.getBlock());
2022 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002023 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002024 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002025 EmitIgnoredExpr(LoopArgs.NextLB);
2026 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002027 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002028
2029 EmitBranch(CondBlock);
2030 LoopStack.pop();
2031 // Emit the fall-through block.
2032 EmitBlock(LoopExit.getBlock());
2033
2034 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002035 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
2036 if (!DynamicOrOrdered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002037 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00002038 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002039 };
2040 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002041}
2042
2043void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002044 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002045 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002046 const OMPLoopArguments &LoopArgs,
2047 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002048 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002049
2050 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002051 const bool DynamicOrOrdered =
2052 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002053
2054 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002055 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002056 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002057 "static non-chunked schedule does not need outer loop");
2058
2059 // Emit outer loop.
2060 //
2061 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2062 // When schedule(dynamic,chunk_size) is specified, the iterations are
2063 // distributed to threads in the team in chunks as the threads request them.
2064 // Each thread executes a chunk of iterations, then requests another chunk,
2065 // until no chunks remain to be distributed. Each chunk contains chunk_size
2066 // iterations, except for the last chunk to be distributed, which may have
2067 // fewer iterations. When no chunk_size is specified, it defaults to 1.
2068 //
2069 // When schedule(guided,chunk_size) is specified, the iterations are assigned
2070 // to threads in the team in chunks as the executing threads request them.
2071 // Each thread executes a chunk of iterations, then requests another chunk,
2072 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
2073 // each chunk is proportional to the number of unassigned iterations divided
2074 // by the number of threads in the team, decreasing to 1. For a chunk_size
2075 // with value k (greater than 1), the size of each chunk is determined in the
2076 // same way, with the restriction that the chunks do not contain fewer than k
2077 // iterations (except for the last chunk to be assigned, which may have fewer
2078 // than k iterations).
2079 //
2080 // When schedule(auto) is specified, the decision regarding scheduling is
2081 // delegated to the compiler and/or runtime system. The programmer gives the
2082 // implementation the freedom to choose any possible mapping of iterations to
2083 // threads in the team.
2084 //
2085 // When schedule(runtime) is specified, the decision regarding scheduling is
2086 // deferred until run time, and the schedule and chunk size are taken from the
2087 // run-sched-var ICV. If the ICV is set to auto, the schedule is
2088 // implementation defined
2089 //
2090 // while(__kmpc_dispatch_next(&LB, &UB)) {
2091 // idx = LB;
2092 // while (idx <= UB) { BODY; ++idx;
2093 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
2094 // } // inner loop
2095 // }
2096 //
2097 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2098 // When schedule(static, chunk_size) is specified, iterations are divided into
2099 // chunks of size chunk_size, and the chunks are assigned to the threads in
2100 // the team in a round-robin fashion in the order of the thread number.
2101 //
2102 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
2103 // while (idx <= UB) { BODY; ++idx; } // inner loop
2104 // LB = LB + ST;
2105 // UB = UB + ST;
2106 // }
2107 //
2108
2109 const Expr *IVExpr = S.getIterationVariable();
2110 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2111 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2112
2113 if (DynamicOrOrdered) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002114 const std::pair<llvm::Value *, llvm::Value *> DispatchBounds =
2115 CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002116 llvm::Value *LBVal = DispatchBounds.first;
2117 llvm::Value *UBVal = DispatchBounds.second;
2118 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
2119 LoopArgs.Chunk};
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002120 RT.emitForDispatchInit(*this, S.getBeginLoc(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002121 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002122 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002123 CGOpenMPRuntime::StaticRTInput StaticInit(
2124 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
2125 LoopArgs.ST, LoopArgs.Chunk);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002126 RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(),
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002127 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002128 }
2129
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002130 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
2131 const unsigned IVSize,
2132 const bool IVSigned) {
2133 if (Ordered) {
2134 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
2135 IVSigned);
2136 }
2137 };
2138
2139 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
2140 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
2141 OuterLoopArgs.IncExpr = S.getInc();
2142 OuterLoopArgs.Init = S.getInit();
2143 OuterLoopArgs.Cond = S.getCond();
2144 OuterLoopArgs.NextLB = S.getNextLowerBound();
2145 OuterLoopArgs.NextUB = S.getNextUpperBound();
2146 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
2147 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002148}
2149
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002150static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
2151 const unsigned IVSize, const bool IVSigned) {}
2152
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002153void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002154 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
2155 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
2156 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002157
Alexey Bataevddf3db92018-04-13 17:31:06 +00002158 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002159
2160 // Emit outer loop.
2161 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
2162 // dynamic
2163 //
2164
2165 const Expr *IVExpr = S.getIterationVariable();
2166 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2167 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2168
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002169 CGOpenMPRuntime::StaticRTInput StaticInit(
2170 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
2171 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002172 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002173
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002174 // for combined 'distribute' and 'for' the increment expression of distribute
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002175 // is stored in DistInc. For 'distribute' alone, it is in Inc.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002176 Expr *IncExpr;
2177 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
2178 IncExpr = S.getDistInc();
2179 else
2180 IncExpr = S.getInc();
2181
2182 // this routine is shared by 'omp distribute parallel for' and
2183 // 'omp distribute': select the right EUB expression depending on the
2184 // directive
2185 OMPLoopArguments OuterLoopArgs;
2186 OuterLoopArgs.LB = LoopArgs.LB;
2187 OuterLoopArgs.UB = LoopArgs.UB;
2188 OuterLoopArgs.ST = LoopArgs.ST;
2189 OuterLoopArgs.IL = LoopArgs.IL;
2190 OuterLoopArgs.Chunk = LoopArgs.Chunk;
2191 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2192 ? S.getCombinedEnsureUpperBound()
2193 : S.getEnsureUpperBound();
2194 OuterLoopArgs.IncExpr = IncExpr;
2195 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2196 ? S.getCombinedInit()
2197 : S.getInit();
2198 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2199 ? S.getCombinedCond()
2200 : S.getCond();
2201 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2202 ? S.getCombinedNextLowerBound()
2203 : S.getNextLowerBound();
2204 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2205 ? S.getCombinedNextUpperBound()
2206 : S.getNextUpperBound();
2207
2208 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
2209 LoopScope, OuterLoopArgs, CodeGenLoopContent,
2210 emitEmptyOrdered);
2211}
2212
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002213static std::pair<LValue, LValue>
2214emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
2215 const OMPExecutableDirective &S) {
2216 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2217 LValue LB =
2218 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2219 LValue UB =
2220 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2221
2222 // When composing 'distribute' with 'for' (e.g. as in 'distribute
2223 // parallel for') we need to use the 'distribute'
2224 // chunk lower and upper bounds rather than the whole loop iteration
2225 // space. These are parameters to the outlined function for 'parallel'
2226 // and we copy the bounds of the previous schedule into the
2227 // the current ones.
2228 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
2229 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002230 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
2231 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002232 PrevLBVal = CGF.EmitScalarConversion(
2233 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002234 LS.getIterationVariable()->getType(),
2235 LS.getPrevLowerBoundVariable()->getExprLoc());
2236 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
2237 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002238 PrevUBVal = CGF.EmitScalarConversion(
2239 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002240 LS.getIterationVariable()->getType(),
2241 LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002242
2243 CGF.EmitStoreOfScalar(PrevLBVal, LB);
2244 CGF.EmitStoreOfScalar(PrevUBVal, UB);
2245
2246 return {LB, UB};
2247}
2248
2249/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
2250/// we need to use the LB and UB expressions generated by the worksharing
2251/// code generation support, whereas in non combined situations we would
2252/// just emit 0 and the LastIteration expression
2253/// This function is necessary due to the difference of the LB and UB
2254/// types for the RT emission routines for 'for_static_init' and
2255/// 'for_dispatch_init'
2256static std::pair<llvm::Value *, llvm::Value *>
2257emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
2258 const OMPExecutableDirective &S,
2259 Address LB, Address UB) {
2260 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2261 const Expr *IVExpr = LS.getIterationVariable();
2262 // when implementing a dynamic schedule for a 'for' combined with a
2263 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
2264 // is not normalized as each team only executes its own assigned
2265 // distribute chunk
2266 QualType IteratorTy = IVExpr->getType();
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002267 llvm::Value *LBVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002268 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002269 llvm::Value *UBVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002270 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002271 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00002272}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002273
2274static void emitDistributeParallelForDistributeInnerBoundParams(
2275 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2276 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2277 const auto &Dir = cast<OMPLoopDirective>(S);
2278 LValue LB =
2279 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08002280 llvm::Value *LBCast = CGF.Builder.CreateIntCast(
2281 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002282 CapturedVars.push_back(LBCast);
2283 LValue UB =
2284 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2285
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08002286 llvm::Value *UBCast = CGF.Builder.CreateIntCast(
2287 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002288 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00002289}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002290
2291static void
2292emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2293 const OMPLoopDirective &S,
2294 CodeGenFunction::JumpDest LoopExit) {
2295 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00002296 PrePostActionTy &Action) {
2297 Action.Enter(CGF);
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002298 bool HasCancel = false;
2299 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2300 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2301 HasCancel = D->hasCancel();
2302 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2303 HasCancel = D->hasCancel();
Alexey Bataev16e79882017-11-22 21:12:03 +00002304 else if (const auto *D =
2305 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2306 HasCancel = D->hasCancel();
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002307 }
2308 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2309 HasCancel);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002310 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2311 emitDistributeParallelForInnerBounds,
2312 emitDistributeParallelForDispatchBounds);
2313 };
2314
2315 emitCommonOMPParallelDirective(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002316 CGF, S,
2317 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2318 CGInlinedWorksharingLoop,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002319 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002320}
2321
Carlo Bertolli9925f152016-06-27 14:55:37 +00002322void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2323 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002324 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2325 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2326 S.getDistInc());
2327 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002328 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev10a54312017-11-27 16:54:08 +00002329 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002330}
2331
Kelvin Li4a39add2016-07-05 05:00:15 +00002332void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2333 const OMPDistributeParallelForSimdDirective &S) {
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002334 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2335 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2336 S.getDistInc());
2337 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002338 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002339 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Kelvin Li4a39add2016-07-05 05:00:15 +00002340}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002341
2342void CodeGenFunction::EmitOMPDistributeSimdDirective(
2343 const OMPDistributeSimdDirective &S) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00002344 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2345 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2346 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002347 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev617db5f2017-12-04 15:38:33 +00002348 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002349}
2350
Alexey Bataevf8365372017-11-17 17:57:25 +00002351void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2352 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2353 // Emit SPMD target parallel for region as a standalone region.
2354 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2355 emitOMPSimdRegion(CGF, S, Action);
2356 };
2357 llvm::Function *Fn;
2358 llvm::Constant *Addr;
2359 // Emit target region as a standalone region.
2360 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2361 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2362 assert(Fn && Addr && "Target device function emission failed.");
2363}
2364
Kelvin Li986330c2016-07-20 22:57:10 +00002365void CodeGenFunction::EmitOMPTargetSimdDirective(
2366 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002367 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2368 emitOMPSimdRegion(CGF, S, Action);
2369 };
2370 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002371}
2372
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002373namespace {
2374 struct ScheduleKindModifiersTy {
2375 OpenMPScheduleClauseKind Kind;
2376 OpenMPScheduleClauseModifier M1;
2377 OpenMPScheduleClauseModifier M2;
2378 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2379 OpenMPScheduleClauseModifier M1,
2380 OpenMPScheduleClauseModifier M2)
2381 : Kind(Kind), M1(M1), M2(M2) {}
2382 };
2383} // namespace
2384
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002385bool CodeGenFunction::EmitOMPWorksharingLoop(
2386 const OMPLoopDirective &S, Expr *EUB,
2387 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2388 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002389 // Emit the loop iteration variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002390 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2391 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
Alexander Musmanc6388682014-12-15 07:07:06 +00002392 EmitVarDecl(*IVDecl);
2393
2394 // Emit the iterations count variable.
2395 // If it is not a variable, Sema decided to calculate iterations count on each
2396 // iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00002397 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002398 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2399 // Emit calculation of the iterations count.
2400 EmitIgnoredExpr(S.getCalcLastIteration());
2401 }
2402
Alexey Bataevddf3db92018-04-13 17:31:06 +00002403 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Alexander Musmanc6388682014-12-15 07:07:06 +00002404
Alexey Bataev38e89532015-04-16 04:54:05 +00002405 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002406 // Check pre-condition.
2407 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002408 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002409 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002410 // If the condition constant folds and can be elided, avoid emitting the
2411 // whole loop.
2412 bool CondConstant;
2413 llvm::BasicBlock *ContBlock = nullptr;
2414 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2415 if (!CondConstant)
2416 return false;
2417 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002418 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
Alexey Bataev62dbb972015-04-22 11:59:37 +00002419 ContBlock = createBasicBlock("omp.precond.end");
2420 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002421 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002422 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002423 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002424 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002425
Alexey Bataevea33dee2018-02-15 23:39:43 +00002426 RunCleanupsScope DoacrossCleanupScope(*this);
Alexey Bataev8b427062016-05-25 12:36:08 +00002427 bool Ordered = false;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002428 if (const auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
Alexey Bataev8b427062016-05-25 12:36:08 +00002429 if (OrderedClause->getNumForLoops())
Alexey Bataevf138fda2018-08-13 19:04:24 +00002430 RT.emitDoacrossInit(*this, S, OrderedClause->getLoopNumIterations());
Alexey Bataev8b427062016-05-25 12:36:08 +00002431 else
2432 Ordered = true;
2433 }
2434
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002435 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002436 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002437 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002438 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002439
2440 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2441 LValue LB = Bounds.first;
2442 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002443 LValue ST =
2444 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2445 LValue IL =
2446 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2447
Alexander Musmanc6388682014-12-15 07:07:06 +00002448 // Emit 'then' code.
2449 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002450 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002451 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002452 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002453 // initialization of firstprivate variables and post-update of
2454 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002455 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002456 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002457 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002458 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002459 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002460 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002461 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002462 EmitOMPPrivateLoopCounters(S, LoopScope);
2463 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002464 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00002465 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2466 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002467
2468 // Detect the loop schedule kind and chunk.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002469 const Expr *ChunkExpr = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002470 OpenMPScheduleTy ScheduleKind;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002471 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002472 ScheduleKind.Schedule = C->getScheduleKind();
2473 ScheduleKind.M1 = C->getFirstScheduleModifier();
2474 ScheduleKind.M2 = C->getSecondScheduleModifier();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002475 ChunkExpr = C->getChunkSize();
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00002476 } else {
2477 // Default behaviour for schedule clause.
2478 CGM.getOpenMPRuntime().getDefaultScheduleAndChunk(
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002479 *this, S, ScheduleKind.Schedule, ChunkExpr);
2480 }
2481 bool HasChunkSizeOne = false;
2482 llvm::Value *Chunk = nullptr;
2483 if (ChunkExpr) {
2484 Chunk = EmitScalarExpr(ChunkExpr);
2485 Chunk = EmitScalarConversion(Chunk, ChunkExpr->getType(),
2486 S.getIterationVariable()->getType(),
2487 S.getBeginLoc());
Fangrui Song407659a2018-11-30 23:41:18 +00002488 Expr::EvalResult Result;
2489 if (ChunkExpr->EvaluateAsInt(Result, getContext())) {
2490 llvm::APSInt EvaluatedChunk = Result.Val.getInt();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002491 HasChunkSizeOne = (EvaluatedChunk.getLimitedValue() == 1);
Fangrui Song407659a2018-11-30 23:41:18 +00002492 }
Alexey Bataev3392d762016-02-16 11:18:12 +00002493 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002494 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2495 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002496 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2497 // If the static schedule kind is specified or if the ordered clause is
2498 // specified, and if no monotonic modifier is specified, the effect will
2499 // be as if the monotonic modifier was specified.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002500 bool StaticChunkedOne = RT.isStaticChunked(ScheduleKind.Schedule,
2501 /* Chunked */ Chunk != nullptr) && HasChunkSizeOne &&
2502 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
2503 if ((RT.isStaticNonchunked(ScheduleKind.Schedule,
2504 /* Chunked */ Chunk != nullptr) ||
2505 StaticChunkedOne) &&
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002506 !Ordered) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002507 JumpDest LoopExit =
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002508 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002509 emitCommonSimdLoop(
2510 *this, S,
2511 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2512 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2513 CGF.EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002514 },
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002515 [IVSize, IVSigned, Ordered, IL, LB, UB, ST, StaticChunkedOne, Chunk,
2516 &S, ScheduleKind, LoopExit,
2517 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
2518 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2519 // When no chunk_size is specified, the iteration space is divided
2520 // into chunks that are approximately equal in size, and at most
2521 // one chunk is distributed to each thread. Note that the size of
2522 // the chunks is unspecified in this case.
2523 CGOpenMPRuntime::StaticRTInput StaticInit(
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08002524 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
2525 UB.getAddress(), ST.getAddress(),
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002526 StaticChunkedOne ? Chunk : nullptr);
2527 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
2528 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind,
2529 StaticInit);
2530 // UB = min(UB, GlobalUB);
2531 if (!StaticChunkedOne)
2532 CGF.EmitIgnoredExpr(S.getEnsureUpperBound());
2533 // IV = LB;
2534 CGF.EmitIgnoredExpr(S.getInit());
2535 // For unchunked static schedule generate:
2536 //
2537 // while (idx <= UB) {
2538 // BODY;
2539 // ++idx;
2540 // }
2541 //
2542 // For static schedule with chunk one:
2543 //
2544 // while (IV <= PrevUB) {
2545 // BODY;
2546 // IV += ST;
2547 // }
2548 CGF.EmitOMPInnerLoop(
2549 S, LoopScope.requiresCleanups(),
2550 StaticChunkedOne ? S.getCombinedParForInDistCond()
2551 : S.getCond(),
2552 StaticChunkedOne ? S.getDistInc() : S.getInc(),
2553 [&S, LoopExit](CodeGenFunction &CGF) {
2554 CGF.EmitOMPLoopBody(S, LoopExit);
2555 CGF.EmitStopPoint(&S);
2556 },
2557 [](CodeGenFunction &) {});
2558 });
Alexey Bataev0f34da12015-07-02 04:17:07 +00002559 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002560 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002561 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002562 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00002563 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002564 };
2565 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002566 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002567 const bool IsMonotonic =
2568 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2569 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2570 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2571 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002572 // Emit the outer loop, which requests its work chunk [LB..UB] from
2573 // runtime and runs the inner loop to process it.
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08002574 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2575 ST.getAddress(), IL.getAddress(),
2576 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002577 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002578 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002579 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002580 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002581 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
2582 return CGF.Builder.CreateIsNotNull(
2583 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
2584 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002585 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002586 EmitOMPReductionClauseFinal(
2587 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2588 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2589 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002590 // Emit post-update of the reduction variables if IsLastIter != 0.
2591 emitPostUpdateForReductionClause(
Alexey Bataevddf3db92018-04-13 17:31:06 +00002592 *this, S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataev61205072016-03-02 04:57:40 +00002593 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002594 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataev61205072016-03-02 04:57:40 +00002595 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002596 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2597 if (HasLastprivateClause)
2598 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002599 S, isOpenMPSimdDirective(S.getDirectiveKind()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002600 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002601 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00002602 EmitOMPLinearClauseFinal(S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataevef549a82016-03-09 09:49:09 +00002603 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002604 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataevef549a82016-03-09 09:49:09 +00002605 });
Alexey Bataevea33dee2018-02-15 23:39:43 +00002606 DoacrossCleanupScope.ForceCleanup();
Alexander Musmanc6388682014-12-15 07:07:06 +00002607 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002608 if (ContBlock) {
2609 EmitBranch(ContBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002610 EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002611 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002612 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002613 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002614}
2615
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002616/// The following two functions generate expressions for the loop lower
2617/// and upper bounds in case of static and dynamic (dispatch) schedule
2618/// of the associated 'for' or 'distribute' loop.
2619static std::pair<LValue, LValue>
2620emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002621 const auto &LS = cast<OMPLoopDirective>(S);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002622 LValue LB =
2623 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2624 LValue UB =
2625 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2626 return {LB, UB};
2627}
2628
2629/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2630/// consider the lower and upper bound expressions generated by the
2631/// worksharing loop support, but we use 0 and the iteration space size as
2632/// constants
2633static std::pair<llvm::Value *, llvm::Value *>
2634emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2635 Address LB, Address UB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002636 const auto &LS = cast<OMPLoopDirective>(S);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002637 const Expr *IVExpr = LS.getIterationVariable();
2638 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2639 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2640 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2641 return {LBVal, UBVal};
2642}
2643
Alexander Musmanc6388682014-12-15 07:07:06 +00002644void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002645 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002646 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2647 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002648 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002649 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2650 emitForLoopBounds,
2651 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002652 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002653 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002654 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002655 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2656 S.hasCancel());
2657 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002658
2659 // Emit an implicit barrier at the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002660 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002661 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002662}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002663
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002664void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002665 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002666 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2667 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002668 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2669 emitForLoopBounds,
2670 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002671 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002672 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002673 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002674 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2675 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002676
2677 // Emit an implicit barrier at the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002678 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002679 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002680}
2681
Alexey Bataev2df54a02015-03-12 08:53:29 +00002682static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2683 const Twine &Name,
2684 llvm::Value *Init = nullptr) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002685 LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002686 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002687 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002688 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002689}
2690
Alexey Bataev3392d762016-02-16 11:18:12 +00002691void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002692 const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
2693 const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002694 bool HasLastprivates = false;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002695 auto &&CodeGen = [&S, CapturedStmt, CS,
2696 &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) {
2697 ASTContext &C = CGF.getContext();
2698 QualType KmpInt32Ty =
2699 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002700 // Emit helper vars inits.
2701 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2702 CGF.Builder.getInt32(0));
Alexey Bataevddf3db92018-04-13 17:31:06 +00002703 llvm::ConstantInt *GlobalUBVal = CS != nullptr
2704 ? CGF.Builder.getInt32(CS->size() - 1)
2705 : CGF.Builder.getInt32(0);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002706 LValue UB =
2707 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2708 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2709 CGF.Builder.getInt32(1));
2710 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2711 CGF.Builder.getInt32(0));
2712 // Loop counter.
2713 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002714 OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002715 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002716 OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002717 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2718 // Generate condition for loop.
2719 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002720 OK_Ordinary, S.getBeginLoc(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002721 // Increment for loop counter.
2722 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002723 S.getBeginLoc(), true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002724 auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002725 // Iterate through all sections and emit a switch construct:
2726 // switch (IV) {
2727 // case 0:
2728 // <SectionStmt[0]>;
2729 // break;
2730 // ...
2731 // case <NumSection> - 1:
2732 // <SectionStmt[<NumSection> - 1]>;
2733 // break;
2734 // }
2735 // .omp.sections.exit:
Alexey Bataevddf3db92018-04-13 17:31:06 +00002736 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2737 llvm::SwitchInst *SwitchStmt =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002738 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002739 ExitBB, CS == nullptr ? 1 : CS->size());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002740 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002741 unsigned CaseNumber = 0;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002742 for (const Stmt *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002743 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2744 CGF.EmitBlock(CaseBB);
2745 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002746 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002747 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002748 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002749 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002750 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002751 llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case");
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002752 CGF.EmitBlock(CaseBB);
2753 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002754 CGF.EmitStmt(CapturedStmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002755 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002756 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002757 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002758 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002759
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002760 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2761 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002762 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002763 // initialization of firstprivate variables and post-update of lastprivate
2764 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002765 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002766 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002767 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002768 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002769 CGF.EmitOMPPrivateClause(S, LoopScope);
2770 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2771 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2772 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00002773 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2774 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002775
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002776 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002777 OpenMPScheduleTy ScheduleKind;
2778 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002779 CGOpenMPRuntime::StaticRTInput StaticInit(
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08002780 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2781 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002782 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002783 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002784 // UB = min(UB, GlobalUB);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002785 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc());
Alexey Bataevddf3db92018-04-13 17:31:06 +00002786 llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect(
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002787 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2788 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2789 // IV = LB;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002790 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002791 // while (idx <= UB) { BODY; ++idx; }
2792 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2793 [](CodeGenFunction &) {});
2794 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002795 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002796 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00002797 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002798 };
2799 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002800 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002801 // Emit post-update of the reduction variables if IsLastIter != 0.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002802 emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) {
2803 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002804 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataevddf3db92018-04-13 17:31:06 +00002805 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002806
2807 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2808 if (HasLastprivates)
2809 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002810 S, /*NoFinals=*/false,
2811 CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002812 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002813 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002814
2815 bool HasCancel = false;
2816 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2817 HasCancel = OSD->hasCancel();
2818 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2819 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002820 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002821 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2822 HasCancel);
2823 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2824 // clause. Otherwise the barrier will be generated by the codegen for the
2825 // directive.
2826 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002827 // Emit implicit barrier to synchronize threads and avoid data races on
2828 // initialization of firstprivate variables.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002829 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002830 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002831 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002832}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002833
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002834void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002835 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002836 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002837 EmitSections(S);
2838 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002839 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002840 if (!S.getSingleClause<OMPNowaitClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002841 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
Alexey Bataev3392d762016-02-16 11:18:12 +00002842 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002843 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002844}
2845
2846void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002847 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002848 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002849 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002850 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002851 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2852 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002853}
2854
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002855void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002856 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002857 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002858 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002859 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002860 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002861 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002862 // Build a list of copyprivate variables along with helper expressions
2863 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002864 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002865 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002866 DestExprs.append(C->destination_exprs().begin(),
2867 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002868 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002869 AssignmentOps.append(C->assignment_ops().begin(),
2870 C->assignment_ops().end());
2871 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002872 // Emit code for 'single' region along with 'copyprivate' clauses
2873 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2874 Action.Enter(CGF);
2875 OMPPrivateScope SingleScope(CGF);
2876 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2877 CGF.EmitOMPPrivateClause(S, SingleScope);
2878 (void)SingleScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00002879 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002880 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002881 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002882 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002883 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(),
Alexey Bataev3392d762016-02-16 11:18:12 +00002884 CopyprivateVars, DestExprs,
2885 SrcExprs, AssignmentOps);
2886 }
2887 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2888 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002889 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002890 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002891 *this, S.getBeginLoc(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002892 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002893 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002894}
2895
Alexey Bataev8d690652014-12-04 07:23:53 +00002896void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002897 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2898 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002899 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002900 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002901 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002902 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
Alexander Musman80c22892014-07-17 08:54:58 +00002903}
2904
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002905void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002906 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2907 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002908 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002909 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00002910 const Expr *Hint = nullptr;
2911 if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
Alexey Bataevfc57d162015-12-15 10:55:09 +00002912 Hint = HintClause->getHint();
Alexey Bataev475a7442018-01-12 19:39:11 +00002913 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002914 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2915 S.getDirectiveName().getAsString(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002916 CodeGen, S.getBeginLoc(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002917}
2918
Alexey Bataev671605e2015-04-13 05:28:11 +00002919void CodeGenFunction::EmitOMPParallelForDirective(
2920 const OMPParallelForDirective &S) {
2921 // Emit directive as a combined directive that consists of two implicit
2922 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00002923 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2924 Action.Enter(CGF);
Alexey Bataev957d8562016-11-17 15:12:05 +00002925 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002926 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2927 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002928 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002929 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2930 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002931}
2932
Alexander Musmane4e893b2014-09-23 09:33:00 +00002933void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002934 const OMPParallelForSimdDirective &S) {
2935 // Emit directive as a combined directive that consists of two implicit
2936 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00002937 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2938 Action.Enter(CGF);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002939 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2940 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002941 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002942 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2943 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002944}
2945
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002946void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002947 const OMPParallelSectionsDirective &S) {
2948 // Emit directive as a combined directive that consists of two implicit
2949 // directives: 'parallel' with 'sections' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00002950 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2951 Action.Enter(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002952 CGF.EmitSections(S);
2953 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002954 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2955 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002956}
2957
Alexey Bataev475a7442018-01-12 19:39:11 +00002958void CodeGenFunction::EmitOMPTaskBasedDirective(
2959 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
2960 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
2961 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002962 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00002963 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002964 auto I = CS->getCapturedDecl()->param_begin();
2965 auto PartId = std::next(I);
2966 auto TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002967 // Check if the task is final
2968 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2969 // If the condition constant folds and can be elided, try to avoid emitting
2970 // the condition and the dead arm of the if/else.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002971 const Expr *Cond = Clause->getCondition();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002972 bool CondConstant;
2973 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2974 Data.Final.setInt(CondConstant);
2975 else
2976 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2977 } else {
2978 // By default the task is not final.
2979 Data.Final.setInt(/*IntVal=*/false);
2980 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002981 // Check if the task has 'priority' clause.
2982 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002983 const Expr *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002984 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002985 Data.Priority.setPointer(EmitScalarConversion(
2986 EmitScalarExpr(Prio), Prio->getType(),
2987 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2988 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002989 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002990 // The first function argument for tasks is a thread id, the second one is a
2991 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002992 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2993 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002994 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002995 auto IRef = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002996 for (const Expr *IInit : C->private_copies()) {
2997 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002998 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002999 Data.PrivateVars.push_back(*IRef);
3000 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003001 }
3002 ++IRef;
3003 }
3004 }
3005 EmittedAsPrivate.clear();
3006 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003007 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003008 auto IRef = C->varlist_begin();
3009 auto IElemInitRef = C->inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003010 for (const Expr *IInit : C->private_copies()) {
3011 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003012 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003013 Data.FirstprivateVars.push_back(*IRef);
3014 Data.FirstprivateCopies.push_back(IInit);
3015 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003016 }
Richard Trieucc3949d2016-02-18 22:34:54 +00003017 ++IRef;
3018 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003019 }
3020 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003021 // Get list of lastprivate variables (for taskloops).
3022 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
3023 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
3024 auto IRef = C->varlist_begin();
3025 auto ID = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003026 for (const Expr *IInit : C->private_copies()) {
3027 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003028 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
3029 Data.LastprivateVars.push_back(*IRef);
3030 Data.LastprivateCopies.push_back(IInit);
3031 }
3032 LastprivateDstsOrigs.insert(
3033 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
3034 cast<DeclRefExpr>(*IRef)});
3035 ++IRef;
3036 ++ID;
3037 }
3038 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003039 SmallVector<const Expr *, 4> LHSs;
3040 SmallVector<const Expr *, 4> RHSs;
3041 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
3042 auto IPriv = C->privates().begin();
3043 auto IRed = C->reduction_ops().begin();
3044 auto ILHS = C->lhs_exprs().begin();
3045 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003046 for (const Expr *Ref : C->varlists()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003047 Data.ReductionVars.emplace_back(Ref);
3048 Data.ReductionCopies.emplace_back(*IPriv);
3049 Data.ReductionOps.emplace_back(*IRed);
3050 LHSs.emplace_back(*ILHS);
3051 RHSs.emplace_back(*IRHS);
3052 std::advance(IPriv, 1);
3053 std::advance(IRed, 1);
3054 std::advance(ILHS, 1);
3055 std::advance(IRHS, 1);
3056 }
3057 }
3058 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003059 *this, S.getBeginLoc(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003060 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00003061 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
Alexey Bataevddf3db92018-04-13 17:31:06 +00003062 for (const Expr *IRef : C->varlists())
Alexey Bataev43a919f2018-04-13 17:48:43 +00003063 Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
Alexey Bataev475a7442018-01-12 19:39:11 +00003064 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
3065 CapturedRegion](CodeGenFunction &CGF,
3066 PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003067 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00003068 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003069 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
3070 !Data.LastprivateVars.empty()) {
James Y Knight9871db02019-02-05 16:42:33 +00003071 llvm::FunctionType *CopyFnTy = llvm::FunctionType::get(
3072 CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true);
Alexey Bataev3c595a62017-08-14 15:01:03 +00003073 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00003074 llvm::Value *CopyFn = CGF.Builder.CreateLoad(
3075 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
3076 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
3077 CS->getCapturedDecl()->getParam(PrivatesParam)));
Alexey Bataev48591dd2016-04-20 04:01:36 +00003078 // Map privates.
3079 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3080 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3081 CallArgs.push_back(PrivatesPtr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003082 for (const Expr *E : Data.PrivateVars) {
3083 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev48591dd2016-04-20 04:01:36 +00003084 Address PrivatePtr = CGF.CreateMemTemp(
3085 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003086 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003087 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003088 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003089 for (const Expr *E : Data.FirstprivateVars) {
3090 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev48591dd2016-04-20 04:01:36 +00003091 Address PrivatePtr =
3092 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3093 ".firstpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003094 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003095 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003096 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003097 for (const Expr *E : Data.LastprivateVars) {
3098 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003099 Address PrivatePtr =
3100 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3101 ".lastpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003102 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003103 CallArgs.push_back(PrivatePtr.getPointer());
3104 }
James Y Knight9871db02019-02-05 16:42:33 +00003105 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3106 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003107 for (const auto &Pair : LastprivateDstsOrigs) {
3108 const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003109 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(OrigVD),
3110 /*RefersToEnclosingVariableOrCapture=*/
3111 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
3112 Pair.second->getType(), VK_LValue,
3113 Pair.second->getExprLoc());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003114 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08003115 return CGF.EmitLValue(&DRE).getAddress();
Alexey Bataevf93095a2016-05-05 08:46:22 +00003116 });
3117 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003118 for (const auto &Pair : PrivatePtrs) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003119 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3120 CGF.getContext().getDeclAlign(Pair.first));
3121 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3122 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003123 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003124 if (Data.Reductions) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003125 OMPLexicalScope LexScope(CGF, S, CapturedRegion);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003126 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
3127 Data.ReductionOps);
3128 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
3129 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
3130 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
3131 RedCG.emitSharedLValue(CGF, Cnt);
3132 RedCG.emitAggregateType(CGF, Cnt);
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003133 // FIXME: This must removed once the runtime library is fixed.
3134 // Emit required threadprivate variables for
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003135 // initializer/combiner/finalizer.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003136 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003137 RedCG, Cnt);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003138 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003139 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003140 Replacement =
3141 Address(CGF.EmitScalarConversion(
3142 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
3143 CGF.getContext().getPointerType(
3144 Data.ReductionCopies[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003145 Data.ReductionCopies[Cnt]->getExprLoc()),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003146 Replacement.getAlignment());
3147 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
3148 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
3149 [Replacement]() { return Replacement; });
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003150 }
3151 }
Alexey Bataev88202be2017-07-27 13:20:36 +00003152 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00003153 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00003154 SmallVector<const Expr *, 4> InRedVars;
3155 SmallVector<const Expr *, 4> InRedPrivs;
3156 SmallVector<const Expr *, 4> InRedOps;
3157 SmallVector<const Expr *, 4> TaskgroupDescriptors;
3158 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
3159 auto IPriv = C->privates().begin();
3160 auto IRed = C->reduction_ops().begin();
3161 auto ITD = C->taskgroup_descriptors().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003162 for (const Expr *Ref : C->varlists()) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003163 InRedVars.emplace_back(Ref);
3164 InRedPrivs.emplace_back(*IPriv);
3165 InRedOps.emplace_back(*IRed);
3166 TaskgroupDescriptors.emplace_back(*ITD);
3167 std::advance(IPriv, 1);
3168 std::advance(IRed, 1);
3169 std::advance(ITD, 1);
3170 }
3171 }
3172 // Privatize in_reduction items here, because taskgroup descriptors must be
3173 // privatized earlier.
3174 OMPPrivateScope InRedScope(CGF);
3175 if (!InRedVars.empty()) {
3176 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
3177 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
3178 RedCG.emitSharedLValue(CGF, Cnt);
3179 RedCG.emitAggregateType(CGF, Cnt);
3180 // The taskgroup descriptor variable is always implicit firstprivate and
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003181 // privatized already during processing of the firstprivates.
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003182 // FIXME: This must removed once the runtime library is fixed.
3183 // Emit required threadprivate variables for
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003184 // initializer/combiner/finalizer.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003185 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003186 RedCG, Cnt);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003187 llvm::Value *ReductionsPtr =
3188 CGF.EmitLoadOfScalar(CGF.EmitLValue(TaskgroupDescriptors[Cnt]),
3189 TaskgroupDescriptors[Cnt]->getExprLoc());
Alexey Bataev88202be2017-07-27 13:20:36 +00003190 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003191 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
Alexey Bataev88202be2017-07-27 13:20:36 +00003192 Replacement = Address(
3193 CGF.EmitScalarConversion(
3194 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
3195 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003196 InRedPrivs[Cnt]->getExprLoc()),
Alexey Bataev88202be2017-07-27 13:20:36 +00003197 Replacement.getAlignment());
3198 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
3199 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
3200 [Replacement]() { return Replacement; });
Alexey Bataev88202be2017-07-27 13:20:36 +00003201 }
3202 }
3203 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00003204
3205 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00003206 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003207 };
James Y Knight9871db02019-02-05 16:42:33 +00003208 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00003209 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
3210 Data.NumberOfParts);
Alexey Bataev5bbcead2019-10-14 17:17:41 +00003211 OMPLexicalScope Scope(*this, S, llvm::None,
3212 !isOpenMPParallelDirective(S.getDirectiveKind()));
Alexey Bataev7292c292016-04-25 12:22:29 +00003213 TaskGen(*this, OutlinedFn, Data);
3214}
3215
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003216static ImplicitParamDecl *
3217createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003218 QualType Ty, CapturedDecl *CD,
3219 SourceLocation Loc) {
3220 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3221 ImplicitParamDecl::Other);
3222 auto *OrigRef = DeclRefExpr::Create(
3223 C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
3224 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
3225 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3226 ImplicitParamDecl::Other);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003227 auto *PrivateRef = DeclRefExpr::Create(
3228 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003229 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003230 QualType ElemType = C.getBaseElementType(Ty);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003231 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
3232 ImplicitParamDecl::Other);
3233 auto *InitRef = DeclRefExpr::Create(
3234 C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
3235 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003236 PrivateVD->setInitStyle(VarDecl::CInit);
3237 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
3238 InitRef, /*BasePath=*/nullptr,
3239 VK_RValue));
3240 Data.FirstprivateVars.emplace_back(OrigRef);
3241 Data.FirstprivateCopies.emplace_back(PrivateRef);
3242 Data.FirstprivateInits.emplace_back(InitRef);
3243 return OrigVD;
3244}
3245
3246void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
3247 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
3248 OMPTargetDataInfo &InputInfo) {
3249 // Emit outlined function for task construct.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003250 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
3251 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3252 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3253 auto I = CS->getCapturedDecl()->param_begin();
3254 auto PartId = std::next(I);
3255 auto TaskT = std::next(I, 4);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003256 OMPTaskDataTy Data;
3257 // The task is not final.
3258 Data.Final.setInt(/*IntVal=*/false);
3259 // Get list of firstprivate variables.
3260 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3261 auto IRef = C->varlist_begin();
3262 auto IElemInitRef = C->inits().begin();
3263 for (auto *IInit : C->private_copies()) {
3264 Data.FirstprivateVars.push_back(*IRef);
3265 Data.FirstprivateCopies.push_back(IInit);
3266 Data.FirstprivateInits.push_back(*IElemInitRef);
3267 ++IRef;
3268 ++IElemInitRef;
3269 }
3270 }
3271 OMPPrivateScope TargetScope(*this);
3272 VarDecl *BPVD = nullptr;
3273 VarDecl *PVD = nullptr;
3274 VarDecl *SVD = nullptr;
3275 if (InputInfo.NumberOfTargetItems > 0) {
3276 auto *CD = CapturedDecl::Create(
3277 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
3278 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
3279 QualType BaseAndPointersType = getContext().getConstantArrayType(
Richard Smith772e2662019-10-04 01:25:59 +00003280 getContext().VoidPtrTy, ArrSize, nullptr, ArrayType::Normal,
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003281 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003282 BPVD = createImplicitFirstprivateForType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003283 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003284 PVD = createImplicitFirstprivateForType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003285 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003286 QualType SizesType = getContext().getConstantArrayType(
Alexey Bataeva90fc662019-06-25 16:00:43 +00003287 getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1),
Richard Smith772e2662019-10-04 01:25:59 +00003288 ArrSize, nullptr, ArrayType::Normal,
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003289 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003290 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003291 S.getBeginLoc());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003292 TargetScope.addPrivate(
3293 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
3294 TargetScope.addPrivate(PVD,
3295 [&InputInfo]() { return InputInfo.PointersArray; });
3296 TargetScope.addPrivate(SVD,
3297 [&InputInfo]() { return InputInfo.SizesArray; });
3298 }
3299 (void)TargetScope.Privatize();
3300 // Build list of dependences.
3301 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
Alexey Bataevddf3db92018-04-13 17:31:06 +00003302 for (const Expr *IRef : C->varlists())
Alexey Bataev43a919f2018-04-13 17:48:43 +00003303 Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003304 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3305 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3306 // Set proper addresses for generated private copies.
3307 OMPPrivateScope Scope(CGF);
3308 if (!Data.FirstprivateVars.empty()) {
James Y Knight9871db02019-02-05 16:42:33 +00003309 llvm::FunctionType *CopyFnTy = llvm::FunctionType::get(
3310 CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003311 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00003312 llvm::Value *CopyFn = CGF.Builder.CreateLoad(
3313 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
3314 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
3315 CS->getCapturedDecl()->getParam(PrivatesParam)));
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003316 // Map privates.
3317 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3318 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3319 CallArgs.push_back(PrivatesPtr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003320 for (const Expr *E : Data.FirstprivateVars) {
3321 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003322 Address PrivatePtr =
3323 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3324 ".firstpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003325 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003326 CallArgs.push_back(PrivatePtr.getPointer());
3327 }
James Y Knight9871db02019-02-05 16:42:33 +00003328 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3329 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003330 for (const auto &Pair : PrivatePtrs) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003331 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3332 CGF.getContext().getDeclAlign(Pair.first));
3333 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3334 }
3335 }
3336 // Privatize all private variables except for in_reduction items.
3337 (void)Scope.Privatize();
Alexey Bataev8451efa2018-01-15 19:06:12 +00003338 if (InputInfo.NumberOfTargetItems > 0) {
3339 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
James Y Knight751fe282019-02-09 22:22:28 +00003340 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003341 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
James Y Knight751fe282019-02-09 22:22:28 +00003342 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003343 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
James Y Knight751fe282019-02-09 22:22:28 +00003344 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003345 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003346
3347 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003348 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003349 BodyGen(CGF);
3350 };
James Y Knight9871db02019-02-05 16:42:33 +00003351 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003352 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3353 Data.NumberOfParts);
3354 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3355 IntegerLiteral IfCond(getContext(), TrueOrFalse,
3356 getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3357 SourceLocation());
3358
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003359 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn,
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003360 SharedsTy, CapturedStruct, &IfCond, Data);
3361}
3362
Alexey Bataev7292c292016-04-25 12:22:29 +00003363void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3364 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00003365 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003366 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3367 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00003368 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00003369 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3370 if (C->getNameModifier() == OMPD_unknown ||
3371 C->getNameModifier() == OMPD_task) {
3372 IfCond = C->getCondition();
3373 break;
3374 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003375 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003376
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003377 OMPTaskDataTy Data;
3378 // Check if we should emit tied or untied task.
3379 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003380 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3381 CGF.EmitStmt(CS->getCapturedStmt());
3382 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003383 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
James Y Knight9871db02019-02-05 16:42:33 +00003384 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003385 const OMPTaskDataTy &Data) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003386 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003387 SharedsTy, CapturedStruct, IfCond,
3388 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003389 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003390 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003391}
3392
Alexey Bataev9f797f32015-02-05 05:57:51 +00003393void CodeGenFunction::EmitOMPTaskyieldDirective(
3394 const OMPTaskyieldDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003395 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc());
Alexey Bataev68446b72014-07-18 07:47:19 +00003396}
3397
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003398void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003399 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003400}
3401
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003402void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003403 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc());
Alexey Bataev2df347a2014-07-18 10:17:07 +00003404}
3405
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003406void CodeGenFunction::EmitOMPTaskgroupDirective(
3407 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003408 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3409 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003410 if (const Expr *E = S.getReductionRef()) {
3411 SmallVector<const Expr *, 4> LHSs;
3412 SmallVector<const Expr *, 4> RHSs;
3413 OMPTaskDataTy Data;
3414 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3415 auto IPriv = C->privates().begin();
3416 auto IRed = C->reduction_ops().begin();
3417 auto ILHS = C->lhs_exprs().begin();
3418 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003419 for (const Expr *Ref : C->varlists()) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003420 Data.ReductionVars.emplace_back(Ref);
3421 Data.ReductionCopies.emplace_back(*IPriv);
3422 Data.ReductionOps.emplace_back(*IRed);
3423 LHSs.emplace_back(*ILHS);
3424 RHSs.emplace_back(*IRHS);
3425 std::advance(IPriv, 1);
3426 std::advance(IRed, 1);
3427 std::advance(ILHS, 1);
3428 std::advance(IRHS, 1);
3429 }
3430 }
3431 llvm::Value *ReductionDesc =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003432 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(),
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003433 LHSs, RHSs, Data);
3434 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3435 CGF.EmitVarDecl(*VD);
3436 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3437 /*Volatile=*/false, E->getType());
3438 }
Alexey Bataev475a7442018-01-12 19:39:11 +00003439 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003440 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003441 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003442 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003443}
3444
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003445void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003446 CGM.getOpenMPRuntime().emitFlush(
3447 *this,
3448 [&S]() -> ArrayRef<const Expr *> {
3449 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>())
3450 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3451 FlushClause->varlist_end());
3452 return llvm::None;
3453 }(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003454 S.getBeginLoc());
Alexey Bataev6125da92014-07-21 11:26:11 +00003455}
3456
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003457void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3458 const CodeGenLoopTy &CodeGenLoop,
3459 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003460 // Emit the loop iteration variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003461 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3462 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003463 EmitVarDecl(*IVDecl);
3464
3465 // Emit the iterations count variable.
3466 // If it is not a variable, Sema decided to calculate iterations count on each
3467 // iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00003468 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003469 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3470 // Emit calculation of the iterations count.
3471 EmitIgnoredExpr(S.getCalcLastIteration());
3472 }
3473
Alexey Bataevddf3db92018-04-13 17:31:06 +00003474 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003475
Carlo Bertolli962bb802017-01-03 18:24:42 +00003476 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003477 // Check pre-condition.
3478 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003479 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003480 // Skip the entire loop if we don't meet the precondition.
3481 // If the condition constant folds and can be elided, avoid emitting the
3482 // whole loop.
3483 bool CondConstant;
3484 llvm::BasicBlock *ContBlock = nullptr;
3485 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3486 if (!CondConstant)
3487 return;
3488 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003489 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003490 ContBlock = createBasicBlock("omp.precond.end");
3491 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3492 getProfileCount(&S));
3493 EmitBlock(ThenBlock);
3494 incrementProfileCounter(&S);
3495 }
3496
Alexey Bataev617db5f2017-12-04 15:38:33 +00003497 emitAlignedClause(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003498 // Emit 'then' code.
3499 {
3500 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003501
3502 LValue LB = EmitOMPHelperVar(
3503 *this, cast<DeclRefExpr>(
3504 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3505 ? S.getCombinedLowerBoundVariable()
3506 : S.getLowerBoundVariable())));
3507 LValue UB = EmitOMPHelperVar(
3508 *this, cast<DeclRefExpr>(
3509 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3510 ? S.getCombinedUpperBoundVariable()
3511 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003512 LValue ST =
3513 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3514 LValue IL =
3515 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3516
3517 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003518 if (EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003519 // Emit implicit barrier to synchronize threads and avoid data races
3520 // on initialization of firstprivate variables and post-update of
Carlo Bertolli962bb802017-01-03 18:24:42 +00003521 // lastprivate variables.
3522 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003523 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev617db5f2017-12-04 15:38:33 +00003524 /*ForceSimpleCall=*/true);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003525 }
3526 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev617db5f2017-12-04 15:38:33 +00003527 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
Alexey Bataev999277a2017-12-06 14:31:09 +00003528 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3529 !isOpenMPTeamsDirective(S.getDirectiveKind()))
Alexey Bataev617db5f2017-12-04 15:38:33 +00003530 EmitOMPReductionClauseInit(S, LoopScope);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003531 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003532 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003533 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00003534 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
3535 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003536
3537 // Detect the distribute schedule kind and chunk.
3538 llvm::Value *Chunk = nullptr;
3539 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003540 if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003541 ScheduleKind = C->getDistScheduleKind();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003542 if (const Expr *Ch = C->getChunkSize()) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003543 Chunk = EmitScalarExpr(Ch);
3544 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
Alexey Bataev617db5f2017-12-04 15:38:33 +00003545 S.getIterationVariable()->getType(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003546 S.getBeginLoc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003547 }
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00003548 } else {
3549 // Default behaviour for dist_schedule clause.
3550 CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk(
3551 *this, S, ScheduleKind, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003552 }
3553 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3554 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3555
3556 // OpenMP [2.10.8, distribute Construct, Description]
3557 // If dist_schedule is specified, kind must be static. If specified,
3558 // iterations are divided into chunks of size chunk_size, chunks are
3559 // assigned to the teams of the league in a round-robin fashion in the
3560 // order of the team number. When no chunk_size is specified, the
3561 // iteration space is divided into chunks that are approximately equal
3562 // in size, and at most one chunk is distributed to each team of the
3563 // league. The size of the chunks is unspecified in this case.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003564 bool StaticChunked = RT.isStaticChunked(
3565 ScheduleKind, /* Chunked */ Chunk != nullptr) &&
3566 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003567 if (RT.isStaticNonchunked(ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003568 /* Chunked */ Chunk != nullptr) ||
3569 StaticChunked) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003570 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3571 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003572 CGOpenMPRuntime::StaticRTInput StaticInit(
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08003573 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3574 LB.getAddress(), UB.getAddress(), ST.getAddress(),
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003575 StaticChunked ? Chunk : nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003576 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003577 StaticInit);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003578 JumpDest LoopExit =
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003579 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3580 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003581 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3582 ? S.getCombinedEnsureUpperBound()
3583 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003584 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003585 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3586 ? S.getCombinedInit()
3587 : S.getInit());
3588
Alexey Bataevddf3db92018-04-13 17:31:06 +00003589 const Expr *Cond =
3590 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3591 ? S.getCombinedCond()
3592 : S.getCond();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003593
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003594 if (StaticChunked)
3595 Cond = S.getCombinedDistCond();
3596
3597 // For static unchunked schedules generate:
3598 //
3599 // 1. For distribute alone, codegen
3600 // while (idx <= UB) {
3601 // BODY;
3602 // ++idx;
3603 // }
3604 //
3605 // 2. When combined with 'for' (e.g. as in 'distribute parallel for')
3606 // while (idx <= UB) {
3607 // <CodeGen rest of pragma>(LB, UB);
3608 // idx += ST;
3609 // }
3610 //
3611 // For static chunk one schedule generate:
3612 //
3613 // while (IV <= GlobalUB) {
3614 // <CodeGen rest of pragma>(LB, UB);
3615 // LB += ST;
3616 // UB += ST;
3617 // UB = min(UB, GlobalUB);
3618 // IV = LB;
3619 // }
3620 //
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003621 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3622 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3623 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003624 },
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003625 [&S, StaticChunked](CodeGenFunction &CGF) {
3626 if (StaticChunked) {
3627 CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound());
3628 CGF.EmitIgnoredExpr(S.getCombinedNextUpperBound());
3629 CGF.EmitIgnoredExpr(S.getCombinedEnsureUpperBound());
3630 CGF.EmitIgnoredExpr(S.getCombinedInit());
3631 }
3632 });
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003633 EmitBlock(LoopExit.getBlock());
3634 // Tell the runtime we are done.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003635 RT.emitForStaticFinish(*this, S.getBeginLoc(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003636 } else {
3637 // Emit the outer loop, which requests its work chunk [LB..UB] from
3638 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003639 const OMPLoopArguments LoopArguments = {
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08003640 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3641 Chunk};
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003642 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3643 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003644 }
Alexey Bataev617db5f2017-12-04 15:38:33 +00003645 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003646 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003647 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003648 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataev617db5f2017-12-04 15:38:33 +00003649 });
3650 }
Carlo Bertollibeda2142018-02-22 19:38:14 +00003651 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
3652 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3653 !isOpenMPTeamsDirective(S.getDirectiveKind())) {
Jonas Hahnfeld5aaaece2018-10-02 19:12:47 +00003654 EmitOMPReductionClauseFinal(S, OMPD_simd);
Carlo Bertollibeda2142018-02-22 19:38:14 +00003655 // Emit post-update of the reduction variables if IsLastIter != 0.
3656 emitPostUpdateForReductionClause(
Alexey Bataevddf3db92018-04-13 17:31:06 +00003657 *this, S, [IL, &S](CodeGenFunction &CGF) {
Carlo Bertollibeda2142018-02-22 19:38:14 +00003658 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003659 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Carlo Bertollibeda2142018-02-22 19:38:14 +00003660 });
Alexey Bataev617db5f2017-12-04 15:38:33 +00003661 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00003662 // Emit final copy of the lastprivate variables if IsLastIter != 0.
Alexey Bataev617db5f2017-12-04 15:38:33 +00003663 if (HasLastprivateClause) {
Carlo Bertolli962bb802017-01-03 18:24:42 +00003664 EmitOMPLastprivateClauseFinal(
3665 S, /*NoFinals=*/false,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003666 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexey Bataev617db5f2017-12-04 15:38:33 +00003667 }
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003668 }
3669
3670 // We're now done with the loop, so jump to the continuation block.
3671 if (ContBlock) {
3672 EmitBranch(ContBlock);
3673 EmitBlock(ContBlock, true);
3674 }
3675 }
3676}
3677
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003678void CodeGenFunction::EmitOMPDistributeDirective(
3679 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003680 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003681 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003682 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003683 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev10a54312017-11-27 16:54:08 +00003684 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003685}
3686
Alexey Bataev5f600d62015-09-29 03:48:57 +00003687static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3688 const CapturedStmt *S) {
3689 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3690 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3691 CGF.CapturedStmtInfo = &CapStmtInfo;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003692 llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003693 Fn->setDoesNotRecurse();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003694 return Fn;
3695}
3696
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003697void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003698 if (S.hasClausesOfKind<OMPDependClause>()) {
3699 assert(!S.getAssociatedStmt() &&
3700 "No associated statement must be in ordered depend construct.");
Alexey Bataev8b427062016-05-25 12:36:08 +00003701 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3702 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003703 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003704 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003705 const auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003706 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3707 PrePostActionTy &Action) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003708 const CapturedStmt *CS = S.getInnermostCapturedStmt();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003709 if (C) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003710 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3711 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003712 llvm::Function *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003713 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
Alexey Bataev3c595a62017-08-14 15:01:03 +00003714 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003715 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003716 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003717 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev5f600d62015-09-29 03:48:57 +00003718 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003719 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003720 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003721 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003722}
3723
Alexey Bataevb57056f2015-01-22 06:17:56 +00003724static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003725 QualType SrcType, QualType DestType,
3726 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003727 assert(CGF.hasScalarEvaluationKind(DestType) &&
3728 "DestType must have scalar evaluation kind.");
3729 assert(!Val.isAggregate() && "Must be a scalar or complex.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003730 return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3731 DestType, Loc)
3732 : CGF.EmitComplexToScalarConversion(
3733 Val.getComplexVal(), SrcType, DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003734}
3735
3736static CodeGenFunction::ComplexPairTy
3737convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003738 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003739 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3740 "DestType must have complex evaluation kind.");
3741 CodeGenFunction::ComplexPairTy ComplexVal;
3742 if (Val.isScalar()) {
3743 // Convert the input element to the element type of the complex.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003744 QualType DestElementType =
3745 DestType->castAs<ComplexType>()->getElementType();
3746 llvm::Value *ScalarVal = CGF.EmitScalarConversion(
3747 Val.getScalarVal(), SrcType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003748 ComplexVal = CodeGenFunction::ComplexPairTy(
3749 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3750 } else {
3751 assert(Val.isComplex() && "Must be a scalar or complex.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003752 QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3753 QualType DestElementType =
3754 DestType->castAs<ComplexType>()->getElementType();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003755 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003756 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003757 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003758 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003759 }
3760 return ComplexVal;
3761}
3762
Alexey Bataev5e018f92015-04-23 06:35:10 +00003763static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3764 LValue LVal, RValue RVal) {
3765 if (LVal.isGlobalReg()) {
3766 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3767 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003768 CGF.EmitAtomicStore(RVal, LVal,
3769 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3770 : llvm::AtomicOrdering::Monotonic,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003771 LVal.isVolatile(), /*isInit=*/false);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003772 }
3773}
3774
Alexey Bataev8524d152016-01-21 12:35:58 +00003775void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3776 QualType RValTy, SourceLocation Loc) {
3777 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003778 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003779 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3780 *this, RVal, RValTy, LVal.getType(), Loc)),
3781 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003782 break;
3783 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003784 EmitStoreOfComplex(
3785 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003786 /*isInit=*/false);
3787 break;
3788 case TEK_Aggregate:
3789 llvm_unreachable("Must be a scalar or complex.");
3790 }
3791}
3792
Alexey Bataevddf3db92018-04-13 17:31:06 +00003793static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb57056f2015-01-22 06:17:56 +00003794 const Expr *X, const Expr *V,
3795 SourceLocation Loc) {
3796 // v = x;
3797 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3798 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3799 LValue XLValue = CGF.EmitLValue(X);
3800 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003801 RValue Res = XLValue.isGlobalReg()
3802 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003803 : CGF.EmitAtomicLoad(
3804 XLValue, Loc,
3805 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3806 : llvm::AtomicOrdering::Monotonic,
3807 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003808 // OpenMP, 2.12.6, atomic Construct
3809 // Any atomic construct with a seq_cst clause forces the atomically
3810 // performed operation to include an implicit flush operation without a
3811 // list.
3812 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003813 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003814 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003815}
3816
Alexey Bataevddf3db92018-04-13 17:31:06 +00003817static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb8329262015-02-27 06:33:30 +00003818 const Expr *X, const Expr *E,
3819 SourceLocation Loc) {
3820 // x = expr;
3821 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003822 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003823 // OpenMP, 2.12.6, atomic Construct
3824 // Any atomic construct with a seq_cst clause forces the atomically
3825 // performed operation to include an implicit flush operation without a
3826 // list.
3827 if (IsSeqCst)
3828 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3829}
3830
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003831static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3832 RValue Update,
3833 BinaryOperatorKind BO,
3834 llvm::AtomicOrdering AO,
3835 bool IsXLHSInRHSPart) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003836 ASTContext &Context = CGF.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003837 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003838 // expression is simple and atomic is allowed for the given type for the
3839 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003840 if (BO == BO_Comma || !Update.isScalar() ||
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08003841 !Update.getScalarVal()->getType()->isIntegerTy() ||
3842 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3843 (Update.getScalarVal()->getType() !=
3844 X.getAddress().getElementType())) ||
3845 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003846 !Context.getTargetInfo().hasBuiltinAtomic(
3847 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003848 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003849
3850 llvm::AtomicRMWInst::BinOp RMWOp;
3851 switch (BO) {
3852 case BO_Add:
3853 RMWOp = llvm::AtomicRMWInst::Add;
3854 break;
3855 case BO_Sub:
3856 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003857 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003858 RMWOp = llvm::AtomicRMWInst::Sub;
3859 break;
3860 case BO_And:
3861 RMWOp = llvm::AtomicRMWInst::And;
3862 break;
3863 case BO_Or:
3864 RMWOp = llvm::AtomicRMWInst::Or;
3865 break;
3866 case BO_Xor:
3867 RMWOp = llvm::AtomicRMWInst::Xor;
3868 break;
3869 case BO_LT:
3870 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3871 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3872 : llvm::AtomicRMWInst::Max)
3873 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3874 : llvm::AtomicRMWInst::UMax);
3875 break;
3876 case BO_GT:
3877 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3878 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3879 : llvm::AtomicRMWInst::Min)
3880 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3881 : llvm::AtomicRMWInst::UMin);
3882 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003883 case BO_Assign:
3884 RMWOp = llvm::AtomicRMWInst::Xchg;
3885 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003886 case BO_Mul:
3887 case BO_Div:
3888 case BO_Rem:
3889 case BO_Shl:
3890 case BO_Shr:
3891 case BO_LAnd:
3892 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003893 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003894 case BO_PtrMemD:
3895 case BO_PtrMemI:
3896 case BO_LE:
3897 case BO_GE:
3898 case BO_EQ:
3899 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00003900 case BO_Cmp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003901 case BO_AddAssign:
3902 case BO_SubAssign:
3903 case BO_AndAssign:
3904 case BO_OrAssign:
3905 case BO_XorAssign:
3906 case BO_MulAssign:
3907 case BO_DivAssign:
3908 case BO_RemAssign:
3909 case BO_ShlAssign:
3910 case BO_ShrAssign:
3911 case BO_Comma:
3912 llvm_unreachable("Unsupported atomic update operation");
3913 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003914 llvm::Value *UpdateVal = Update.getScalarVal();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003915 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3916 UpdateVal = CGF.Builder.CreateIntCast(
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08003917 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003918 X.getType()->hasSignedIntegerRepresentation());
3919 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003920 llvm::Value *Res =
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08003921 CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003922 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003923}
3924
Alexey Bataev5e018f92015-04-23 06:35:10 +00003925std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003926 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3927 llvm::AtomicOrdering AO, SourceLocation Loc,
Alexey Bataevddf3db92018-04-13 17:31:06 +00003928 const llvm::function_ref<RValue(RValue)> CommonGen) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003929 // Update expressions are allowed to have the following forms:
3930 // x binop= expr; -> xrval + expr;
3931 // x++, ++x -> xrval + 1;
3932 // x--, --x -> xrval - 1;
3933 // x = x binop expr; -> xrval binop expr
3934 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003935 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3936 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003937 if (X.isGlobalReg()) {
3938 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3939 // 'xrval'.
3940 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3941 } else {
3942 // Perform compare-and-swap procedure.
3943 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003944 }
3945 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003946 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003947}
3948
Alexey Bataevddf3db92018-04-13 17:31:06 +00003949static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb4505a72015-03-30 05:20:59 +00003950 const Expr *X, const Expr *E,
3951 const Expr *UE, bool IsXLHSInRHSPart,
3952 SourceLocation Loc) {
3953 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3954 "Update expr in 'atomic update' must be a binary operator.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003955 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003956 // Update expressions are allowed to have the following forms:
3957 // x binop= expr; -> xrval + expr;
3958 // x++, ++x -> xrval + 1;
3959 // x--, --x -> xrval - 1;
3960 // x = x binop expr; -> xrval binop expr
3961 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003962 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003963 LValue XLValue = CGF.EmitLValue(X);
3964 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003965 llvm::AtomicOrdering AO = IsSeqCst
3966 ? llvm::AtomicOrdering::SequentiallyConsistent
3967 : llvm::AtomicOrdering::Monotonic;
3968 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3969 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3970 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3971 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3972 auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) {
3973 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3974 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3975 return CGF.EmitAnyExpr(UE);
3976 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003977 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3978 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3979 // OpenMP, 2.12.6, atomic Construct
3980 // Any atomic construct with a seq_cst clause forces the atomically
3981 // performed operation to include an implicit flush operation without a
3982 // list.
3983 if (IsSeqCst)
3984 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3985}
3986
3987static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003988 QualType SourceType, QualType ResType,
3989 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003990 switch (CGF.getEvaluationKind(ResType)) {
3991 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003992 return RValue::get(
3993 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003994 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003995 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003996 return RValue::getComplex(Res.first, Res.second);
3997 }
3998 case TEK_Aggregate:
3999 break;
4000 }
4001 llvm_unreachable("Must be a scalar or complex.");
4002}
4003
Alexey Bataevddf3db92018-04-13 17:31:06 +00004004static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataev5e018f92015-04-23 06:35:10 +00004005 bool IsPostfixUpdate, const Expr *V,
4006 const Expr *X, const Expr *E,
4007 const Expr *UE, bool IsXLHSInRHSPart,
4008 SourceLocation Loc) {
4009 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
4010 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
4011 RValue NewVVal;
4012 LValue VLValue = CGF.EmitLValue(V);
4013 LValue XLValue = CGF.EmitLValue(X);
4014 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004015 llvm::AtomicOrdering AO = IsSeqCst
4016 ? llvm::AtomicOrdering::SequentiallyConsistent
4017 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004018 QualType NewVValType;
4019 if (UE) {
4020 // 'x' is updated with some additional value.
4021 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
4022 "Update expr in 'atomic capture' must be a binary operator.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00004023 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
Alexey Bataev5e018f92015-04-23 06:35:10 +00004024 // Update expressions are allowed to have the following forms:
4025 // x binop= expr; -> xrval + expr;
4026 // x++, ++x -> xrval + 1;
4027 // x--, --x -> xrval - 1;
4028 // x = x binop expr; -> xrval binop expr
4029 // x = expr Op x; - > expr binop xrval;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004030 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
4031 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
4032 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004033 NewVValType = XRValExpr->getType();
Alexey Bataevddf3db92018-04-13 17:31:06 +00004034 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004035 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Alexey Bataevddf3db92018-04-13 17:31:06 +00004036 IsPostfixUpdate](RValue XRValue) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00004037 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
4038 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
4039 RValue Res = CGF.EmitAnyExpr(UE);
4040 NewVVal = IsPostfixUpdate ? XRValue : Res;
4041 return Res;
4042 };
4043 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
4044 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
4045 if (Res.first) {
4046 // 'atomicrmw' instruction was generated.
4047 if (IsPostfixUpdate) {
4048 // Use old value from 'atomicrmw'.
4049 NewVVal = Res.second;
4050 } else {
4051 // 'atomicrmw' does not provide new value, so evaluate it using old
4052 // value of 'x'.
4053 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
4054 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
4055 NewVVal = CGF.EmitAnyExpr(UE);
4056 }
4057 }
4058 } else {
4059 // 'x' is simply rewritten with some 'expr'.
4060 NewVValType = X->getType().getNonReferenceType();
4061 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004062 X->getType().getNonReferenceType(), Loc);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004063 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00004064 NewVVal = XRValue;
4065 return ExprRValue;
4066 };
4067 // Try to perform atomicrmw xchg, otherwise simple exchange.
4068 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
4069 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
4070 Loc, Gen);
4071 if (Res.first) {
4072 // 'atomicrmw' instruction was generated.
4073 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
4074 }
4075 }
4076 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00004077 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00004078 // OpenMP, 2.12.6, atomic Construct
4079 // Any atomic construct with a seq_cst clause forces the atomically
4080 // performed operation to include an implicit flush operation without a
4081 // list.
4082 if (IsSeqCst)
4083 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
4084}
4085
Alexey Bataevddf3db92018-04-13 17:31:06 +00004086static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00004087 bool IsSeqCst, bool IsPostfixUpdate,
4088 const Expr *X, const Expr *V, const Expr *E,
4089 const Expr *UE, bool IsXLHSInRHSPart,
4090 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00004091 switch (Kind) {
4092 case OMPC_read:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004093 emitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00004094 break;
4095 case OMPC_write:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004096 emitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
Alexey Bataevb8329262015-02-27 06:33:30 +00004097 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004098 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004099 case OMPC_update:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004100 emitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00004101 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00004102 case OMPC_capture:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004103 emitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
Alexey Bataev5e018f92015-04-23 06:35:10 +00004104 IsXLHSInRHSPart, Loc);
4105 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00004106 case OMPC_if:
4107 case OMPC_final:
4108 case OMPC_num_threads:
4109 case OMPC_private:
4110 case OMPC_firstprivate:
4111 case OMPC_lastprivate:
4112 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004113 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00004114 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004115 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00004116 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00004117 case OMPC_allocator:
Alexey Bataeve04483e2019-03-27 14:14:31 +00004118 case OMPC_allocate:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004119 case OMPC_collapse:
4120 case OMPC_default:
4121 case OMPC_seq_cst:
4122 case OMPC_shared:
4123 case OMPC_linear:
4124 case OMPC_aligned:
4125 case OMPC_copyin:
4126 case OMPC_copyprivate:
4127 case OMPC_flush:
4128 case OMPC_proc_bind:
4129 case OMPC_schedule:
4130 case OMPC_ordered:
4131 case OMPC_nowait:
4132 case OMPC_untied:
4133 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00004134 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004135 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00004136 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00004137 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004138 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00004139 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00004140 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00004141 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00004142 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00004143 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00004144 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00004145 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00004146 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00004147 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00004148 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004149 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00004150 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00004151 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00004152 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00004153 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00004154 case OMPC_unified_address:
Alexey Bataev94c50642018-10-01 14:26:31 +00004155 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00004156 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00004157 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00004158 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +00004159 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +00004160 case OMPC_match:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004161 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
4162 }
4163}
4164
4165void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004166 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00004167 OpenMPClauseKind Kind = OMPC_unknown;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004168 for (const OMPClause *C : S.clauses()) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00004169 // Find first clause (skip seq_cst clause, if it is first).
4170 if (C->getClauseKind() != OMPC_seq_cst) {
4171 Kind = C->getClauseKind();
4172 break;
4173 }
4174 }
Alexey Bataev10fec572015-03-11 04:48:56 +00004175
Alexey Bataevddf3db92018-04-13 17:31:06 +00004176 const Stmt *CS = S.getInnermostCapturedStmt()->IgnoreContainers();
Bill Wendling7c44da22018-10-31 03:48:47 +00004177 if (const auto *FE = dyn_cast<FullExpr>(CS))
4178 enterFullExpression(FE);
Alexey Bataev5e018f92015-04-23 06:35:10 +00004179 // Processing for statements under 'atomic capture'.
4180 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004181 for (const Stmt *C : Compound->body()) {
Bill Wendling7c44da22018-10-31 03:48:47 +00004182 if (const auto *FE = dyn_cast<FullExpr>(C))
4183 enterFullExpression(FE);
Alexey Bataev5e018f92015-04-23 06:35:10 +00004184 }
4185 }
Alexey Bataev10fec572015-03-11 04:48:56 +00004186
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004187 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
4188 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00004189 CGF.EmitStopPoint(CS);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004190 emitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
Alexey Bataev5e018f92015-04-23 06:35:10 +00004191 S.getV(), S.getExpr(), S.getUpdateExpr(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004192 S.isXLHSInRHSPart(), S.getBeginLoc());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004193 };
Alexey Bataev475a7442018-01-12 19:39:11 +00004194 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004195 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00004196}
4197
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004198static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
4199 const OMPExecutableDirective &S,
4200 const RegionCodeGenTy &CodeGen) {
4201 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
4202 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00004203
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00004204 // On device emit this construct as inlined code.
4205 if (CGM.getLangOpts().OpenMPIsDevice) {
4206 OMPLexicalScope Scope(CGF, S, OMPD_target);
4207 CGM.getOpenMPRuntime().emitInlinedDirective(
4208 CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev4ac68a22018-05-16 15:08:32 +00004209 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00004210 });
4211 return;
4212 }
4213
Samuel Antaoee8fb302016-01-06 13:42:12 +00004214 llvm::Function *Fn = nullptr;
4215 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00004216
Samuel Antaobed3c462015-10-02 16:14:20 +00004217 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00004218 // Check for the at most one if clause associated with the target region.
4219 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4220 if (C->getNameModifier() == OMPD_unknown ||
4221 C->getNameModifier() == OMPD_target) {
4222 IfCond = C->getCondition();
4223 break;
4224 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004225 }
4226
4227 // Check if we have any device clause associated with the directive.
4228 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004229 if (auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaobed3c462015-10-02 16:14:20 +00004230 Device = C->getDevice();
Samuel Antaobed3c462015-10-02 16:14:20 +00004231
Samuel Antaoee8fb302016-01-06 13:42:12 +00004232 // Check if we have an if clause whose conditional always evaluates to false
4233 // or if we do not have any targets specified. If so the target region is not
4234 // an offload entry point.
4235 bool IsOffloadEntry = true;
4236 if (IfCond) {
4237 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004238 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00004239 IsOffloadEntry = false;
4240 }
4241 if (CGM.getLangOpts().OMPTargetTriples.empty())
4242 IsOffloadEntry = false;
4243
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004244 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004245 StringRef ParentName;
4246 // In case we have Ctors/Dtors we use the complete type variant to produce
4247 // the mangling of the device outlined kernel.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004248 if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00004249 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Alexey Bataevddf3db92018-04-13 17:31:06 +00004250 else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00004251 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
4252 else
4253 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004254 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004255
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004256 // Emit target region as a standalone region.
4257 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
4258 IsOffloadEntry, CodeGen);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004259 OMPLexicalScope Scope(CGF, S, OMPD_task);
Alexey Bataevec7946e2019-09-23 14:06:51 +00004260 auto &&SizeEmitter =
4261 [IsOffloadEntry](CodeGenFunction &CGF,
4262 const OMPLoopDirective &D) -> llvm::Value * {
4263 if (IsOffloadEntry) {
4264 OMPLoopScope(CGF, D);
4265 // Emit calculation of the iterations count.
4266 llvm::Value *NumIterations = CGF.EmitScalarExpr(D.getNumIterations());
4267 NumIterations = CGF.Builder.CreateIntCast(NumIterations, CGF.Int64Ty,
4268 /*isSigned=*/false);
4269 return NumIterations;
4270 }
4271 return nullptr;
Alexey Bataev7bb33532019-01-07 21:30:43 +00004272 };
Alexey Bataevec7946e2019-09-23 14:06:51 +00004273 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
4274 SizeEmitter);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004275}
4276
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004277static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
4278 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004279 Action.Enter(CGF);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004280 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4281 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4282 CGF.EmitOMPPrivateClause(S, PrivateScope);
4283 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00004284 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4285 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004286
Alexey Bataev475a7442018-01-12 19:39:11 +00004287 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004288}
4289
4290void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
4291 StringRef ParentName,
4292 const OMPTargetDirective &S) {
4293 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4294 emitTargetRegion(CGF, S, Action);
4295 };
4296 llvm::Function *Fn;
4297 llvm::Constant *Addr;
4298 // Emit target region as a standalone region.
4299 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4300 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4301 assert(Fn && Addr && "Target device function emission failed.");
4302}
4303
4304void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
4305 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4306 emitTargetRegion(CGF, S, Action);
4307 };
4308 emitCommonOMPTargetDirective(*this, S, CodeGen);
4309}
4310
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004311static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
4312 const OMPExecutableDirective &S,
4313 OpenMPDirectiveKind InnermostKind,
4314 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004315 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
James Y Knight9871db02019-02-05 16:42:33 +00004316 llvm::Function *OutlinedFn =
Alexey Bataevddf3db92018-04-13 17:31:06 +00004317 CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
4318 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004319
Alexey Bataevddf3db92018-04-13 17:31:06 +00004320 const auto *NT = S.getSingleClause<OMPNumTeamsClause>();
4321 const auto *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004322 if (NT || TL) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004323 const Expr *NumTeams = NT ? NT->getNumTeams() : nullptr;
4324 const Expr *ThreadLimit = TL ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004325
Carlo Bertollic6872252016-04-04 15:55:02 +00004326 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004327 S.getBeginLoc());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004328 }
4329
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004330 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004331 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4332 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004333 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004334 CapturedVars);
4335}
4336
4337void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00004338 // Emit teams region as a standalone region.
Alexey Bataevc99042b2018-03-15 18:10:54 +00004339 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004340 Action.Enter(CGF);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004341 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00004342 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4343 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004344 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004345 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00004346 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004347 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004348 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00004349 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004350 emitPostUpdateForReductionClause(*this, S,
4351 [](CodeGenFunction &) { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00004352}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004353
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004354static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4355 const OMPTargetTeamsDirective &S) {
4356 auto *CS = S.getCapturedStmt(OMPD_teams);
4357 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004358 // Emit teams region as a standalone region.
4359 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004360 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004361 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4362 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4363 CGF.EmitOMPPrivateClause(S, PrivateScope);
4364 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4365 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00004366 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4367 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004368 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004369 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004370 };
4371 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004372 emitPostUpdateForReductionClause(CGF, S,
4373 [](CodeGenFunction &) { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004374}
4375
4376void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4377 CodeGenModule &CGM, StringRef ParentName,
4378 const OMPTargetTeamsDirective &S) {
4379 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4380 emitTargetTeamsRegion(CGF, Action, S);
4381 };
4382 llvm::Function *Fn;
4383 llvm::Constant *Addr;
4384 // Emit target region as a standalone region.
4385 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4386 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4387 assert(Fn && Addr && "Target device function emission failed.");
4388}
4389
4390void CodeGenFunction::EmitOMPTargetTeamsDirective(
4391 const OMPTargetTeamsDirective &S) {
4392 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4393 emitTargetTeamsRegion(CGF, Action, S);
4394 };
4395 emitCommonOMPTargetDirective(*this, S, CodeGen);
4396}
4397
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004398static void
4399emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4400 const OMPTargetTeamsDistributeDirective &S) {
4401 Action.Enter(CGF);
4402 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4403 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4404 };
4405
4406 // Emit teams region as a standalone region.
4407 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004408 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004409 Action.Enter(CGF);
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004410 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4411 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4412 (void)PrivateScope.Privatize();
4413 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4414 CodeGenDistribute);
4415 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4416 };
4417 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4418 emitPostUpdateForReductionClause(CGF, S,
4419 [](CodeGenFunction &) { return nullptr; });
4420}
4421
4422void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4423 CodeGenModule &CGM, StringRef ParentName,
4424 const OMPTargetTeamsDistributeDirective &S) {
4425 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4426 emitTargetTeamsDistributeRegion(CGF, Action, S);
4427 };
4428 llvm::Function *Fn;
4429 llvm::Constant *Addr;
4430 // Emit target region as a standalone region.
4431 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4432 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4433 assert(Fn && Addr && "Target device function emission failed.");
4434}
4435
4436void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4437 const OMPTargetTeamsDistributeDirective &S) {
4438 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4439 emitTargetTeamsDistributeRegion(CGF, Action, S);
4440 };
4441 emitCommonOMPTargetDirective(*this, S, CodeGen);
4442}
4443
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004444static void emitTargetTeamsDistributeSimdRegion(
4445 CodeGenFunction &CGF, PrePostActionTy &Action,
4446 const OMPTargetTeamsDistributeSimdDirective &S) {
4447 Action.Enter(CGF);
4448 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4449 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4450 };
4451
4452 // Emit teams region as a standalone region.
4453 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004454 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004455 Action.Enter(CGF);
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004456 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4457 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4458 (void)PrivateScope.Privatize();
4459 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4460 CodeGenDistribute);
4461 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4462 };
4463 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4464 emitPostUpdateForReductionClause(CGF, S,
4465 [](CodeGenFunction &) { return nullptr; });
4466}
4467
4468void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4469 CodeGenModule &CGM, StringRef ParentName,
4470 const OMPTargetTeamsDistributeSimdDirective &S) {
4471 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4472 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4473 };
4474 llvm::Function *Fn;
4475 llvm::Constant *Addr;
4476 // Emit target region as a standalone region.
4477 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4478 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4479 assert(Fn && Addr && "Target device function emission failed.");
4480}
4481
4482void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4483 const OMPTargetTeamsDistributeSimdDirective &S) {
4484 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4485 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4486 };
4487 emitCommonOMPTargetDirective(*this, S, CodeGen);
4488}
4489
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004490void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4491 const OMPTeamsDistributeDirective &S) {
4492
4493 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4494 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4495 };
4496
4497 // Emit teams region as a standalone region.
4498 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004499 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004500 Action.Enter(CGF);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004501 OMPPrivateScope PrivateScope(CGF);
4502 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4503 (void)PrivateScope.Privatize();
4504 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4505 CodeGenDistribute);
4506 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4507 };
Alexey Bataev95c6dd42017-11-29 15:14:16 +00004508 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004509 emitPostUpdateForReductionClause(*this, S,
4510 [](CodeGenFunction &) { return nullptr; });
4511}
4512
Alexey Bataev999277a2017-12-06 14:31:09 +00004513void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4514 const OMPTeamsDistributeSimdDirective &S) {
4515 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4516 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4517 };
4518
4519 // Emit teams region as a standalone region.
4520 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004521 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004522 Action.Enter(CGF);
Alexey Bataev999277a2017-12-06 14:31:09 +00004523 OMPPrivateScope PrivateScope(CGF);
4524 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4525 (void)PrivateScope.Privatize();
4526 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4527 CodeGenDistribute);
4528 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4529 };
4530 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4531 emitPostUpdateForReductionClause(*this, S,
4532 [](CodeGenFunction &) { return nullptr; });
4533}
4534
Carlo Bertolli62fae152017-11-20 20:46:39 +00004535void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4536 const OMPTeamsDistributeParallelForDirective &S) {
4537 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4538 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4539 S.getDistInc());
4540 };
4541
4542 // Emit teams region as a standalone region.
4543 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004544 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004545 Action.Enter(CGF);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004546 OMPPrivateScope PrivateScope(CGF);
4547 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4548 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00004549 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4550 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004551 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4552 };
4553 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4554 emitPostUpdateForReductionClause(*this, S,
4555 [](CodeGenFunction &) { return nullptr; });
4556}
4557
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004558void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4559 const OMPTeamsDistributeParallelForSimdDirective &S) {
4560 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4561 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4562 S.getDistInc());
4563 };
4564
4565 // Emit teams region as a standalone region.
4566 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004567 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004568 Action.Enter(CGF);
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004569 OMPPrivateScope PrivateScope(CGF);
4570 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4571 (void)PrivateScope.Privatize();
4572 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4573 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4574 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4575 };
4576 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4577 emitPostUpdateForReductionClause(*this, S,
4578 [](CodeGenFunction &) { return nullptr; });
4579}
4580
Carlo Bertolli52978c32018-01-03 21:12:44 +00004581static void emitTargetTeamsDistributeParallelForRegion(
4582 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
4583 PrePostActionTy &Action) {
Carlo Bertolli79712092018-02-28 20:48:35 +00004584 Action.Enter(CGF);
Carlo Bertolli52978c32018-01-03 21:12:44 +00004585 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4586 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4587 S.getDistInc());
4588 };
4589
4590 // Emit teams region as a standalone region.
4591 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004592 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004593 Action.Enter(CGF);
Carlo Bertolli52978c32018-01-03 21:12:44 +00004594 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4595 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4596 (void)PrivateScope.Privatize();
4597 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4598 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4599 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4600 };
4601
4602 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
4603 CodeGenTeams);
4604 emitPostUpdateForReductionClause(CGF, S,
4605 [](CodeGenFunction &) { return nullptr; });
4606}
4607
4608void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
4609 CodeGenModule &CGM, StringRef ParentName,
4610 const OMPTargetTeamsDistributeParallelForDirective &S) {
4611 // Emit SPMD target teams distribute parallel for region as a standalone
4612 // region.
4613 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4614 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4615 };
4616 llvm::Function *Fn;
4617 llvm::Constant *Addr;
4618 // Emit target region as a standalone region.
4619 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4620 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4621 assert(Fn && Addr && "Target device function emission failed.");
4622}
4623
4624void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
4625 const OMPTargetTeamsDistributeParallelForDirective &S) {
4626 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4627 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4628 };
4629 emitCommonOMPTargetDirective(*this, S, CodeGen);
4630}
4631
Alexey Bataev647dd842018-01-15 20:59:40 +00004632static void emitTargetTeamsDistributeParallelForSimdRegion(
4633 CodeGenFunction &CGF,
4634 const OMPTargetTeamsDistributeParallelForSimdDirective &S,
4635 PrePostActionTy &Action) {
Carlo Bertolli79712092018-02-28 20:48:35 +00004636 Action.Enter(CGF);
Alexey Bataev647dd842018-01-15 20:59:40 +00004637 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4638 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4639 S.getDistInc());
4640 };
4641
4642 // Emit teams region as a standalone region.
4643 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004644 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004645 Action.Enter(CGF);
Alexey Bataev647dd842018-01-15 20:59:40 +00004646 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4647 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4648 (void)PrivateScope.Privatize();
4649 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4650 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4651 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4652 };
4653
4654 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
4655 CodeGenTeams);
4656 emitPostUpdateForReductionClause(CGF, S,
4657 [](CodeGenFunction &) { return nullptr; });
4658}
4659
4660void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
4661 CodeGenModule &CGM, StringRef ParentName,
4662 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4663 // Emit SPMD target teams distribute parallel for simd region as a standalone
4664 // region.
4665 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4666 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4667 };
4668 llvm::Function *Fn;
4669 llvm::Constant *Addr;
4670 // Emit target region as a standalone region.
4671 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4672 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4673 assert(Fn && Addr && "Target device function emission failed.");
4674}
4675
4676void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
4677 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4678 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4679 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4680 };
4681 emitCommonOMPTargetDirective(*this, S, CodeGen);
4682}
4683
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004684void CodeGenFunction::EmitOMPCancellationPointDirective(
4685 const OMPCancellationPointDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004686 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00004687 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004688}
4689
Alexey Bataev80909872015-07-02 11:25:17 +00004690void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004691 const Expr *IfCond = nullptr;
4692 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4693 if (C->getNameModifier() == OMPD_unknown ||
4694 C->getNameModifier() == OMPD_cancel) {
4695 IfCond = C->getCondition();
4696 break;
4697 }
4698 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004699 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004700 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00004701}
4702
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004703CodeGenFunction::JumpDest
4704CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00004705 if (Kind == OMPD_parallel || Kind == OMPD_task ||
4706 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004707 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004708 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00004709 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
4710 Kind == OMPD_distribute_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004711 Kind == OMPD_target_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004712 Kind == OMPD_teams_distribute_parallel_for ||
4713 Kind == OMPD_target_teams_distribute_parallel_for);
Alexey Bataev957d8562016-11-17 15:12:05 +00004714 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004715}
Michael Wong65f367f2015-07-21 13:44:28 +00004716
Samuel Antaocc10b852016-07-28 14:23:26 +00004717void CodeGenFunction::EmitOMPUseDevicePtrClause(
4718 const OMPClause &NC, OMPPrivateScope &PrivateScope,
4719 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
4720 const auto &C = cast<OMPUseDevicePtrClause>(NC);
4721 auto OrigVarIt = C.varlist_begin();
4722 auto InitIt = C.inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00004723 for (const Expr *PvtVarIt : C.private_copies()) {
4724 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
4725 const auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
4726 const auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
Samuel Antaocc10b852016-07-28 14:23:26 +00004727
4728 // In order to identify the right initializer we need to match the
4729 // declaration used by the mapping logic. In some cases we may get
4730 // OMPCapturedExprDecl that refers to the original declaration.
4731 const ValueDecl *MatchingVD = OrigVD;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004732 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004733 // OMPCapturedExprDecl are used to privative fields of the current
4734 // structure.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004735 const auto *ME = cast<MemberExpr>(OED->getInit());
Samuel Antaocc10b852016-07-28 14:23:26 +00004736 assert(isa<CXXThisExpr>(ME->getBase()) &&
4737 "Base should be the current struct!");
4738 MatchingVD = ME->getMemberDecl();
4739 }
4740
4741 // If we don't have information about the current list item, move on to
4742 // the next one.
4743 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
4744 if (InitAddrIt == CaptureDeviceAddrMap.end())
4745 continue;
4746
Alexey Bataevddf3db92018-04-13 17:31:06 +00004747 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, OrigVD,
4748 InitAddrIt, InitVD,
4749 PvtVD]() {
Samuel Antaocc10b852016-07-28 14:23:26 +00004750 // Initialize the temporary initialization variable with the address we
4751 // get from the runtime library. We have to cast the source address
4752 // because it is always a void *. References are materialized in the
4753 // privatization scope, so the initialization here disregards the fact
4754 // the original variable is a reference.
4755 QualType AddrQTy =
4756 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
4757 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
4758 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
4759 setAddrOfLocalVar(InitVD, InitAddr);
4760
4761 // Emit private declaration, it will be initialized by the value we
4762 // declaration we just added to the local declarations map.
4763 EmitDecl(*PvtVD);
4764
4765 // The initialization variables reached its purpose in the emission
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004766 // of the previous declaration, so we don't need it anymore.
Samuel Antaocc10b852016-07-28 14:23:26 +00004767 LocalDeclMap.erase(InitVD);
4768
4769 // Return the address of the private variable.
4770 return GetAddrOfLocalVar(PvtVD);
4771 });
4772 assert(IsRegistered && "firstprivate var already registered as private");
4773 // Silence the warning about unused variable.
4774 (void)IsRegistered;
4775
4776 ++OrigVarIt;
4777 ++InitIt;
4778 }
4779}
4780
Michael Wong65f367f2015-07-21 13:44:28 +00004781// Generate the instructions for '#pragma omp target data' directive.
4782void CodeGenFunction::EmitOMPTargetDataDirective(
4783 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004784 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4785
4786 // Create a pre/post action to signal the privatization of the device pointer.
4787 // This action can be replaced by the OpenMP runtime code generation to
4788 // deactivate privatization.
4789 bool PrivatizeDevicePointers = false;
4790 class DevicePointerPrivActionTy : public PrePostActionTy {
4791 bool &PrivatizeDevicePointers;
4792
4793 public:
4794 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4795 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4796 void Enter(CodeGenFunction &CGF) override {
4797 PrivatizeDevicePointers = true;
4798 }
Samuel Antaodf158d52016-04-27 22:58:19 +00004799 };
Samuel Antaocc10b852016-07-28 14:23:26 +00004800 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4801
4802 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
Alexey Bataev475a7442018-01-12 19:39:11 +00004803 CodeGenFunction &CGF, PrePostActionTy &Action) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004804 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00004805 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Samuel Antaocc10b852016-07-28 14:23:26 +00004806 };
4807
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004808 // Codegen that selects whether to generate the privatization code or not.
Samuel Antaocc10b852016-07-28 14:23:26 +00004809 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4810 &InnermostCodeGen](CodeGenFunction &CGF,
4811 PrePostActionTy &Action) {
4812 RegionCodeGenTy RCG(InnermostCodeGen);
4813 PrivatizeDevicePointers = false;
4814
4815 // Call the pre-action to change the status of PrivatizeDevicePointers if
4816 // needed.
4817 Action.Enter(CGF);
4818
4819 if (PrivatizeDevicePointers) {
4820 OMPPrivateScope PrivateScope(CGF);
4821 // Emit all instances of the use_device_ptr clause.
4822 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4823 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4824 Info.CaptureDeviceAddrMap);
4825 (void)PrivateScope.Privatize();
4826 RCG(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004827 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00004828 RCG(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004829 }
Samuel Antaocc10b852016-07-28 14:23:26 +00004830 };
4831
4832 // Forward the provided action to the privatization codegen.
4833 RegionCodeGenTy PrivRCG(PrivCodeGen);
4834 PrivRCG.setAction(Action);
4835
4836 // Notwithstanding the body of the region is emitted as inlined directive,
4837 // we don't use an inline scope as changes in the references inside the
4838 // region are expected to be visible outside, so we do not privative them.
4839 OMPLexicalScope Scope(CGF, S);
4840 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4841 PrivRCG);
4842 };
4843
4844 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004845
4846 // If we don't have target devices, don't bother emitting the data mapping
4847 // code.
4848 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004849 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004850 return;
4851 }
4852
4853 // Check if we have any if clause associated with the directive.
4854 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004855 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antaodf158d52016-04-27 22:58:19 +00004856 IfCond = C->getCondition();
4857
4858 // Check if we have any device clause associated with the directive.
4859 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004860 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaodf158d52016-04-27 22:58:19 +00004861 Device = C->getDevice();
4862
Samuel Antaocc10b852016-07-28 14:23:26 +00004863 // Set the action to signal privatization of device pointers.
4864 RCG.setAction(PrivAction);
4865
4866 // Emit region code.
4867 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4868 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004869}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004870
Samuel Antaodf67fc42016-01-19 19:15:56 +00004871void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4872 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004873 // If we don't have target devices, don't bother emitting the data mapping
4874 // code.
4875 if (CGM.getLangOpts().OMPTargetTriples.empty())
4876 return;
4877
4878 // Check if we have any if clause associated with the directive.
4879 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004880 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004881 IfCond = C->getCondition();
4882
4883 // Check if we have any device clause associated with the directive.
4884 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004885 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004886 Device = C->getDevice();
4887
Alexey Bataev475a7442018-01-12 19:39:11 +00004888 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004889 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004890}
4891
Samuel Antao72590762016-01-19 20:04:50 +00004892void CodeGenFunction::EmitOMPTargetExitDataDirective(
4893 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004894 // If we don't have target devices, don't bother emitting the data mapping
4895 // code.
4896 if (CGM.getLangOpts().OMPTargetTriples.empty())
4897 return;
4898
4899 // Check if we have any if clause associated with the directive.
4900 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004901 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antao8dd66282016-04-27 23:14:30 +00004902 IfCond = C->getCondition();
4903
4904 // Check if we have any device clause associated with the directive.
4905 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004906 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antao8dd66282016-04-27 23:14:30 +00004907 Device = C->getDevice();
4908
Alexey Bataev475a7442018-01-12 19:39:11 +00004909 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004910 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004911}
4912
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004913static void emitTargetParallelRegion(CodeGenFunction &CGF,
4914 const OMPTargetParallelDirective &S,
4915 PrePostActionTy &Action) {
4916 // Get the captured statement associated with the 'parallel' region.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004917 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004918 Action.Enter(CGF);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004919 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004920 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004921 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4922 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4923 CGF.EmitOMPPrivateClause(S, PrivateScope);
4924 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4925 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00004926 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4927 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004928 // TODO: Add support for clauses.
4929 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004930 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004931 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004932 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4933 emitEmptyBoundParameters);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004934 emitPostUpdateForReductionClause(CGF, S,
4935 [](CodeGenFunction &) { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004936}
4937
4938void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4939 CodeGenModule &CGM, StringRef ParentName,
4940 const OMPTargetParallelDirective &S) {
4941 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4942 emitTargetParallelRegion(CGF, S, Action);
4943 };
4944 llvm::Function *Fn;
4945 llvm::Constant *Addr;
4946 // Emit target region as a standalone region.
4947 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4948 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4949 assert(Fn && Addr && "Target device function emission failed.");
4950}
4951
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004952void CodeGenFunction::EmitOMPTargetParallelDirective(
4953 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004954 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4955 emitTargetParallelRegion(CGF, S, Action);
4956 };
4957 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004958}
4959
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004960static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4961 const OMPTargetParallelForDirective &S,
4962 PrePostActionTy &Action) {
4963 Action.Enter(CGF);
4964 // Emit directive as a combined directive that consists of two implicit
4965 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00004966 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4967 Action.Enter(CGF);
Alexey Bataev2139ed62017-11-16 18:20:21 +00004968 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4969 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004970 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4971 emitDispatchForLoopBounds);
4972 };
4973 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4974 emitEmptyBoundParameters);
4975}
4976
4977void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4978 CodeGenModule &CGM, StringRef ParentName,
4979 const OMPTargetParallelForDirective &S) {
4980 // Emit SPMD target parallel for region as a standalone region.
4981 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4982 emitTargetParallelForRegion(CGF, S, Action);
4983 };
4984 llvm::Function *Fn;
4985 llvm::Constant *Addr;
4986 // Emit target region as a standalone region.
4987 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4988 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4989 assert(Fn && Addr && "Target device function emission failed.");
4990}
4991
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004992void CodeGenFunction::EmitOMPTargetParallelForDirective(
4993 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004994 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4995 emitTargetParallelForRegion(CGF, S, Action);
4996 };
4997 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004998}
4999
Alexey Bataev5d7edca2017-11-09 17:32:15 +00005000static void
5001emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
5002 const OMPTargetParallelForSimdDirective &S,
5003 PrePostActionTy &Action) {
5004 Action.Enter(CGF);
5005 // Emit directive as a combined directive that consists of two implicit
5006 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00005007 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5008 Action.Enter(CGF);
Alexey Bataev5d7edca2017-11-09 17:32:15 +00005009 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
5010 emitDispatchForLoopBounds);
5011 };
5012 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
5013 emitEmptyBoundParameters);
5014}
5015
5016void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
5017 CodeGenModule &CGM, StringRef ParentName,
5018 const OMPTargetParallelForSimdDirective &S) {
5019 // Emit SPMD target parallel for region as a standalone region.
5020 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5021 emitTargetParallelForSimdRegion(CGF, S, Action);
5022 };
5023 llvm::Function *Fn;
5024 llvm::Constant *Addr;
5025 // Emit target region as a standalone region.
5026 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
5027 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
5028 assert(Fn && Addr && "Target device function emission failed.");
5029}
5030
5031void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
5032 const OMPTargetParallelForSimdDirective &S) {
5033 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5034 emitTargetParallelForSimdRegion(CGF, S, Action);
5035 };
5036 emitCommonOMPTargetDirective(*this, S, CodeGen);
5037}
5038
Alexey Bataev7292c292016-04-25 12:22:29 +00005039/// Emit a helper variable and return corresponding lvalue.
5040static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
5041 const ImplicitParamDecl *PVD,
5042 CodeGenFunction::OMPPrivateScope &Privates) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005043 const auto *VDecl = cast<VarDecl>(Helper->getDecl());
5044 Privates.addPrivate(VDecl,
5045 [&CGF, PVD]() { return CGF.GetAddrOfLocalVar(PVD); });
Alexey Bataev7292c292016-04-25 12:22:29 +00005046}
5047
5048void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
5049 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
5050 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00005051 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
Alexey Bataevddf3db92018-04-13 17:31:06 +00005052 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
5053 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev7292c292016-04-25 12:22:29 +00005054 const Expr *IfCond = nullptr;
5055 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
5056 if (C->getNameModifier() == OMPD_unknown ||
5057 C->getNameModifier() == OMPD_taskloop) {
5058 IfCond = C->getCondition();
5059 break;
5060 }
5061 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005062
5063 OMPTaskDataTy Data;
5064 // Check if taskloop must be emitted without taskgroup.
5065 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00005066 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005067 Data.Tied = true;
5068 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005069 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
5070 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005071 Data.Schedule.setInt(/*IntVal=*/false);
5072 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005073 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
5074 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005075 Data.Schedule.setInt(/*IntVal=*/true);
5076 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005077 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005078
5079 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
5080 // if (PreCond) {
5081 // for (IV in 0..LastIteration) BODY;
5082 // <Final counter/linear vars updates>;
5083 // }
5084 //
5085
5086 // Emit: if (PreCond) - begin.
5087 // If the condition constant folds and can be elided, avoid emitting the
5088 // whole loop.
5089 bool CondConstant;
5090 llvm::BasicBlock *ContBlock = nullptr;
5091 OMPLoopScope PreInitScope(CGF, S);
5092 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
5093 if (!CondConstant)
5094 return;
5095 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005096 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
Alexey Bataev7292c292016-04-25 12:22:29 +00005097 ContBlock = CGF.createBasicBlock("taskloop.if.end");
5098 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
5099 CGF.getProfileCount(&S));
5100 CGF.EmitBlock(ThenBlock);
5101 CGF.incrementProfileCounter(&S);
5102 }
5103
Alexey Bataev14a388f2019-10-25 10:27:13 -04005104 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00005105 CGF.EmitOMPSimdInit(S);
Alexey Bataev14a388f2019-10-25 10:27:13 -04005106 (void)CGF.EmitOMPLinearClauseInit(S);
5107 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00005108
Alexey Bataev7292c292016-04-25 12:22:29 +00005109 OMPPrivateScope LoopScope(CGF);
5110 // Emit helper vars inits.
5111 enum { LowerBound = 5, UpperBound, Stride, LastIter };
5112 auto *I = CS->getCapturedDecl()->param_begin();
5113 auto *LBP = std::next(I, LowerBound);
5114 auto *UBP = std::next(I, UpperBound);
5115 auto *STP = std::next(I, Stride);
5116 auto *LIP = std::next(I, LastIter);
5117 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
5118 LoopScope);
5119 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
5120 LoopScope);
5121 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
5122 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
5123 LoopScope);
5124 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataev14a388f2019-10-25 10:27:13 -04005125 CGF.EmitOMPLinearClause(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00005126 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00005127 (void)LoopScope.Privatize();
5128 // Emit the loop iteration variable.
5129 const Expr *IVExpr = S.getIterationVariable();
Alexey Bataevddf3db92018-04-13 17:31:06 +00005130 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
Alexey Bataev7292c292016-04-25 12:22:29 +00005131 CGF.EmitVarDecl(*IVDecl);
5132 CGF.EmitIgnoredExpr(S.getInit());
5133
5134 // Emit the iterations count variable.
5135 // If it is not a variable, Sema decided to calculate iterations count on
5136 // each iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00005137 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005138 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
5139 // Emit calculation of the iterations count.
5140 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
5141 }
5142
5143 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
5144 S.getInc(),
5145 [&S](CodeGenFunction &CGF) {
5146 CGF.EmitOMPLoopBody(S, JumpDest());
5147 CGF.EmitStopPoint(&S);
5148 },
5149 [](CodeGenFunction &) {});
5150 // Emit: if (PreCond) - end.
5151 if (ContBlock) {
5152 CGF.EmitBranch(ContBlock);
5153 CGF.EmitBlock(ContBlock, true);
5154 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00005155 // Emit final copy of the lastprivate variables if IsLastIter != 0.
5156 if (HasLastprivateClause) {
5157 CGF.EmitOMPLastprivateClauseFinal(
5158 S, isOpenMPSimdDirective(S.getDirectiveKind()),
5159 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
5160 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005161 (*LIP)->getType(), S.getBeginLoc())));
Alexey Bataevf93095a2016-05-05 08:46:22 +00005162 }
Alexey Bataev14a388f2019-10-25 10:27:13 -04005163 CGF.EmitOMPLinearClauseFinal(S, [LIP, &S](CodeGenFunction &CGF) {
5164 return CGF.Builder.CreateIsNotNull(
5165 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
5166 (*LIP)->getType(), S.getBeginLoc()));
5167 });
Alexey Bataev7292c292016-04-25 12:22:29 +00005168 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005169 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
James Y Knight9871db02019-02-05 16:42:33 +00005170 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005171 const OMPTaskDataTy &Data) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005172 auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond,
5173 &Data](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005174 OMPLoopScope PreInitScope(CGF, S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005175 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005176 OutlinedFn, SharedsTy,
5177 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00005178 };
5179 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
5180 CodeGen);
5181 };
Alexey Bataev475a7442018-01-12 19:39:11 +00005182 if (Data.Nogroup) {
5183 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
5184 } else {
Alexey Bataev33446032017-07-12 18:09:32 +00005185 CGM.getOpenMPRuntime().emitTaskgroupRegion(
5186 *this,
5187 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
5188 PrePostActionTy &Action) {
5189 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00005190 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
5191 Data);
Alexey Bataev33446032017-07-12 18:09:32 +00005192 },
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005193 S.getBeginLoc());
Alexey Bataev33446032017-07-12 18:09:32 +00005194 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005195}
5196
Alexey Bataev49f6e782015-12-01 04:18:41 +00005197void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005198 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00005199}
5200
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005201void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
5202 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00005203 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005204}
Samuel Antao686c70c2016-05-26 17:30:50 +00005205
Alexey Bataev60e51c42019-10-10 20:13:02 +00005206void CodeGenFunction::EmitOMPMasterTaskLoopDirective(
5207 const OMPMasterTaskLoopDirective &S) {
5208 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5209 Action.Enter(CGF);
5210 EmitOMPTaskLoopBasedDirective(S);
5211 };
5212 OMPLexicalScope Scope(*this, S, llvm::None, /*EmitPreInitStmt=*/false);
5213 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
5214}
5215
Alexey Bataevb8552ab2019-10-18 16:47:35 +00005216void CodeGenFunction::EmitOMPMasterTaskLoopSimdDirective(
5217 const OMPMasterTaskLoopSimdDirective &S) {
5218 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5219 Action.Enter(CGF);
5220 EmitOMPTaskLoopBasedDirective(S);
5221 };
5222 OMPLexicalScope Scope(*this, S, llvm::None, /*EmitPreInitStmt=*/false);
5223 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
5224}
5225
Alexey Bataev5bbcead2019-10-14 17:17:41 +00005226void CodeGenFunction::EmitOMPParallelMasterTaskLoopDirective(
5227 const OMPParallelMasterTaskLoopDirective &S) {
5228 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5229 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
5230 PrePostActionTy &Action) {
5231 Action.Enter(CGF);
5232 CGF.EmitOMPTaskLoopBasedDirective(S);
5233 };
5234 OMPLexicalScope Scope(CGF, S, llvm::None, /*EmitPreInitStmt=*/false);
5235 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
5236 S.getBeginLoc());
5237 };
5238 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop, CodeGen,
5239 emitEmptyBoundParameters);
5240}
5241
Alexey Bataev14a388f2019-10-25 10:27:13 -04005242void CodeGenFunction::EmitOMPParallelMasterTaskLoopSimdDirective(
5243 const OMPParallelMasterTaskLoopSimdDirective &S) {
5244 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5245 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
5246 PrePostActionTy &Action) {
5247 Action.Enter(CGF);
5248 CGF.EmitOMPTaskLoopBasedDirective(S);
5249 };
5250 OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false);
5251 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
5252 S.getBeginLoc());
5253 };
5254 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop_simd, CodeGen,
5255 emitEmptyBoundParameters);
5256}
5257
Samuel Antao686c70c2016-05-26 17:30:50 +00005258// Generate the instructions for '#pragma omp target update' directive.
5259void CodeGenFunction::EmitOMPTargetUpdateDirective(
5260 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00005261 // If we don't have target devices, don't bother emitting the data mapping
5262 // code.
5263 if (CGM.getLangOpts().OMPTargetTriples.empty())
5264 return;
5265
5266 // Check if we have any if clause associated with the directive.
5267 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005268 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005269 IfCond = C->getCondition();
5270
5271 // Check if we have any device clause associated with the directive.
5272 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005273 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005274 Device = C->getDevice();
5275
Alexey Bataev475a7442018-01-12 19:39:11 +00005276 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00005277 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00005278}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005279
5280void CodeGenFunction::EmitSimpleOMPExecutableDirective(
5281 const OMPExecutableDirective &D) {
5282 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
5283 return;
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08005284 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005285 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
5286 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
5287 } else {
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005288 OMPPrivateScope LoopGlobals(CGF);
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005289 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005290 for (const Expr *E : LD->counters()) {
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005291 const auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
5292 if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) {
5293 LValue GlobLVal = CGF.EmitLValue(E);
5294 LoopGlobals.addPrivate(
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08005295 VD, [&GlobLVal]() { return GlobLVal.getAddress(); });
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005296 }
Bjorn Pettersson6c2d83b2018-10-30 08:49:26 +00005297 if (isa<OMPCapturedExprDecl>(VD)) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005298 // Emit only those that were not explicitly referenced in clauses.
5299 if (!CGF.LocalDeclMap.count(VD))
5300 CGF.EmitVarDecl(*VD);
5301 }
5302 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005303 for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) {
5304 if (!C->getNumForLoops())
5305 continue;
5306 for (unsigned I = LD->getCollapsedNumber(),
5307 E = C->getLoopNumIterations().size();
5308 I < E; ++I) {
5309 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
Mike Rice0ed46662018-09-20 17:19:41 +00005310 cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00005311 // Emit only those that were not explicitly referenced in clauses.
5312 if (!CGF.LocalDeclMap.count(VD))
5313 CGF.EmitVarDecl(*VD);
5314 }
5315 }
5316 }
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005317 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005318 LoopGlobals.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00005319 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005320 }
5321 };
5322 OMPSimdLexicalScope Scope(*this, D);
5323 CGM.getOpenMPRuntime().emitInlinedDirective(
5324 *this,
5325 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
5326 : D.getDirectiveKind(),
5327 CodeGen);
5328}