blob: 2195c4443eb83ecad0145ec521bbb4d838bd57d9 [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 Hatanakaf139ae32019-12-03 15:17:01 -080080 return CGF.EmitLValue(&DRE).getAddress(CGF);
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 Hatanakaf139ae32019-12-03 15:17:01 -0800235 return CGF.EmitLValue(&DRE).getAddress(CGF);
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 Hatanakaf139ae32019-12-03 15:17:01 -0800328 CapturedVars.push_back(EmitLValue(*I).getAddress(*this).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 Hatanakaf139ae32019-12-03 15:17:01 -0800339 AddrLV.getAddress(CGF).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 Hatanakaf139ae32019-12-03 15:17:01 -0800343 .getAddress(CGF);
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 Hatanakaf139ae32019-12-03 15:17:01 -0800522 Address ArgAddr = ArgLVal.getAddress(CGF);
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 Hatanakaf139ae32019-12-03 15:17:01 -0800544 : ArgLVal.getAddress(CGF)}});
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 Hatanakaf139ae32019-12-03 15:17:01 -0800549 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress(CGF)}});
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 Hatanakaf139ae32019-12-03 15:17:01 -0800833 Emission.getAllocatedAddress(),
834 OriginalLVal.getAddress(*this), 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 Hatanakaf139ae32019-12-03 15:17:01 -0800852 Address OriginalAddr = OriginalLVal.getAddress(*this);
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 Hatanakaf139ae32019-12-03 15:17:01 -0800929 MasterAddr = EmitLValue(&DRE).getAddress(*this);
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 Hatanakaf139ae32019-12-03 15:17:01 -0800938 Address PrivateAddr = EmitLValue(*IRef).getAddress(*this);
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 Hatanakaf139ae32019-12-03 15:17:01 -08001006 return EmitLValue(&DRE).getAddress(*this);
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 Hatanakaf139ae32019-12-03 15:17:01 -08001163 PrivateScope.addPrivate(LHSVD, [&RedCG, Count, this]() {
1164 return RedCG.getSharedLValue(Count).getAddress(*this);
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 Hatanakaf139ae32019-12-03 15:17:01 -08001172 PrivateScope.addPrivate(LHSVD, [&RedCG, Count, this]() {
1173 return RedCG.getSharedLValue(Count).getAddress(*this);
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 Hatanakaf139ae32019-12-03 15:17:01 -08001183 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress(*this);
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 Hatanakaf139ae32019-12-03 15:17:01 -08001532 Address OrigAddr = EmitLValue(&DRE).getAddress(*this);
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 Hatanakaf139ae32019-12-03 15:17:01 -08001602 return EmitLValue(&DRE).getAddress(*this);
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 Hatanakaf139ae32019-12-03 15:17:01 -08001765 OrigAddr =
1766 EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress(*this);
Alexey Bataevab4ea222018-03-07 18:17:06 +00001767 } else {
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001768 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(PrivateVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001769 /*RefersToEnclosingVariableOrCapture=*/false,
1770 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001771 OrigAddr = EmitLValue(&DRE).getAddress(*this);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001772 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001773 OMPPrivateScope VarScope(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001774 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001775 (void)VarScope.Privatize();
1776 EmitIgnoredExpr(F);
1777 }
1778 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001779 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001780 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001781 if (DoneBB)
1782 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001783}
1784
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001785static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1786 const OMPLoopDirective &S,
1787 CodeGenFunction::JumpDest LoopExit) {
1788 CGF.EmitOMPLoopBody(S, LoopExit);
1789 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001790}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001791
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001792/// Emit a helper variable and return corresponding lvalue.
1793static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1794 const DeclRefExpr *Helper) {
1795 auto VDecl = cast<VarDecl>(Helper->getDecl());
1796 CGF.EmitVarDecl(*VDecl);
1797 return CGF.EmitLValue(Helper);
1798}
1799
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05001800static void emitCommonSimdLoop(CodeGenFunction &CGF, const OMPLoopDirective &S,
1801 const RegionCodeGenTy &SimdInitGen,
1802 const RegionCodeGenTy &BodyCodeGen) {
1803 auto &&ThenGen = [&SimdInitGen, &BodyCodeGen](CodeGenFunction &CGF,
1804 PrePostActionTy &) {
1805 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
1806 SimdInitGen(CGF);
1807
1808 BodyCodeGen(CGF);
1809 };
1810 auto &&ElseGen = [&BodyCodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
1811 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
1812 CGF.LoopStack.setVectorizeEnable(/*Enable=*/false);
1813
1814 BodyCodeGen(CGF);
1815 };
1816 const Expr *IfCond = nullptr;
1817 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1818 if (CGF.getLangOpts().OpenMP >= 50 &&
1819 (C->getNameModifier() == OMPD_unknown ||
1820 C->getNameModifier() == OMPD_simd)) {
1821 IfCond = C->getCondition();
1822 break;
1823 }
1824 }
1825 if (IfCond) {
1826 CGF.CGM.getOpenMPRuntime().emitIfClause(CGF, IfCond, ThenGen, ElseGen);
1827 } else {
1828 RegionCodeGenTy ThenRCG(ThenGen);
1829 ThenRCG(CGF);
1830 }
1831}
1832
Alexey Bataevf8365372017-11-17 17:57:25 +00001833static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1834 PrePostActionTy &Action) {
1835 Action.Enter(CGF);
1836 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1837 "Expected simd directive");
1838 OMPLoopScope PreInitScope(CGF, S);
1839 // if (PreCond) {
1840 // for (IV in 0..LastIteration) BODY;
1841 // <Final counter/linear vars updates>;
1842 // }
1843 //
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001844 if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
1845 isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
1846 isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
1847 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1848 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1849 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001850
Alexey Bataevf8365372017-11-17 17:57:25 +00001851 // Emit: if (PreCond) - begin.
1852 // If the condition constant folds and can be elided, avoid emitting the
1853 // whole loop.
1854 bool CondConstant;
1855 llvm::BasicBlock *ContBlock = nullptr;
1856 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1857 if (!CondConstant)
1858 return;
1859 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001860 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("simd.if.then");
Alexey Bataevf8365372017-11-17 17:57:25 +00001861 ContBlock = CGF.createBasicBlock("simd.if.end");
1862 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1863 CGF.getProfileCount(&S));
1864 CGF.EmitBlock(ThenBlock);
1865 CGF.incrementProfileCounter(&S);
1866 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001867
Alexey Bataevf8365372017-11-17 17:57:25 +00001868 // Emit the loop iteration variable.
1869 const Expr *IVExpr = S.getIterationVariable();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001870 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
Alexey Bataevf8365372017-11-17 17:57:25 +00001871 CGF.EmitVarDecl(*IVDecl);
1872 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001873
Alexey Bataevf8365372017-11-17 17:57:25 +00001874 // Emit the iterations count variable.
1875 // If it is not a variable, Sema decided to calculate iterations count on
1876 // each iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00001877 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexey Bataevf8365372017-11-17 17:57:25 +00001878 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1879 // Emit calculation of the iterations count.
1880 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1881 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001882
Alexey Bataevf8365372017-11-17 17:57:25 +00001883 emitAlignedClause(CGF, S);
1884 (void)CGF.EmitOMPLinearClauseInit(S);
1885 {
1886 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1887 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1888 CGF.EmitOMPLinearClause(S, LoopScope);
1889 CGF.EmitOMPPrivateClause(S, LoopScope);
1890 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1891 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1892 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00001893 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
1894 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Alexey Bataevd08c0562019-11-19 12:07:54 -05001895
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05001896 emitCommonSimdLoop(
1897 CGF, S,
1898 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1899 CGF.EmitOMPSimdInit(S);
1900 },
1901 [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
1902 CGF.EmitOMPInnerLoop(
1903 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1904 [&S](CodeGenFunction &CGF) {
1905 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1906 CGF.EmitStopPoint(&S);
1907 },
1908 [](CodeGenFunction &) {});
1909 });
Alexey Bataevddf3db92018-04-13 17:31:06 +00001910 CGF.EmitOMPSimdFinal(S, [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001911 // Emit final copy of the lastprivate variables at the end of loops.
1912 if (HasLastprivateClause)
1913 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1914 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001915 emitPostUpdateForReductionClause(CGF, S,
1916 [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001917 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001918 CGF.EmitOMPLinearClauseFinal(S, [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001919 // Emit: if (PreCond) - end.
1920 if (ContBlock) {
1921 CGF.EmitBranch(ContBlock);
1922 CGF.EmitBlock(ContBlock, true);
1923 }
1924}
1925
1926void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1927 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1928 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001929 };
Alexey Bataev475a7442018-01-12 19:39:11 +00001930 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001931 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001932}
1933
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001934void CodeGenFunction::EmitOMPOuterLoop(
1935 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1936 CodeGenFunction::OMPPrivateScope &LoopScope,
1937 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1938 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1939 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001940 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001941
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001942 const Expr *IVExpr = S.getIterationVariable();
1943 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1944 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1945
Alexey Bataevddf3db92018-04-13 17:31:06 +00001946 JumpDest LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001947
1948 // Start the loop with a block that tests the condition.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001949 llvm::BasicBlock *CondBlock = createBasicBlock("omp.dispatch.cond");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001950 EmitBlock(CondBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001951 const SourceRange R = S.getSourceRange();
Amara Emerson652795d2016-11-10 14:44:30 +00001952 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1953 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001954
1955 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001956 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001957 // UB = min(UB, GlobalUB) or
1958 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1959 // 'distribute parallel for')
1960 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001961 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001962 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001963 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001964 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001965 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001966 BoolCondVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001967 RT.emitForNext(*this, S.getBeginLoc(), IVSize, IVSigned, LoopArgs.IL,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001968 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001969 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001970
1971 // If there are any cleanups between here and the loop-exit scope,
1972 // create a block to stage a loop exit along.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001973 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001974 if (LoopScope.requiresCleanups())
1975 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1976
Alexey Bataevddf3db92018-04-13 17:31:06 +00001977 llvm::BasicBlock *LoopBody = createBasicBlock("omp.dispatch.body");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001978 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1979 if (ExitBlock != LoopExit.getBlock()) {
1980 EmitBlock(ExitBlock);
1981 EmitBranchThroughCleanup(LoopExit);
1982 }
1983 EmitBlock(LoopBody);
1984
Alexander Musman92bdaab2015-03-12 13:37:50 +00001985 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1986 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001987 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001988 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001989
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001990 // Create a block for the increment.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001991 JumpDest Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001992 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1993
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05001994 emitCommonSimdLoop(
1995 *this, S,
1996 [&S, IsMonotonic](CodeGenFunction &CGF, PrePostActionTy &) {
1997 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1998 // with dynamic/guided scheduling and without ordered clause.
1999 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
2000 CGF.LoopStack.setParallel(!IsMonotonic);
2001 else
2002 CGF.EmitOMPSimdInit(S, IsMonotonic);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002003 },
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002004 [&S, &LoopArgs, LoopExit, &CodeGenLoop, IVSize, IVSigned, &CodeGenOrdered,
2005 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
2006 SourceLocation Loc = S.getBeginLoc();
2007 // when 'distribute' is not combined with a 'for':
2008 // while (idx <= UB) { BODY; ++idx; }
2009 // when 'distribute' is combined with a 'for'
2010 // (e.g. 'distribute parallel for')
2011 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
2012 CGF.EmitOMPInnerLoop(
2013 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
2014 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
2015 CodeGenLoop(CGF, S, LoopExit);
2016 },
2017 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
2018 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
2019 });
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002020 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002021
2022 EmitBlock(Continue.getBlock());
2023 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002024 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002025 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002026 EmitIgnoredExpr(LoopArgs.NextLB);
2027 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002028 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002029
2030 EmitBranch(CondBlock);
2031 LoopStack.pop();
2032 // Emit the fall-through block.
2033 EmitBlock(LoopExit.getBlock());
2034
2035 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002036 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
2037 if (!DynamicOrOrdered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002038 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00002039 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002040 };
2041 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002042}
2043
2044void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002045 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002046 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002047 const OMPLoopArguments &LoopArgs,
2048 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002049 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002050
2051 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002052 const bool DynamicOrOrdered =
2053 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002054
2055 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002056 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002057 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002058 "static non-chunked schedule does not need outer loop");
2059
2060 // Emit outer loop.
2061 //
2062 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2063 // When schedule(dynamic,chunk_size) is specified, the iterations are
2064 // distributed to threads in the team in chunks as the threads request them.
2065 // Each thread executes a chunk of iterations, then requests another chunk,
2066 // until no chunks remain to be distributed. Each chunk contains chunk_size
2067 // iterations, except for the last chunk to be distributed, which may have
2068 // fewer iterations. When no chunk_size is specified, it defaults to 1.
2069 //
2070 // When schedule(guided,chunk_size) is specified, the iterations are assigned
2071 // to threads in the team in chunks as the executing threads request them.
2072 // Each thread executes a chunk of iterations, then requests another chunk,
2073 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
2074 // each chunk is proportional to the number of unassigned iterations divided
2075 // by the number of threads in the team, decreasing to 1. For a chunk_size
2076 // with value k (greater than 1), the size of each chunk is determined in the
2077 // same way, with the restriction that the chunks do not contain fewer than k
2078 // iterations (except for the last chunk to be assigned, which may have fewer
2079 // than k iterations).
2080 //
2081 // When schedule(auto) is specified, the decision regarding scheduling is
2082 // delegated to the compiler and/or runtime system. The programmer gives the
2083 // implementation the freedom to choose any possible mapping of iterations to
2084 // threads in the team.
2085 //
2086 // When schedule(runtime) is specified, the decision regarding scheduling is
2087 // deferred until run time, and the schedule and chunk size are taken from the
2088 // run-sched-var ICV. If the ICV is set to auto, the schedule is
2089 // implementation defined
2090 //
2091 // while(__kmpc_dispatch_next(&LB, &UB)) {
2092 // idx = LB;
2093 // while (idx <= UB) { BODY; ++idx;
2094 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
2095 // } // inner loop
2096 // }
2097 //
2098 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2099 // When schedule(static, chunk_size) is specified, iterations are divided into
2100 // chunks of size chunk_size, and the chunks are assigned to the threads in
2101 // the team in a round-robin fashion in the order of the thread number.
2102 //
2103 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
2104 // while (idx <= UB) { BODY; ++idx; } // inner loop
2105 // LB = LB + ST;
2106 // UB = UB + ST;
2107 // }
2108 //
2109
2110 const Expr *IVExpr = S.getIterationVariable();
2111 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2112 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2113
2114 if (DynamicOrOrdered) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002115 const std::pair<llvm::Value *, llvm::Value *> DispatchBounds =
2116 CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002117 llvm::Value *LBVal = DispatchBounds.first;
2118 llvm::Value *UBVal = DispatchBounds.second;
2119 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
2120 LoopArgs.Chunk};
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002121 RT.emitForDispatchInit(*this, S.getBeginLoc(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002122 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002123 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002124 CGOpenMPRuntime::StaticRTInput StaticInit(
2125 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
2126 LoopArgs.ST, LoopArgs.Chunk);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002127 RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(),
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002128 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002129 }
2130
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002131 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
2132 const unsigned IVSize,
2133 const bool IVSigned) {
2134 if (Ordered) {
2135 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
2136 IVSigned);
2137 }
2138 };
2139
2140 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
2141 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
2142 OuterLoopArgs.IncExpr = S.getInc();
2143 OuterLoopArgs.Init = S.getInit();
2144 OuterLoopArgs.Cond = S.getCond();
2145 OuterLoopArgs.NextLB = S.getNextLowerBound();
2146 OuterLoopArgs.NextUB = S.getNextUpperBound();
2147 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
2148 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002149}
2150
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002151static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
2152 const unsigned IVSize, const bool IVSigned) {}
2153
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002154void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002155 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
2156 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
2157 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002158
Alexey Bataevddf3db92018-04-13 17:31:06 +00002159 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002160
2161 // Emit outer loop.
2162 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
2163 // dynamic
2164 //
2165
2166 const Expr *IVExpr = S.getIterationVariable();
2167 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2168 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2169
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002170 CGOpenMPRuntime::StaticRTInput StaticInit(
2171 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
2172 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002173 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002174
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002175 // for combined 'distribute' and 'for' the increment expression of distribute
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002176 // is stored in DistInc. For 'distribute' alone, it is in Inc.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002177 Expr *IncExpr;
2178 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
2179 IncExpr = S.getDistInc();
2180 else
2181 IncExpr = S.getInc();
2182
2183 // this routine is shared by 'omp distribute parallel for' and
2184 // 'omp distribute': select the right EUB expression depending on the
2185 // directive
2186 OMPLoopArguments OuterLoopArgs;
2187 OuterLoopArgs.LB = LoopArgs.LB;
2188 OuterLoopArgs.UB = LoopArgs.UB;
2189 OuterLoopArgs.ST = LoopArgs.ST;
2190 OuterLoopArgs.IL = LoopArgs.IL;
2191 OuterLoopArgs.Chunk = LoopArgs.Chunk;
2192 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2193 ? S.getCombinedEnsureUpperBound()
2194 : S.getEnsureUpperBound();
2195 OuterLoopArgs.IncExpr = IncExpr;
2196 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2197 ? S.getCombinedInit()
2198 : S.getInit();
2199 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2200 ? S.getCombinedCond()
2201 : S.getCond();
2202 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2203 ? S.getCombinedNextLowerBound()
2204 : S.getNextLowerBound();
2205 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2206 ? S.getCombinedNextUpperBound()
2207 : S.getNextUpperBound();
2208
2209 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
2210 LoopScope, OuterLoopArgs, CodeGenLoopContent,
2211 emitEmptyOrdered);
2212}
2213
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002214static std::pair<LValue, LValue>
2215emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
2216 const OMPExecutableDirective &S) {
2217 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2218 LValue LB =
2219 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2220 LValue UB =
2221 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2222
2223 // When composing 'distribute' with 'for' (e.g. as in 'distribute
2224 // parallel for') we need to use the 'distribute'
2225 // chunk lower and upper bounds rather than the whole loop iteration
2226 // space. These are parameters to the outlined function for 'parallel'
2227 // and we copy the bounds of the previous schedule into the
2228 // the current ones.
2229 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
2230 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002231 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
2232 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002233 PrevLBVal = CGF.EmitScalarConversion(
2234 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002235 LS.getIterationVariable()->getType(),
2236 LS.getPrevLowerBoundVariable()->getExprLoc());
2237 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
2238 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002239 PrevUBVal = CGF.EmitScalarConversion(
2240 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002241 LS.getIterationVariable()->getType(),
2242 LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002243
2244 CGF.EmitStoreOfScalar(PrevLBVal, LB);
2245 CGF.EmitStoreOfScalar(PrevUBVal, UB);
2246
2247 return {LB, UB};
2248}
2249
2250/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
2251/// we need to use the LB and UB expressions generated by the worksharing
2252/// code generation support, whereas in non combined situations we would
2253/// just emit 0 and the LastIteration expression
2254/// This function is necessary due to the difference of the LB and UB
2255/// types for the RT emission routines for 'for_static_init' and
2256/// 'for_dispatch_init'
2257static std::pair<llvm::Value *, llvm::Value *>
2258emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
2259 const OMPExecutableDirective &S,
2260 Address LB, Address UB) {
2261 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2262 const Expr *IVExpr = LS.getIterationVariable();
2263 // when implementing a dynamic schedule for a 'for' combined with a
2264 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
2265 // is not normalized as each team only executes its own assigned
2266 // distribute chunk
2267 QualType IteratorTy = IVExpr->getType();
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002268 llvm::Value *LBVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002269 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002270 llvm::Value *UBVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002271 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002272 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00002273}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002274
2275static void emitDistributeParallelForDistributeInnerBoundParams(
2276 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2277 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2278 const auto &Dir = cast<OMPLoopDirective>(S);
2279 LValue LB =
2280 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002281 llvm::Value *LBCast =
2282 CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(LB.getAddress(CGF)),
2283 CGF.SizeTy, /*isSigned=*/false);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002284 CapturedVars.push_back(LBCast);
2285 LValue UB =
2286 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2287
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002288 llvm::Value *UBCast =
2289 CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(UB.getAddress(CGF)),
2290 CGF.SizeTy, /*isSigned=*/false);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002291 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00002292}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002293
2294static void
2295emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2296 const OMPLoopDirective &S,
2297 CodeGenFunction::JumpDest LoopExit) {
2298 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00002299 PrePostActionTy &Action) {
2300 Action.Enter(CGF);
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002301 bool HasCancel = false;
2302 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2303 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2304 HasCancel = D->hasCancel();
2305 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2306 HasCancel = D->hasCancel();
Alexey Bataev16e79882017-11-22 21:12:03 +00002307 else if (const auto *D =
2308 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2309 HasCancel = D->hasCancel();
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002310 }
2311 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2312 HasCancel);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002313 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2314 emitDistributeParallelForInnerBounds,
2315 emitDistributeParallelForDispatchBounds);
2316 };
2317
2318 emitCommonOMPParallelDirective(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002319 CGF, S,
2320 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2321 CGInlinedWorksharingLoop,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002322 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002323}
2324
Carlo Bertolli9925f152016-06-27 14:55:37 +00002325void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2326 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002327 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2328 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2329 S.getDistInc());
2330 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002331 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev10a54312017-11-27 16:54:08 +00002332 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002333}
2334
Kelvin Li4a39add2016-07-05 05:00:15 +00002335void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2336 const OMPDistributeParallelForSimdDirective &S) {
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002337 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2338 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2339 S.getDistInc());
2340 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002341 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002342 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Kelvin Li4a39add2016-07-05 05:00:15 +00002343}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002344
2345void CodeGenFunction::EmitOMPDistributeSimdDirective(
2346 const OMPDistributeSimdDirective &S) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00002347 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2348 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2349 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002350 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev617db5f2017-12-04 15:38:33 +00002351 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002352}
2353
Alexey Bataevf8365372017-11-17 17:57:25 +00002354void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2355 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2356 // Emit SPMD target parallel for region as a standalone region.
2357 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2358 emitOMPSimdRegion(CGF, S, Action);
2359 };
2360 llvm::Function *Fn;
2361 llvm::Constant *Addr;
2362 // Emit target region as a standalone region.
2363 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2364 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2365 assert(Fn && Addr && "Target device function emission failed.");
2366}
2367
Kelvin Li986330c2016-07-20 22:57:10 +00002368void CodeGenFunction::EmitOMPTargetSimdDirective(
2369 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002370 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2371 emitOMPSimdRegion(CGF, S, Action);
2372 };
2373 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002374}
2375
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002376namespace {
2377 struct ScheduleKindModifiersTy {
2378 OpenMPScheduleClauseKind Kind;
2379 OpenMPScheduleClauseModifier M1;
2380 OpenMPScheduleClauseModifier M2;
2381 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2382 OpenMPScheduleClauseModifier M1,
2383 OpenMPScheduleClauseModifier M2)
2384 : Kind(Kind), M1(M1), M2(M2) {}
2385 };
2386} // namespace
2387
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002388bool CodeGenFunction::EmitOMPWorksharingLoop(
2389 const OMPLoopDirective &S, Expr *EUB,
2390 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2391 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002392 // Emit the loop iteration variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002393 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2394 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
Alexander Musmanc6388682014-12-15 07:07:06 +00002395 EmitVarDecl(*IVDecl);
2396
2397 // Emit the iterations count variable.
2398 // If it is not a variable, Sema decided to calculate iterations count on each
2399 // iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00002400 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002401 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2402 // Emit calculation of the iterations count.
2403 EmitIgnoredExpr(S.getCalcLastIteration());
2404 }
2405
Alexey Bataevddf3db92018-04-13 17:31:06 +00002406 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Alexander Musmanc6388682014-12-15 07:07:06 +00002407
Alexey Bataev38e89532015-04-16 04:54:05 +00002408 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002409 // Check pre-condition.
2410 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002411 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002412 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002413 // If the condition constant folds and can be elided, avoid emitting the
2414 // whole loop.
2415 bool CondConstant;
2416 llvm::BasicBlock *ContBlock = nullptr;
2417 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2418 if (!CondConstant)
2419 return false;
2420 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002421 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
Alexey Bataev62dbb972015-04-22 11:59:37 +00002422 ContBlock = createBasicBlock("omp.precond.end");
2423 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002424 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002425 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002426 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002427 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002428
Alexey Bataevea33dee2018-02-15 23:39:43 +00002429 RunCleanupsScope DoacrossCleanupScope(*this);
Alexey Bataev8b427062016-05-25 12:36:08 +00002430 bool Ordered = false;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002431 if (const auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
Alexey Bataev8b427062016-05-25 12:36:08 +00002432 if (OrderedClause->getNumForLoops())
Alexey Bataevf138fda2018-08-13 19:04:24 +00002433 RT.emitDoacrossInit(*this, S, OrderedClause->getLoopNumIterations());
Alexey Bataev8b427062016-05-25 12:36:08 +00002434 else
2435 Ordered = true;
2436 }
2437
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002438 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002439 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002440 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002441 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002442
2443 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2444 LValue LB = Bounds.first;
2445 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002446 LValue ST =
2447 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2448 LValue IL =
2449 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2450
Alexander Musmanc6388682014-12-15 07:07:06 +00002451 // Emit 'then' code.
2452 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002453 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002454 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002455 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002456 // initialization of firstprivate variables and post-update of
2457 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002458 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002459 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002460 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002461 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002462 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002463 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002464 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002465 EmitOMPPrivateLoopCounters(S, LoopScope);
2466 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002467 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00002468 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2469 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002470
2471 // Detect the loop schedule kind and chunk.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002472 const Expr *ChunkExpr = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002473 OpenMPScheduleTy ScheduleKind;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002474 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002475 ScheduleKind.Schedule = C->getScheduleKind();
2476 ScheduleKind.M1 = C->getFirstScheduleModifier();
2477 ScheduleKind.M2 = C->getSecondScheduleModifier();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002478 ChunkExpr = C->getChunkSize();
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00002479 } else {
2480 // Default behaviour for schedule clause.
2481 CGM.getOpenMPRuntime().getDefaultScheduleAndChunk(
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002482 *this, S, ScheduleKind.Schedule, ChunkExpr);
2483 }
2484 bool HasChunkSizeOne = false;
2485 llvm::Value *Chunk = nullptr;
2486 if (ChunkExpr) {
2487 Chunk = EmitScalarExpr(ChunkExpr);
2488 Chunk = EmitScalarConversion(Chunk, ChunkExpr->getType(),
2489 S.getIterationVariable()->getType(),
2490 S.getBeginLoc());
Fangrui Song407659a2018-11-30 23:41:18 +00002491 Expr::EvalResult Result;
2492 if (ChunkExpr->EvaluateAsInt(Result, getContext())) {
2493 llvm::APSInt EvaluatedChunk = Result.Val.getInt();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002494 HasChunkSizeOne = (EvaluatedChunk.getLimitedValue() == 1);
Fangrui Song407659a2018-11-30 23:41:18 +00002495 }
Alexey Bataev3392d762016-02-16 11:18:12 +00002496 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002497 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2498 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002499 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2500 // If the static schedule kind is specified or if the ordered clause is
2501 // specified, and if no monotonic modifier is specified, the effect will
2502 // be as if the monotonic modifier was specified.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002503 bool StaticChunkedOne = RT.isStaticChunked(ScheduleKind.Schedule,
2504 /* Chunked */ Chunk != nullptr) && HasChunkSizeOne &&
2505 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
2506 if ((RT.isStaticNonchunked(ScheduleKind.Schedule,
2507 /* Chunked */ Chunk != nullptr) ||
2508 StaticChunkedOne) &&
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002509 !Ordered) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002510 JumpDest LoopExit =
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002511 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002512 emitCommonSimdLoop(
2513 *this, S,
2514 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2515 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2516 CGF.EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002517 },
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002518 [IVSize, IVSigned, Ordered, IL, LB, UB, ST, StaticChunkedOne, Chunk,
2519 &S, ScheduleKind, LoopExit,
2520 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
2521 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2522 // When no chunk_size is specified, the iteration space is divided
2523 // into chunks that are approximately equal in size, and at most
2524 // one chunk is distributed to each thread. Note that the size of
2525 // the chunks is unspecified in this case.
2526 CGOpenMPRuntime::StaticRTInput StaticInit(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002527 IVSize, IVSigned, Ordered, IL.getAddress(CGF),
2528 LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF),
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05002529 StaticChunkedOne ? Chunk : nullptr);
2530 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
2531 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind,
2532 StaticInit);
2533 // UB = min(UB, GlobalUB);
2534 if (!StaticChunkedOne)
2535 CGF.EmitIgnoredExpr(S.getEnsureUpperBound());
2536 // IV = LB;
2537 CGF.EmitIgnoredExpr(S.getInit());
2538 // For unchunked static schedule generate:
2539 //
2540 // while (idx <= UB) {
2541 // BODY;
2542 // ++idx;
2543 // }
2544 //
2545 // For static schedule with chunk one:
2546 //
2547 // while (IV <= PrevUB) {
2548 // BODY;
2549 // IV += ST;
2550 // }
2551 CGF.EmitOMPInnerLoop(
2552 S, LoopScope.requiresCleanups(),
2553 StaticChunkedOne ? S.getCombinedParForInDistCond()
2554 : S.getCond(),
2555 StaticChunkedOne ? S.getDistInc() : S.getInc(),
2556 [&S, LoopExit](CodeGenFunction &CGF) {
2557 CGF.EmitOMPLoopBody(S, LoopExit);
2558 CGF.EmitStopPoint(&S);
2559 },
2560 [](CodeGenFunction &) {});
2561 });
Alexey Bataev0f34da12015-07-02 04:17:07 +00002562 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002563 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002564 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002565 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00002566 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002567 };
2568 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002569 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002570 const bool IsMonotonic =
2571 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2572 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2573 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2574 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002575 // Emit the outer loop, which requests its work chunk [LB..UB] from
2576 // runtime and runs the inner loop to process it.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002577 const OMPLoopArguments LoopArguments(
2578 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
2579 IL.getAddress(*this), Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002580 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002581 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002582 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002583 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002584 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
2585 return CGF.Builder.CreateIsNotNull(
2586 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
2587 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002588 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002589 EmitOMPReductionClauseFinal(
2590 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2591 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2592 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002593 // Emit post-update of the reduction variables if IsLastIter != 0.
2594 emitPostUpdateForReductionClause(
Alexey Bataevddf3db92018-04-13 17:31:06 +00002595 *this, S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataev61205072016-03-02 04:57:40 +00002596 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002597 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataev61205072016-03-02 04:57:40 +00002598 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002599 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2600 if (HasLastprivateClause)
2601 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002602 S, isOpenMPSimdDirective(S.getDirectiveKind()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002603 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002604 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00002605 EmitOMPLinearClauseFinal(S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataevef549a82016-03-09 09:49:09 +00002606 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002607 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataevef549a82016-03-09 09:49:09 +00002608 });
Alexey Bataevea33dee2018-02-15 23:39:43 +00002609 DoacrossCleanupScope.ForceCleanup();
Alexander Musmanc6388682014-12-15 07:07:06 +00002610 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002611 if (ContBlock) {
2612 EmitBranch(ContBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002613 EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002614 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002615 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002616 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002617}
2618
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002619/// The following two functions generate expressions for the loop lower
2620/// and upper bounds in case of static and dynamic (dispatch) schedule
2621/// of the associated 'for' or 'distribute' loop.
2622static std::pair<LValue, LValue>
2623emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002624 const auto &LS = cast<OMPLoopDirective>(S);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002625 LValue LB =
2626 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2627 LValue UB =
2628 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2629 return {LB, UB};
2630}
2631
2632/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2633/// consider the lower and upper bound expressions generated by the
2634/// worksharing loop support, but we use 0 and the iteration space size as
2635/// constants
2636static std::pair<llvm::Value *, llvm::Value *>
2637emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2638 Address LB, Address UB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002639 const auto &LS = cast<OMPLoopDirective>(S);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002640 const Expr *IVExpr = LS.getIterationVariable();
2641 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2642 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2643 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2644 return {LBVal, UBVal};
2645}
2646
Alexander Musmanc6388682014-12-15 07:07:06 +00002647void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002648 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002649 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2650 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002651 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002652 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2653 emitForLoopBounds,
2654 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002655 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002656 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002657 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002658 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2659 S.hasCancel());
2660 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002661
2662 // Emit an implicit barrier at the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002663 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002664 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002665}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002666
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002667void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002668 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002669 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2670 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002671 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2672 emitForLoopBounds,
2673 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002674 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002675 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002676 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002677 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2678 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002679
2680 // Emit an implicit barrier at the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002681 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002682 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002683}
2684
Alexey Bataev2df54a02015-03-12 08:53:29 +00002685static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2686 const Twine &Name,
2687 llvm::Value *Init = nullptr) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002688 LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002689 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002690 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002691 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002692}
2693
Alexey Bataev3392d762016-02-16 11:18:12 +00002694void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002695 const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
2696 const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002697 bool HasLastprivates = false;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002698 auto &&CodeGen = [&S, CapturedStmt, CS,
2699 &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) {
2700 ASTContext &C = CGF.getContext();
2701 QualType KmpInt32Ty =
2702 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002703 // Emit helper vars inits.
2704 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2705 CGF.Builder.getInt32(0));
Alexey Bataevddf3db92018-04-13 17:31:06 +00002706 llvm::ConstantInt *GlobalUBVal = CS != nullptr
2707 ? CGF.Builder.getInt32(CS->size() - 1)
2708 : CGF.Builder.getInt32(0);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002709 LValue UB =
2710 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2711 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2712 CGF.Builder.getInt32(1));
2713 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2714 CGF.Builder.getInt32(0));
2715 // Loop counter.
2716 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002717 OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002718 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002719 OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002720 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2721 // Generate condition for loop.
2722 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002723 OK_Ordinary, S.getBeginLoc(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002724 // Increment for loop counter.
2725 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002726 S.getBeginLoc(), true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002727 auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002728 // Iterate through all sections and emit a switch construct:
2729 // switch (IV) {
2730 // case 0:
2731 // <SectionStmt[0]>;
2732 // break;
2733 // ...
2734 // case <NumSection> - 1:
2735 // <SectionStmt[<NumSection> - 1]>;
2736 // break;
2737 // }
2738 // .omp.sections.exit:
Alexey Bataevddf3db92018-04-13 17:31:06 +00002739 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2740 llvm::SwitchInst *SwitchStmt =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002741 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002742 ExitBB, CS == nullptr ? 1 : CS->size());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002743 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002744 unsigned CaseNumber = 0;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002745 for (const Stmt *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002746 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2747 CGF.EmitBlock(CaseBB);
2748 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002749 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002750 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002751 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002752 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002753 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002754 llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case");
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002755 CGF.EmitBlock(CaseBB);
2756 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002757 CGF.EmitStmt(CapturedStmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002758 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002759 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002760 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002761 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002762
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002763 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2764 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002765 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002766 // initialization of firstprivate variables and post-update of lastprivate
2767 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002768 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002769 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002770 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002771 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002772 CGF.EmitOMPPrivateClause(S, LoopScope);
2773 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2774 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2775 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00002776 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2777 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002778
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002779 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002780 OpenMPScheduleTy ScheduleKind;
2781 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002782 CGOpenMPRuntime::StaticRTInput StaticInit(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002783 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(CGF),
2784 LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF));
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002785 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002786 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002787 // UB = min(UB, GlobalUB);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002788 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc());
Alexey Bataevddf3db92018-04-13 17:31:06 +00002789 llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect(
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002790 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2791 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2792 // IV = LB;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002793 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002794 // while (idx <= UB) { BODY; ++idx; }
2795 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2796 [](CodeGenFunction &) {});
2797 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002798 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002799 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00002800 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002801 };
2802 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002803 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002804 // Emit post-update of the reduction variables if IsLastIter != 0.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002805 emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) {
2806 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002807 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataevddf3db92018-04-13 17:31:06 +00002808 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002809
2810 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2811 if (HasLastprivates)
2812 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002813 S, /*NoFinals=*/false,
2814 CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002815 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002816 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002817
2818 bool HasCancel = false;
2819 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2820 HasCancel = OSD->hasCancel();
2821 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2822 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002823 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002824 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2825 HasCancel);
2826 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2827 // clause. Otherwise the barrier will be generated by the codegen for the
2828 // directive.
2829 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002830 // Emit implicit barrier to synchronize threads and avoid data races on
2831 // initialization of firstprivate variables.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002832 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002833 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002834 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002835}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002836
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002837void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002838 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002839 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002840 EmitSections(S);
2841 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002842 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002843 if (!S.getSingleClause<OMPNowaitClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002844 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
Alexey Bataev3392d762016-02-16 11:18:12 +00002845 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002846 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002847}
2848
2849void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002850 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002851 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002852 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002853 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002854 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2855 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002856}
2857
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002858void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002859 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002860 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002861 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002862 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002863 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002864 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002865 // Build a list of copyprivate variables along with helper expressions
2866 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002867 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002868 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002869 DestExprs.append(C->destination_exprs().begin(),
2870 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002871 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002872 AssignmentOps.append(C->assignment_ops().begin(),
2873 C->assignment_ops().end());
2874 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002875 // Emit code for 'single' region along with 'copyprivate' clauses
2876 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2877 Action.Enter(CGF);
2878 OMPPrivateScope SingleScope(CGF);
2879 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2880 CGF.EmitOMPPrivateClause(S, SingleScope);
2881 (void)SingleScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00002882 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002883 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002884 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002885 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002886 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(),
Alexey Bataev3392d762016-02-16 11:18:12 +00002887 CopyprivateVars, DestExprs,
2888 SrcExprs, AssignmentOps);
2889 }
2890 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2891 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002892 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002893 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002894 *this, S.getBeginLoc(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002895 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002896 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002897}
2898
Alexey Bataev8d690652014-12-04 07:23:53 +00002899void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002900 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2901 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002902 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002903 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002904 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002905 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
Alexander Musman80c22892014-07-17 08:54:58 +00002906}
2907
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002908void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002909 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2910 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002911 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002912 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00002913 const Expr *Hint = nullptr;
2914 if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
Alexey Bataevfc57d162015-12-15 10:55:09 +00002915 Hint = HintClause->getHint();
Alexey Bataev475a7442018-01-12 19:39:11 +00002916 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002917 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2918 S.getDirectiveName().getAsString(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002919 CodeGen, S.getBeginLoc(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002920}
2921
Alexey Bataev671605e2015-04-13 05:28:11 +00002922void CodeGenFunction::EmitOMPParallelForDirective(
2923 const OMPParallelForDirective &S) {
2924 // Emit directive as a combined directive that consists of two implicit
2925 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00002926 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2927 Action.Enter(CGF);
Alexey Bataev957d8562016-11-17 15:12:05 +00002928 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002929 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2930 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002931 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002932 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2933 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002934}
2935
Alexander Musmane4e893b2014-09-23 09:33:00 +00002936void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002937 const OMPParallelForSimdDirective &S) {
2938 // Emit directive as a combined directive that consists of two implicit
2939 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00002940 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2941 Action.Enter(CGF);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002942 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2943 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002944 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002945 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2946 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002947}
2948
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002949void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002950 const OMPParallelSectionsDirective &S) {
2951 // Emit directive as a combined directive that consists of two implicit
2952 // directives: 'parallel' with 'sections' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00002953 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2954 Action.Enter(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002955 CGF.EmitSections(S);
2956 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002957 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2958 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002959}
2960
Alexey Bataev475a7442018-01-12 19:39:11 +00002961void CodeGenFunction::EmitOMPTaskBasedDirective(
2962 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
2963 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
2964 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002965 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00002966 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002967 auto I = CS->getCapturedDecl()->param_begin();
2968 auto PartId = std::next(I);
2969 auto TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002970 // Check if the task is final
2971 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2972 // If the condition constant folds and can be elided, try to avoid emitting
2973 // the condition and the dead arm of the if/else.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002974 const Expr *Cond = Clause->getCondition();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002975 bool CondConstant;
2976 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2977 Data.Final.setInt(CondConstant);
2978 else
2979 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2980 } else {
2981 // By default the task is not final.
2982 Data.Final.setInt(/*IntVal=*/false);
2983 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002984 // Check if the task has 'priority' clause.
2985 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002986 const Expr *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002987 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002988 Data.Priority.setPointer(EmitScalarConversion(
2989 EmitScalarExpr(Prio), Prio->getType(),
2990 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2991 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002992 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002993 // The first function argument for tasks is a thread id, the second one is a
2994 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002995 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2996 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002997 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002998 auto IRef = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002999 for (const Expr *IInit : C->private_copies()) {
3000 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003001 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003002 Data.PrivateVars.push_back(*IRef);
3003 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003004 }
3005 ++IRef;
3006 }
3007 }
3008 EmittedAsPrivate.clear();
3009 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003010 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003011 auto IRef = C->varlist_begin();
3012 auto IElemInitRef = C->inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003013 for (const Expr *IInit : C->private_copies()) {
3014 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003015 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003016 Data.FirstprivateVars.push_back(*IRef);
3017 Data.FirstprivateCopies.push_back(IInit);
3018 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003019 }
Richard Trieucc3949d2016-02-18 22:34:54 +00003020 ++IRef;
3021 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003022 }
3023 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003024 // Get list of lastprivate variables (for taskloops).
3025 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
3026 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
3027 auto IRef = C->varlist_begin();
3028 auto ID = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003029 for (const Expr *IInit : C->private_copies()) {
3030 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003031 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
3032 Data.LastprivateVars.push_back(*IRef);
3033 Data.LastprivateCopies.push_back(IInit);
3034 }
3035 LastprivateDstsOrigs.insert(
3036 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
3037 cast<DeclRefExpr>(*IRef)});
3038 ++IRef;
3039 ++ID;
3040 }
3041 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003042 SmallVector<const Expr *, 4> LHSs;
3043 SmallVector<const Expr *, 4> RHSs;
3044 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
3045 auto IPriv = C->privates().begin();
3046 auto IRed = C->reduction_ops().begin();
3047 auto ILHS = C->lhs_exprs().begin();
3048 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003049 for (const Expr *Ref : C->varlists()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003050 Data.ReductionVars.emplace_back(Ref);
3051 Data.ReductionCopies.emplace_back(*IPriv);
3052 Data.ReductionOps.emplace_back(*IRed);
3053 LHSs.emplace_back(*ILHS);
3054 RHSs.emplace_back(*IRHS);
3055 std::advance(IPriv, 1);
3056 std::advance(IRed, 1);
3057 std::advance(ILHS, 1);
3058 std::advance(IRHS, 1);
3059 }
3060 }
3061 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003062 *this, S.getBeginLoc(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003063 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00003064 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
Alexey Bataevddf3db92018-04-13 17:31:06 +00003065 for (const Expr *IRef : C->varlists())
Alexey Bataev43a919f2018-04-13 17:48:43 +00003066 Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
Alexey Bataev475a7442018-01-12 19:39:11 +00003067 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
3068 CapturedRegion](CodeGenFunction &CGF,
3069 PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003070 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00003071 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003072 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
3073 !Data.LastprivateVars.empty()) {
James Y Knight9871db02019-02-05 16:42:33 +00003074 llvm::FunctionType *CopyFnTy = llvm::FunctionType::get(
3075 CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true);
Alexey Bataev3c595a62017-08-14 15:01:03 +00003076 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00003077 llvm::Value *CopyFn = CGF.Builder.CreateLoad(
3078 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
3079 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
3080 CS->getCapturedDecl()->getParam(PrivatesParam)));
Alexey Bataev48591dd2016-04-20 04:01:36 +00003081 // Map privates.
3082 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3083 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3084 CallArgs.push_back(PrivatesPtr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003085 for (const Expr *E : Data.PrivateVars) {
3086 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev48591dd2016-04-20 04:01:36 +00003087 Address PrivatePtr = CGF.CreateMemTemp(
3088 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003089 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003090 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003091 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003092 for (const Expr *E : Data.FirstprivateVars) {
3093 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev48591dd2016-04-20 04:01:36 +00003094 Address PrivatePtr =
3095 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3096 ".firstpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003097 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003098 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003099 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003100 for (const Expr *E : Data.LastprivateVars) {
3101 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003102 Address PrivatePtr =
3103 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3104 ".lastpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003105 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003106 CallArgs.push_back(PrivatePtr.getPointer());
3107 }
James Y Knight9871db02019-02-05 16:42:33 +00003108 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3109 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003110 for (const auto &Pair : LastprivateDstsOrigs) {
3111 const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003112 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(OrigVD),
3113 /*RefersToEnclosingVariableOrCapture=*/
3114 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
3115 Pair.second->getType(), VK_LValue,
3116 Pair.second->getExprLoc());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003117 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003118 return CGF.EmitLValue(&DRE).getAddress(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003119 });
3120 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003121 for (const auto &Pair : PrivatePtrs) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003122 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3123 CGF.getContext().getDeclAlign(Pair.first));
3124 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3125 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003126 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003127 if (Data.Reductions) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003128 OMPLexicalScope LexScope(CGF, S, CapturedRegion);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003129 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
3130 Data.ReductionOps);
3131 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
3132 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
3133 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
3134 RedCG.emitSharedLValue(CGF, Cnt);
3135 RedCG.emitAggregateType(CGF, Cnt);
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003136 // FIXME: This must removed once the runtime library is fixed.
3137 // Emit required threadprivate variables for
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003138 // initializer/combiner/finalizer.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003139 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003140 RedCG, Cnt);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003141 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003142 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003143 Replacement =
3144 Address(CGF.EmitScalarConversion(
3145 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
3146 CGF.getContext().getPointerType(
3147 Data.ReductionCopies[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003148 Data.ReductionCopies[Cnt]->getExprLoc()),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003149 Replacement.getAlignment());
3150 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
3151 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
3152 [Replacement]() { return Replacement; });
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003153 }
3154 }
Alexey Bataev88202be2017-07-27 13:20:36 +00003155 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00003156 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00003157 SmallVector<const Expr *, 4> InRedVars;
3158 SmallVector<const Expr *, 4> InRedPrivs;
3159 SmallVector<const Expr *, 4> InRedOps;
3160 SmallVector<const Expr *, 4> TaskgroupDescriptors;
3161 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
3162 auto IPriv = C->privates().begin();
3163 auto IRed = C->reduction_ops().begin();
3164 auto ITD = C->taskgroup_descriptors().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003165 for (const Expr *Ref : C->varlists()) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003166 InRedVars.emplace_back(Ref);
3167 InRedPrivs.emplace_back(*IPriv);
3168 InRedOps.emplace_back(*IRed);
3169 TaskgroupDescriptors.emplace_back(*ITD);
3170 std::advance(IPriv, 1);
3171 std::advance(IRed, 1);
3172 std::advance(ITD, 1);
3173 }
3174 }
3175 // Privatize in_reduction items here, because taskgroup descriptors must be
3176 // privatized earlier.
3177 OMPPrivateScope InRedScope(CGF);
3178 if (!InRedVars.empty()) {
3179 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
3180 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
3181 RedCG.emitSharedLValue(CGF, Cnt);
3182 RedCG.emitAggregateType(CGF, Cnt);
3183 // The taskgroup descriptor variable is always implicit firstprivate and
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003184 // privatized already during processing of the firstprivates.
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003185 // FIXME: This must removed once the runtime library is fixed.
3186 // Emit required threadprivate variables for
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003187 // initializer/combiner/finalizer.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003188 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003189 RedCG, Cnt);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003190 llvm::Value *ReductionsPtr =
3191 CGF.EmitLoadOfScalar(CGF.EmitLValue(TaskgroupDescriptors[Cnt]),
3192 TaskgroupDescriptors[Cnt]->getExprLoc());
Alexey Bataev88202be2017-07-27 13:20:36 +00003193 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003194 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
Alexey Bataev88202be2017-07-27 13:20:36 +00003195 Replacement = Address(
3196 CGF.EmitScalarConversion(
3197 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
3198 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003199 InRedPrivs[Cnt]->getExprLoc()),
Alexey Bataev88202be2017-07-27 13:20:36 +00003200 Replacement.getAlignment());
3201 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
3202 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
3203 [Replacement]() { return Replacement; });
Alexey Bataev88202be2017-07-27 13:20:36 +00003204 }
3205 }
3206 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00003207
3208 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00003209 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003210 };
James Y Knight9871db02019-02-05 16:42:33 +00003211 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00003212 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
3213 Data.NumberOfParts);
Alexey Bataev5bbcead2019-10-14 17:17:41 +00003214 OMPLexicalScope Scope(*this, S, llvm::None,
3215 !isOpenMPParallelDirective(S.getDirectiveKind()));
Alexey Bataev7292c292016-04-25 12:22:29 +00003216 TaskGen(*this, OutlinedFn, Data);
3217}
3218
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003219static ImplicitParamDecl *
3220createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003221 QualType Ty, CapturedDecl *CD,
3222 SourceLocation Loc) {
3223 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3224 ImplicitParamDecl::Other);
3225 auto *OrigRef = DeclRefExpr::Create(
3226 C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
3227 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
3228 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3229 ImplicitParamDecl::Other);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003230 auto *PrivateRef = DeclRefExpr::Create(
3231 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003232 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003233 QualType ElemType = C.getBaseElementType(Ty);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003234 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
3235 ImplicitParamDecl::Other);
3236 auto *InitRef = DeclRefExpr::Create(
3237 C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
3238 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003239 PrivateVD->setInitStyle(VarDecl::CInit);
3240 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
3241 InitRef, /*BasePath=*/nullptr,
3242 VK_RValue));
3243 Data.FirstprivateVars.emplace_back(OrigRef);
3244 Data.FirstprivateCopies.emplace_back(PrivateRef);
3245 Data.FirstprivateInits.emplace_back(InitRef);
3246 return OrigVD;
3247}
3248
3249void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
3250 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
3251 OMPTargetDataInfo &InputInfo) {
3252 // Emit outlined function for task construct.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003253 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
3254 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3255 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3256 auto I = CS->getCapturedDecl()->param_begin();
3257 auto PartId = std::next(I);
3258 auto TaskT = std::next(I, 4);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003259 OMPTaskDataTy Data;
3260 // The task is not final.
3261 Data.Final.setInt(/*IntVal=*/false);
3262 // Get list of firstprivate variables.
3263 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3264 auto IRef = C->varlist_begin();
3265 auto IElemInitRef = C->inits().begin();
3266 for (auto *IInit : C->private_copies()) {
3267 Data.FirstprivateVars.push_back(*IRef);
3268 Data.FirstprivateCopies.push_back(IInit);
3269 Data.FirstprivateInits.push_back(*IElemInitRef);
3270 ++IRef;
3271 ++IElemInitRef;
3272 }
3273 }
3274 OMPPrivateScope TargetScope(*this);
3275 VarDecl *BPVD = nullptr;
3276 VarDecl *PVD = nullptr;
3277 VarDecl *SVD = nullptr;
3278 if (InputInfo.NumberOfTargetItems > 0) {
3279 auto *CD = CapturedDecl::Create(
3280 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
3281 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
3282 QualType BaseAndPointersType = getContext().getConstantArrayType(
Richard Smith772e2662019-10-04 01:25:59 +00003283 getContext().VoidPtrTy, ArrSize, nullptr, ArrayType::Normal,
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003284 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003285 BPVD = createImplicitFirstprivateForType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003286 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003287 PVD = createImplicitFirstprivateForType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003288 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003289 QualType SizesType = getContext().getConstantArrayType(
Alexey Bataeva90fc662019-06-25 16:00:43 +00003290 getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1),
Richard Smith772e2662019-10-04 01:25:59 +00003291 ArrSize, nullptr, ArrayType::Normal,
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003292 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003293 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003294 S.getBeginLoc());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003295 TargetScope.addPrivate(
3296 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
3297 TargetScope.addPrivate(PVD,
3298 [&InputInfo]() { return InputInfo.PointersArray; });
3299 TargetScope.addPrivate(SVD,
3300 [&InputInfo]() { return InputInfo.SizesArray; });
3301 }
3302 (void)TargetScope.Privatize();
3303 // Build list of dependences.
3304 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
Alexey Bataevddf3db92018-04-13 17:31:06 +00003305 for (const Expr *IRef : C->varlists())
Alexey Bataev43a919f2018-04-13 17:48:43 +00003306 Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003307 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3308 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3309 // Set proper addresses for generated private copies.
3310 OMPPrivateScope Scope(CGF);
3311 if (!Data.FirstprivateVars.empty()) {
James Y Knight9871db02019-02-05 16:42:33 +00003312 llvm::FunctionType *CopyFnTy = llvm::FunctionType::get(
3313 CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003314 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00003315 llvm::Value *CopyFn = CGF.Builder.CreateLoad(
3316 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
3317 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
3318 CS->getCapturedDecl()->getParam(PrivatesParam)));
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003319 // Map privates.
3320 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3321 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3322 CallArgs.push_back(PrivatesPtr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003323 for (const Expr *E : Data.FirstprivateVars) {
3324 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003325 Address PrivatePtr =
3326 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3327 ".firstpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003328 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003329 CallArgs.push_back(PrivatePtr.getPointer());
3330 }
James Y Knight9871db02019-02-05 16:42:33 +00003331 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3332 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003333 for (const auto &Pair : PrivatePtrs) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003334 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3335 CGF.getContext().getDeclAlign(Pair.first));
3336 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3337 }
3338 }
3339 // Privatize all private variables except for in_reduction items.
3340 (void)Scope.Privatize();
Alexey Bataev8451efa2018-01-15 19:06:12 +00003341 if (InputInfo.NumberOfTargetItems > 0) {
3342 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
James Y Knight751fe282019-02-09 22:22:28 +00003343 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003344 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
James Y Knight751fe282019-02-09 22:22:28 +00003345 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003346 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
James Y Knight751fe282019-02-09 22:22:28 +00003347 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003348 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003349
3350 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003351 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003352 BodyGen(CGF);
3353 };
James Y Knight9871db02019-02-05 16:42:33 +00003354 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003355 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3356 Data.NumberOfParts);
3357 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3358 IntegerLiteral IfCond(getContext(), TrueOrFalse,
3359 getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3360 SourceLocation());
3361
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003362 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn,
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003363 SharedsTy, CapturedStruct, &IfCond, Data);
3364}
3365
Alexey Bataev7292c292016-04-25 12:22:29 +00003366void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3367 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00003368 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003369 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3370 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00003371 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00003372 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3373 if (C->getNameModifier() == OMPD_unknown ||
3374 C->getNameModifier() == OMPD_task) {
3375 IfCond = C->getCondition();
3376 break;
3377 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003378 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003379
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003380 OMPTaskDataTy Data;
3381 // Check if we should emit tied or untied task.
3382 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003383 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3384 CGF.EmitStmt(CS->getCapturedStmt());
3385 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003386 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
James Y Knight9871db02019-02-05 16:42:33 +00003387 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003388 const OMPTaskDataTy &Data) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003389 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003390 SharedsTy, CapturedStruct, IfCond,
3391 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003392 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003393 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003394}
3395
Alexey Bataev9f797f32015-02-05 05:57:51 +00003396void CodeGenFunction::EmitOMPTaskyieldDirective(
3397 const OMPTaskyieldDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003398 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc());
Alexey Bataev68446b72014-07-18 07:47:19 +00003399}
3400
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003401void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003402 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003403}
3404
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003405void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003406 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc());
Alexey Bataev2df347a2014-07-18 10:17:07 +00003407}
3408
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003409void CodeGenFunction::EmitOMPTaskgroupDirective(
3410 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003411 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3412 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003413 if (const Expr *E = S.getReductionRef()) {
3414 SmallVector<const Expr *, 4> LHSs;
3415 SmallVector<const Expr *, 4> RHSs;
3416 OMPTaskDataTy Data;
3417 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3418 auto IPriv = C->privates().begin();
3419 auto IRed = C->reduction_ops().begin();
3420 auto ILHS = C->lhs_exprs().begin();
3421 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003422 for (const Expr *Ref : C->varlists()) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003423 Data.ReductionVars.emplace_back(Ref);
3424 Data.ReductionCopies.emplace_back(*IPriv);
3425 Data.ReductionOps.emplace_back(*IRed);
3426 LHSs.emplace_back(*ILHS);
3427 RHSs.emplace_back(*IRHS);
3428 std::advance(IPriv, 1);
3429 std::advance(IRed, 1);
3430 std::advance(ILHS, 1);
3431 std::advance(IRHS, 1);
3432 }
3433 }
3434 llvm::Value *ReductionDesc =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003435 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(),
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003436 LHSs, RHSs, Data);
3437 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3438 CGF.EmitVarDecl(*VD);
3439 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3440 /*Volatile=*/false, E->getType());
3441 }
Alexey Bataev475a7442018-01-12 19:39:11 +00003442 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003443 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003444 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003445 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003446}
3447
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003448void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003449 CGM.getOpenMPRuntime().emitFlush(
3450 *this,
3451 [&S]() -> ArrayRef<const Expr *> {
3452 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>())
3453 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3454 FlushClause->varlist_end());
3455 return llvm::None;
3456 }(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003457 S.getBeginLoc());
Alexey Bataev6125da92014-07-21 11:26:11 +00003458}
3459
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003460void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3461 const CodeGenLoopTy &CodeGenLoop,
3462 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003463 // Emit the loop iteration variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003464 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3465 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003466 EmitVarDecl(*IVDecl);
3467
3468 // Emit the iterations count variable.
3469 // If it is not a variable, Sema decided to calculate iterations count on each
3470 // iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00003471 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003472 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3473 // Emit calculation of the iterations count.
3474 EmitIgnoredExpr(S.getCalcLastIteration());
3475 }
3476
Alexey Bataevddf3db92018-04-13 17:31:06 +00003477 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003478
Carlo Bertolli962bb802017-01-03 18:24:42 +00003479 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003480 // Check pre-condition.
3481 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003482 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003483 // Skip the entire loop if we don't meet the precondition.
3484 // If the condition constant folds and can be elided, avoid emitting the
3485 // whole loop.
3486 bool CondConstant;
3487 llvm::BasicBlock *ContBlock = nullptr;
3488 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3489 if (!CondConstant)
3490 return;
3491 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003492 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003493 ContBlock = createBasicBlock("omp.precond.end");
3494 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3495 getProfileCount(&S));
3496 EmitBlock(ThenBlock);
3497 incrementProfileCounter(&S);
3498 }
3499
Alexey Bataev617db5f2017-12-04 15:38:33 +00003500 emitAlignedClause(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003501 // Emit 'then' code.
3502 {
3503 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003504
3505 LValue LB = EmitOMPHelperVar(
3506 *this, cast<DeclRefExpr>(
3507 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3508 ? S.getCombinedLowerBoundVariable()
3509 : S.getLowerBoundVariable())));
3510 LValue UB = EmitOMPHelperVar(
3511 *this, cast<DeclRefExpr>(
3512 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3513 ? S.getCombinedUpperBoundVariable()
3514 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003515 LValue ST =
3516 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3517 LValue IL =
3518 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3519
3520 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003521 if (EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003522 // Emit implicit barrier to synchronize threads and avoid data races
3523 // on initialization of firstprivate variables and post-update of
Carlo Bertolli962bb802017-01-03 18:24:42 +00003524 // lastprivate variables.
3525 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003526 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev617db5f2017-12-04 15:38:33 +00003527 /*ForceSimpleCall=*/true);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003528 }
3529 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev617db5f2017-12-04 15:38:33 +00003530 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
Alexey Bataev999277a2017-12-06 14:31:09 +00003531 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3532 !isOpenMPTeamsDirective(S.getDirectiveKind()))
Alexey Bataev617db5f2017-12-04 15:38:33 +00003533 EmitOMPReductionClauseInit(S, LoopScope);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003534 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003535 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003536 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00003537 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
3538 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003539
3540 // Detect the distribute schedule kind and chunk.
3541 llvm::Value *Chunk = nullptr;
3542 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003543 if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003544 ScheduleKind = C->getDistScheduleKind();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003545 if (const Expr *Ch = C->getChunkSize()) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003546 Chunk = EmitScalarExpr(Ch);
3547 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
Alexey Bataev617db5f2017-12-04 15:38:33 +00003548 S.getIterationVariable()->getType(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003549 S.getBeginLoc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003550 }
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00003551 } else {
3552 // Default behaviour for dist_schedule clause.
3553 CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk(
3554 *this, S, ScheduleKind, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003555 }
3556 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3557 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3558
3559 // OpenMP [2.10.8, distribute Construct, Description]
3560 // If dist_schedule is specified, kind must be static. If specified,
3561 // iterations are divided into chunks of size chunk_size, chunks are
3562 // assigned to the teams of the league in a round-robin fashion in the
3563 // order of the team number. When no chunk_size is specified, the
3564 // iteration space is divided into chunks that are approximately equal
3565 // in size, and at most one chunk is distributed to each team of the
3566 // league. The size of the chunks is unspecified in this case.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003567 bool StaticChunked = RT.isStaticChunked(
3568 ScheduleKind, /* Chunked */ Chunk != nullptr) &&
3569 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003570 if (RT.isStaticNonchunked(ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003571 /* Chunked */ Chunk != nullptr) ||
3572 StaticChunked) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003573 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3574 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003575 CGOpenMPRuntime::StaticRTInput StaticInit(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003576 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(*this),
3577 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003578 StaticChunked ? Chunk : nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003579 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003580 StaticInit);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003581 JumpDest LoopExit =
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003582 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3583 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003584 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3585 ? S.getCombinedEnsureUpperBound()
3586 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003587 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003588 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3589 ? S.getCombinedInit()
3590 : S.getInit());
3591
Alexey Bataevddf3db92018-04-13 17:31:06 +00003592 const Expr *Cond =
3593 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3594 ? S.getCombinedCond()
3595 : S.getCond();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003596
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003597 if (StaticChunked)
3598 Cond = S.getCombinedDistCond();
3599
3600 // For static unchunked schedules generate:
3601 //
3602 // 1. For distribute alone, codegen
3603 // while (idx <= UB) {
3604 // BODY;
3605 // ++idx;
3606 // }
3607 //
3608 // 2. When combined with 'for' (e.g. as in 'distribute parallel for')
3609 // while (idx <= UB) {
3610 // <CodeGen rest of pragma>(LB, UB);
3611 // idx += ST;
3612 // }
3613 //
3614 // For static chunk one schedule generate:
3615 //
3616 // while (IV <= GlobalUB) {
3617 // <CodeGen rest of pragma>(LB, UB);
3618 // LB += ST;
3619 // UB += ST;
3620 // UB = min(UB, GlobalUB);
3621 // IV = LB;
3622 // }
3623 //
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003624 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3625 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3626 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003627 },
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003628 [&S, StaticChunked](CodeGenFunction &CGF) {
3629 if (StaticChunked) {
3630 CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound());
3631 CGF.EmitIgnoredExpr(S.getCombinedNextUpperBound());
3632 CGF.EmitIgnoredExpr(S.getCombinedEnsureUpperBound());
3633 CGF.EmitIgnoredExpr(S.getCombinedInit());
3634 }
3635 });
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003636 EmitBlock(LoopExit.getBlock());
3637 // Tell the runtime we are done.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003638 RT.emitForStaticFinish(*this, S.getBeginLoc(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003639 } else {
3640 // Emit the outer loop, which requests its work chunk [LB..UB] from
3641 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003642 const OMPLoopArguments LoopArguments = {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003643 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
3644 IL.getAddress(*this), Chunk};
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003645 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3646 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003647 }
Alexey Bataev617db5f2017-12-04 15:38:33 +00003648 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003649 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003650 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003651 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataev617db5f2017-12-04 15:38:33 +00003652 });
3653 }
Carlo Bertollibeda2142018-02-22 19:38:14 +00003654 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
3655 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3656 !isOpenMPTeamsDirective(S.getDirectiveKind())) {
Jonas Hahnfeld5aaaece2018-10-02 19:12:47 +00003657 EmitOMPReductionClauseFinal(S, OMPD_simd);
Carlo Bertollibeda2142018-02-22 19:38:14 +00003658 // Emit post-update of the reduction variables if IsLastIter != 0.
3659 emitPostUpdateForReductionClause(
Alexey Bataevddf3db92018-04-13 17:31:06 +00003660 *this, S, [IL, &S](CodeGenFunction &CGF) {
Carlo Bertollibeda2142018-02-22 19:38:14 +00003661 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003662 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Carlo Bertollibeda2142018-02-22 19:38:14 +00003663 });
Alexey Bataev617db5f2017-12-04 15:38:33 +00003664 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00003665 // Emit final copy of the lastprivate variables if IsLastIter != 0.
Alexey Bataev617db5f2017-12-04 15:38:33 +00003666 if (HasLastprivateClause) {
Carlo Bertolli962bb802017-01-03 18:24:42 +00003667 EmitOMPLastprivateClauseFinal(
3668 S, /*NoFinals=*/false,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003669 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexey Bataev617db5f2017-12-04 15:38:33 +00003670 }
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003671 }
3672
3673 // We're now done with the loop, so jump to the continuation block.
3674 if (ContBlock) {
3675 EmitBranch(ContBlock);
3676 EmitBlock(ContBlock, true);
3677 }
3678 }
3679}
3680
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003681void CodeGenFunction::EmitOMPDistributeDirective(
3682 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003683 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003684 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003685 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003686 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev10a54312017-11-27 16:54:08 +00003687 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003688}
3689
Alexey Bataev5f600d62015-09-29 03:48:57 +00003690static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3691 const CapturedStmt *S) {
3692 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3693 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3694 CGF.CapturedStmtInfo = &CapStmtInfo;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003695 llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003696 Fn->setDoesNotRecurse();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003697 return Fn;
3698}
3699
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003700void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003701 if (S.hasClausesOfKind<OMPDependClause>()) {
3702 assert(!S.getAssociatedStmt() &&
3703 "No associated statement must be in ordered depend construct.");
Alexey Bataev8b427062016-05-25 12:36:08 +00003704 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3705 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003706 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003707 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003708 const auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003709 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3710 PrePostActionTy &Action) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003711 const CapturedStmt *CS = S.getInnermostCapturedStmt();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003712 if (C) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003713 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3714 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003715 llvm::Function *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003716 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
Alexey Bataev3c595a62017-08-14 15:01:03 +00003717 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003718 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003719 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003720 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev5f600d62015-09-29 03:48:57 +00003721 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003722 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003723 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003724 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003725}
3726
Alexey Bataevb57056f2015-01-22 06:17:56 +00003727static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003728 QualType SrcType, QualType DestType,
3729 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003730 assert(CGF.hasScalarEvaluationKind(DestType) &&
3731 "DestType must have scalar evaluation kind.");
3732 assert(!Val.isAggregate() && "Must be a scalar or complex.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003733 return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3734 DestType, Loc)
3735 : CGF.EmitComplexToScalarConversion(
3736 Val.getComplexVal(), SrcType, DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003737}
3738
3739static CodeGenFunction::ComplexPairTy
3740convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003741 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003742 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3743 "DestType must have complex evaluation kind.");
3744 CodeGenFunction::ComplexPairTy ComplexVal;
3745 if (Val.isScalar()) {
3746 // Convert the input element to the element type of the complex.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003747 QualType DestElementType =
3748 DestType->castAs<ComplexType>()->getElementType();
3749 llvm::Value *ScalarVal = CGF.EmitScalarConversion(
3750 Val.getScalarVal(), SrcType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003751 ComplexVal = CodeGenFunction::ComplexPairTy(
3752 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3753 } else {
3754 assert(Val.isComplex() && "Must be a scalar or complex.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003755 QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3756 QualType DestElementType =
3757 DestType->castAs<ComplexType>()->getElementType();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003758 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003759 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003760 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003761 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003762 }
3763 return ComplexVal;
3764}
3765
Alexey Bataev5e018f92015-04-23 06:35:10 +00003766static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3767 LValue LVal, RValue RVal) {
3768 if (LVal.isGlobalReg()) {
3769 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3770 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003771 CGF.EmitAtomicStore(RVal, LVal,
3772 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3773 : llvm::AtomicOrdering::Monotonic,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003774 LVal.isVolatile(), /*isInit=*/false);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003775 }
3776}
3777
Alexey Bataev8524d152016-01-21 12:35:58 +00003778void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3779 QualType RValTy, SourceLocation Loc) {
3780 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003781 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003782 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3783 *this, RVal, RValTy, LVal.getType(), Loc)),
3784 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003785 break;
3786 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003787 EmitStoreOfComplex(
3788 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003789 /*isInit=*/false);
3790 break;
3791 case TEK_Aggregate:
3792 llvm_unreachable("Must be a scalar or complex.");
3793 }
3794}
3795
Alexey Bataevddf3db92018-04-13 17:31:06 +00003796static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb57056f2015-01-22 06:17:56 +00003797 const Expr *X, const Expr *V,
3798 SourceLocation Loc) {
3799 // v = x;
3800 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3801 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3802 LValue XLValue = CGF.EmitLValue(X);
3803 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003804 RValue Res = XLValue.isGlobalReg()
3805 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003806 : CGF.EmitAtomicLoad(
3807 XLValue, Loc,
3808 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3809 : llvm::AtomicOrdering::Monotonic,
3810 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003811 // OpenMP, 2.12.6, atomic Construct
3812 // Any atomic construct with a seq_cst clause forces the atomically
3813 // performed operation to include an implicit flush operation without a
3814 // list.
3815 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003816 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003817 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003818}
3819
Alexey Bataevddf3db92018-04-13 17:31:06 +00003820static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb8329262015-02-27 06:33:30 +00003821 const Expr *X, const Expr *E,
3822 SourceLocation Loc) {
3823 // x = expr;
3824 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003825 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003826 // OpenMP, 2.12.6, atomic Construct
3827 // Any atomic construct with a seq_cst clause forces the atomically
3828 // performed operation to include an implicit flush operation without a
3829 // list.
3830 if (IsSeqCst)
3831 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3832}
3833
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003834static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3835 RValue Update,
3836 BinaryOperatorKind BO,
3837 llvm::AtomicOrdering AO,
3838 bool IsXLHSInRHSPart) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003839 ASTContext &Context = CGF.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003840 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003841 // expression is simple and atomic is allowed for the given type for the
3842 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003843 if (BO == BO_Comma || !Update.isScalar() ||
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003844 !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() ||
3845 (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3846 (Update.getScalarVal()->getType() !=
3847 X.getAddress(CGF).getElementType())) ||
3848 !X.getAddress(CGF).getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003849 !Context.getTargetInfo().hasBuiltinAtomic(
3850 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003851 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003852
3853 llvm::AtomicRMWInst::BinOp RMWOp;
3854 switch (BO) {
3855 case BO_Add:
3856 RMWOp = llvm::AtomicRMWInst::Add;
3857 break;
3858 case BO_Sub:
3859 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003860 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003861 RMWOp = llvm::AtomicRMWInst::Sub;
3862 break;
3863 case BO_And:
3864 RMWOp = llvm::AtomicRMWInst::And;
3865 break;
3866 case BO_Or:
3867 RMWOp = llvm::AtomicRMWInst::Or;
3868 break;
3869 case BO_Xor:
3870 RMWOp = llvm::AtomicRMWInst::Xor;
3871 break;
3872 case BO_LT:
3873 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3874 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3875 : llvm::AtomicRMWInst::Max)
3876 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3877 : llvm::AtomicRMWInst::UMax);
3878 break;
3879 case BO_GT:
3880 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3881 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3882 : llvm::AtomicRMWInst::Min)
3883 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3884 : llvm::AtomicRMWInst::UMin);
3885 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003886 case BO_Assign:
3887 RMWOp = llvm::AtomicRMWInst::Xchg;
3888 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003889 case BO_Mul:
3890 case BO_Div:
3891 case BO_Rem:
3892 case BO_Shl:
3893 case BO_Shr:
3894 case BO_LAnd:
3895 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003896 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003897 case BO_PtrMemD:
3898 case BO_PtrMemI:
3899 case BO_LE:
3900 case BO_GE:
3901 case BO_EQ:
3902 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00003903 case BO_Cmp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003904 case BO_AddAssign:
3905 case BO_SubAssign:
3906 case BO_AndAssign:
3907 case BO_OrAssign:
3908 case BO_XorAssign:
3909 case BO_MulAssign:
3910 case BO_DivAssign:
3911 case BO_RemAssign:
3912 case BO_ShlAssign:
3913 case BO_ShrAssign:
3914 case BO_Comma:
3915 llvm_unreachable("Unsupported atomic update operation");
3916 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003917 llvm::Value *UpdateVal = Update.getScalarVal();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003918 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3919 UpdateVal = CGF.Builder.CreateIntCast(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003920 IC, X.getAddress(CGF).getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003921 X.getType()->hasSignedIntegerRepresentation());
3922 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003923 llvm::Value *Res =
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003924 CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(CGF), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003925 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003926}
3927
Alexey Bataev5e018f92015-04-23 06:35:10 +00003928std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003929 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3930 llvm::AtomicOrdering AO, SourceLocation Loc,
Alexey Bataevddf3db92018-04-13 17:31:06 +00003931 const llvm::function_ref<RValue(RValue)> CommonGen) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003932 // Update expressions are allowed to have the following forms:
3933 // x binop= expr; -> xrval + expr;
3934 // x++, ++x -> xrval + 1;
3935 // x--, --x -> xrval - 1;
3936 // x = x binop expr; -> xrval binop expr
3937 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003938 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3939 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003940 if (X.isGlobalReg()) {
3941 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3942 // 'xrval'.
3943 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3944 } else {
3945 // Perform compare-and-swap procedure.
3946 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003947 }
3948 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003949 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003950}
3951
Alexey Bataevddf3db92018-04-13 17:31:06 +00003952static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb4505a72015-03-30 05:20:59 +00003953 const Expr *X, const Expr *E,
3954 const Expr *UE, bool IsXLHSInRHSPart,
3955 SourceLocation Loc) {
3956 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3957 "Update expr in 'atomic update' must be a binary operator.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003958 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003959 // Update expressions are allowed to have the following forms:
3960 // x binop= expr; -> xrval + expr;
3961 // x++, ++x -> xrval + 1;
3962 // x--, --x -> xrval - 1;
3963 // x = x binop expr; -> xrval binop expr
3964 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003965 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003966 LValue XLValue = CGF.EmitLValue(X);
3967 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003968 llvm::AtomicOrdering AO = IsSeqCst
3969 ? llvm::AtomicOrdering::SequentiallyConsistent
3970 : llvm::AtomicOrdering::Monotonic;
3971 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3972 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3973 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3974 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3975 auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) {
3976 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3977 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3978 return CGF.EmitAnyExpr(UE);
3979 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003980 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3981 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3982 // OpenMP, 2.12.6, atomic Construct
3983 // Any atomic construct with a seq_cst clause forces the atomically
3984 // performed operation to include an implicit flush operation without a
3985 // list.
3986 if (IsSeqCst)
3987 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3988}
3989
3990static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003991 QualType SourceType, QualType ResType,
3992 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003993 switch (CGF.getEvaluationKind(ResType)) {
3994 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003995 return RValue::get(
3996 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003997 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003998 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003999 return RValue::getComplex(Res.first, Res.second);
4000 }
4001 case TEK_Aggregate:
4002 break;
4003 }
4004 llvm_unreachable("Must be a scalar or complex.");
4005}
4006
Alexey Bataevddf3db92018-04-13 17:31:06 +00004007static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataev5e018f92015-04-23 06:35:10 +00004008 bool IsPostfixUpdate, const Expr *V,
4009 const Expr *X, const Expr *E,
4010 const Expr *UE, bool IsXLHSInRHSPart,
4011 SourceLocation Loc) {
4012 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
4013 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
4014 RValue NewVVal;
4015 LValue VLValue = CGF.EmitLValue(V);
4016 LValue XLValue = CGF.EmitLValue(X);
4017 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004018 llvm::AtomicOrdering AO = IsSeqCst
4019 ? llvm::AtomicOrdering::SequentiallyConsistent
4020 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004021 QualType NewVValType;
4022 if (UE) {
4023 // 'x' is updated with some additional value.
4024 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
4025 "Update expr in 'atomic capture' must be a binary operator.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00004026 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
Alexey Bataev5e018f92015-04-23 06:35:10 +00004027 // Update expressions are allowed to have the following forms:
4028 // x binop= expr; -> xrval + expr;
4029 // x++, ++x -> xrval + 1;
4030 // x--, --x -> xrval - 1;
4031 // x = x binop expr; -> xrval binop expr
4032 // x = expr Op x; - > expr binop xrval;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004033 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
4034 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
4035 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004036 NewVValType = XRValExpr->getType();
Alexey Bataevddf3db92018-04-13 17:31:06 +00004037 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004038 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Alexey Bataevddf3db92018-04-13 17:31:06 +00004039 IsPostfixUpdate](RValue XRValue) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00004040 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
4041 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
4042 RValue Res = CGF.EmitAnyExpr(UE);
4043 NewVVal = IsPostfixUpdate ? XRValue : Res;
4044 return Res;
4045 };
4046 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
4047 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
4048 if (Res.first) {
4049 // 'atomicrmw' instruction was generated.
4050 if (IsPostfixUpdate) {
4051 // Use old value from 'atomicrmw'.
4052 NewVVal = Res.second;
4053 } else {
4054 // 'atomicrmw' does not provide new value, so evaluate it using old
4055 // value of 'x'.
4056 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
4057 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
4058 NewVVal = CGF.EmitAnyExpr(UE);
4059 }
4060 }
4061 } else {
4062 // 'x' is simply rewritten with some 'expr'.
4063 NewVValType = X->getType().getNonReferenceType();
4064 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004065 X->getType().getNonReferenceType(), Loc);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004066 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00004067 NewVVal = XRValue;
4068 return ExprRValue;
4069 };
4070 // Try to perform atomicrmw xchg, otherwise simple exchange.
4071 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
4072 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
4073 Loc, Gen);
4074 if (Res.first) {
4075 // 'atomicrmw' instruction was generated.
4076 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
4077 }
4078 }
4079 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00004080 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00004081 // OpenMP, 2.12.6, atomic Construct
4082 // Any atomic construct with a seq_cst clause forces the atomically
4083 // performed operation to include an implicit flush operation without a
4084 // list.
4085 if (IsSeqCst)
4086 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
4087}
4088
Alexey Bataevddf3db92018-04-13 17:31:06 +00004089static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00004090 bool IsSeqCst, bool IsPostfixUpdate,
4091 const Expr *X, const Expr *V, const Expr *E,
4092 const Expr *UE, bool IsXLHSInRHSPart,
4093 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00004094 switch (Kind) {
4095 case OMPC_read:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004096 emitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00004097 break;
4098 case OMPC_write:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004099 emitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
Alexey Bataevb8329262015-02-27 06:33:30 +00004100 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004101 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004102 case OMPC_update:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004103 emitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00004104 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00004105 case OMPC_capture:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004106 emitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
Alexey Bataev5e018f92015-04-23 06:35:10 +00004107 IsXLHSInRHSPart, Loc);
4108 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00004109 case OMPC_if:
4110 case OMPC_final:
4111 case OMPC_num_threads:
4112 case OMPC_private:
4113 case OMPC_firstprivate:
4114 case OMPC_lastprivate:
4115 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004116 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00004117 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004118 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00004119 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00004120 case OMPC_allocator:
Alexey Bataeve04483e2019-03-27 14:14:31 +00004121 case OMPC_allocate:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004122 case OMPC_collapse:
4123 case OMPC_default:
4124 case OMPC_seq_cst:
4125 case OMPC_shared:
4126 case OMPC_linear:
4127 case OMPC_aligned:
4128 case OMPC_copyin:
4129 case OMPC_copyprivate:
4130 case OMPC_flush:
4131 case OMPC_proc_bind:
4132 case OMPC_schedule:
4133 case OMPC_ordered:
4134 case OMPC_nowait:
4135 case OMPC_untied:
4136 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00004137 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004138 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00004139 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00004140 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004141 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00004142 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00004143 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00004144 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00004145 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00004146 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00004147 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00004148 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00004149 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00004150 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00004151 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004152 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00004153 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00004154 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00004155 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00004156 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00004157 case OMPC_unified_address:
Alexey Bataev94c50642018-10-01 14:26:31 +00004158 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00004159 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00004160 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00004161 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +00004162 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +00004163 case OMPC_match:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004164 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
4165 }
4166}
4167
4168void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004169 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00004170 OpenMPClauseKind Kind = OMPC_unknown;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004171 for (const OMPClause *C : S.clauses()) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00004172 // Find first clause (skip seq_cst clause, if it is first).
4173 if (C->getClauseKind() != OMPC_seq_cst) {
4174 Kind = C->getClauseKind();
4175 break;
4176 }
4177 }
Alexey Bataev10fec572015-03-11 04:48:56 +00004178
Alexey Bataevddf3db92018-04-13 17:31:06 +00004179 const Stmt *CS = S.getInnermostCapturedStmt()->IgnoreContainers();
Bill Wendling7c44da22018-10-31 03:48:47 +00004180 if (const auto *FE = dyn_cast<FullExpr>(CS))
4181 enterFullExpression(FE);
Alexey Bataev5e018f92015-04-23 06:35:10 +00004182 // Processing for statements under 'atomic capture'.
4183 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004184 for (const Stmt *C : Compound->body()) {
Bill Wendling7c44da22018-10-31 03:48:47 +00004185 if (const auto *FE = dyn_cast<FullExpr>(C))
4186 enterFullExpression(FE);
Alexey Bataev5e018f92015-04-23 06:35:10 +00004187 }
4188 }
Alexey Bataev10fec572015-03-11 04:48:56 +00004189
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004190 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
4191 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00004192 CGF.EmitStopPoint(CS);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004193 emitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
Alexey Bataev5e018f92015-04-23 06:35:10 +00004194 S.getV(), S.getExpr(), S.getUpdateExpr(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004195 S.isXLHSInRHSPart(), S.getBeginLoc());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004196 };
Alexey Bataev475a7442018-01-12 19:39:11 +00004197 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004198 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00004199}
4200
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004201static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
4202 const OMPExecutableDirective &S,
4203 const RegionCodeGenTy &CodeGen) {
4204 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
4205 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00004206
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00004207 // On device emit this construct as inlined code.
4208 if (CGM.getLangOpts().OpenMPIsDevice) {
4209 OMPLexicalScope Scope(CGF, S, OMPD_target);
4210 CGM.getOpenMPRuntime().emitInlinedDirective(
4211 CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev4ac68a22018-05-16 15:08:32 +00004212 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00004213 });
4214 return;
4215 }
4216
Samuel Antaoee8fb302016-01-06 13:42:12 +00004217 llvm::Function *Fn = nullptr;
4218 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00004219
Samuel Antaobed3c462015-10-02 16:14:20 +00004220 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00004221 // Check for the at most one if clause associated with the target region.
4222 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4223 if (C->getNameModifier() == OMPD_unknown ||
4224 C->getNameModifier() == OMPD_target) {
4225 IfCond = C->getCondition();
4226 break;
4227 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004228 }
4229
4230 // Check if we have any device clause associated with the directive.
4231 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004232 if (auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaobed3c462015-10-02 16:14:20 +00004233 Device = C->getDevice();
Samuel Antaobed3c462015-10-02 16:14:20 +00004234
Samuel Antaoee8fb302016-01-06 13:42:12 +00004235 // Check if we have an if clause whose conditional always evaluates to false
4236 // or if we do not have any targets specified. If so the target region is not
4237 // an offload entry point.
4238 bool IsOffloadEntry = true;
4239 if (IfCond) {
4240 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004241 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00004242 IsOffloadEntry = false;
4243 }
4244 if (CGM.getLangOpts().OMPTargetTriples.empty())
4245 IsOffloadEntry = false;
4246
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004247 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004248 StringRef ParentName;
4249 // In case we have Ctors/Dtors we use the complete type variant to produce
4250 // the mangling of the device outlined kernel.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004251 if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00004252 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Alexey Bataevddf3db92018-04-13 17:31:06 +00004253 else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00004254 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
4255 else
4256 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004257 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004258
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004259 // Emit target region as a standalone region.
4260 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
4261 IsOffloadEntry, CodeGen);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004262 OMPLexicalScope Scope(CGF, S, OMPD_task);
Alexey Bataevec7946e2019-09-23 14:06:51 +00004263 auto &&SizeEmitter =
4264 [IsOffloadEntry](CodeGenFunction &CGF,
4265 const OMPLoopDirective &D) -> llvm::Value * {
4266 if (IsOffloadEntry) {
4267 OMPLoopScope(CGF, D);
4268 // Emit calculation of the iterations count.
4269 llvm::Value *NumIterations = CGF.EmitScalarExpr(D.getNumIterations());
4270 NumIterations = CGF.Builder.CreateIntCast(NumIterations, CGF.Int64Ty,
4271 /*isSigned=*/false);
4272 return NumIterations;
4273 }
4274 return nullptr;
Alexey Bataev7bb33532019-01-07 21:30:43 +00004275 };
Alexey Bataevec7946e2019-09-23 14:06:51 +00004276 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
4277 SizeEmitter);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004278}
4279
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004280static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
4281 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004282 Action.Enter(CGF);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004283 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4284 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4285 CGF.EmitOMPPrivateClause(S, PrivateScope);
4286 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00004287 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4288 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004289
Alexey Bataev475a7442018-01-12 19:39:11 +00004290 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004291}
4292
4293void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
4294 StringRef ParentName,
4295 const OMPTargetDirective &S) {
4296 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4297 emitTargetRegion(CGF, S, Action);
4298 };
4299 llvm::Function *Fn;
4300 llvm::Constant *Addr;
4301 // Emit target region as a standalone region.
4302 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4303 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4304 assert(Fn && Addr && "Target device function emission failed.");
4305}
4306
4307void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
4308 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4309 emitTargetRegion(CGF, S, Action);
4310 };
4311 emitCommonOMPTargetDirective(*this, S, CodeGen);
4312}
4313
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004314static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
4315 const OMPExecutableDirective &S,
4316 OpenMPDirectiveKind InnermostKind,
4317 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004318 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
James Y Knight9871db02019-02-05 16:42:33 +00004319 llvm::Function *OutlinedFn =
Alexey Bataevddf3db92018-04-13 17:31:06 +00004320 CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
4321 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004322
Alexey Bataevddf3db92018-04-13 17:31:06 +00004323 const auto *NT = S.getSingleClause<OMPNumTeamsClause>();
4324 const auto *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004325 if (NT || TL) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004326 const Expr *NumTeams = NT ? NT->getNumTeams() : nullptr;
4327 const Expr *ThreadLimit = TL ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004328
Carlo Bertollic6872252016-04-04 15:55:02 +00004329 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004330 S.getBeginLoc());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004331 }
4332
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004333 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004334 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4335 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004336 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004337 CapturedVars);
4338}
4339
4340void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00004341 // Emit teams region as a standalone region.
Alexey Bataevc99042b2018-03-15 18:10:54 +00004342 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004343 Action.Enter(CGF);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004344 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00004345 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4346 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004347 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004348 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00004349 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004350 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004351 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00004352 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004353 emitPostUpdateForReductionClause(*this, S,
4354 [](CodeGenFunction &) { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00004355}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004356
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004357static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4358 const OMPTargetTeamsDirective &S) {
4359 auto *CS = S.getCapturedStmt(OMPD_teams);
4360 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004361 // Emit teams region as a standalone region.
4362 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004363 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004364 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4365 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4366 CGF.EmitOMPPrivateClause(S, PrivateScope);
4367 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4368 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00004369 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4370 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004371 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004372 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004373 };
4374 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004375 emitPostUpdateForReductionClause(CGF, S,
4376 [](CodeGenFunction &) { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004377}
4378
4379void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4380 CodeGenModule &CGM, StringRef ParentName,
4381 const OMPTargetTeamsDirective &S) {
4382 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4383 emitTargetTeamsRegion(CGF, Action, S);
4384 };
4385 llvm::Function *Fn;
4386 llvm::Constant *Addr;
4387 // Emit target region as a standalone region.
4388 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4389 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4390 assert(Fn && Addr && "Target device function emission failed.");
4391}
4392
4393void CodeGenFunction::EmitOMPTargetTeamsDirective(
4394 const OMPTargetTeamsDirective &S) {
4395 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4396 emitTargetTeamsRegion(CGF, Action, S);
4397 };
4398 emitCommonOMPTargetDirective(*this, S, CodeGen);
4399}
4400
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004401static void
4402emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4403 const OMPTargetTeamsDistributeDirective &S) {
4404 Action.Enter(CGF);
4405 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4406 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4407 };
4408
4409 // Emit teams region as a standalone region.
4410 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004411 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004412 Action.Enter(CGF);
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004413 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4414 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4415 (void)PrivateScope.Privatize();
4416 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4417 CodeGenDistribute);
4418 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4419 };
4420 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4421 emitPostUpdateForReductionClause(CGF, S,
4422 [](CodeGenFunction &) { return nullptr; });
4423}
4424
4425void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4426 CodeGenModule &CGM, StringRef ParentName,
4427 const OMPTargetTeamsDistributeDirective &S) {
4428 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4429 emitTargetTeamsDistributeRegion(CGF, Action, S);
4430 };
4431 llvm::Function *Fn;
4432 llvm::Constant *Addr;
4433 // Emit target region as a standalone region.
4434 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4435 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4436 assert(Fn && Addr && "Target device function emission failed.");
4437}
4438
4439void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4440 const OMPTargetTeamsDistributeDirective &S) {
4441 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4442 emitTargetTeamsDistributeRegion(CGF, Action, S);
4443 };
4444 emitCommonOMPTargetDirective(*this, S, CodeGen);
4445}
4446
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004447static void emitTargetTeamsDistributeSimdRegion(
4448 CodeGenFunction &CGF, PrePostActionTy &Action,
4449 const OMPTargetTeamsDistributeSimdDirective &S) {
4450 Action.Enter(CGF);
4451 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4452 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4453 };
4454
4455 // Emit teams region as a standalone region.
4456 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004457 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004458 Action.Enter(CGF);
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004459 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4460 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4461 (void)PrivateScope.Privatize();
4462 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4463 CodeGenDistribute);
4464 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4465 };
4466 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4467 emitPostUpdateForReductionClause(CGF, S,
4468 [](CodeGenFunction &) { return nullptr; });
4469}
4470
4471void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4472 CodeGenModule &CGM, StringRef ParentName,
4473 const OMPTargetTeamsDistributeSimdDirective &S) {
4474 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4475 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4476 };
4477 llvm::Function *Fn;
4478 llvm::Constant *Addr;
4479 // Emit target region as a standalone region.
4480 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4481 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4482 assert(Fn && Addr && "Target device function emission failed.");
4483}
4484
4485void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4486 const OMPTargetTeamsDistributeSimdDirective &S) {
4487 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4488 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4489 };
4490 emitCommonOMPTargetDirective(*this, S, CodeGen);
4491}
4492
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004493void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4494 const OMPTeamsDistributeDirective &S) {
4495
4496 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4497 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4498 };
4499
4500 // Emit teams region as a standalone region.
4501 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004502 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004503 Action.Enter(CGF);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004504 OMPPrivateScope PrivateScope(CGF);
4505 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4506 (void)PrivateScope.Privatize();
4507 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4508 CodeGenDistribute);
4509 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4510 };
Alexey Bataev95c6dd42017-11-29 15:14:16 +00004511 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004512 emitPostUpdateForReductionClause(*this, S,
4513 [](CodeGenFunction &) { return nullptr; });
4514}
4515
Alexey Bataev999277a2017-12-06 14:31:09 +00004516void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4517 const OMPTeamsDistributeSimdDirective &S) {
4518 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4519 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4520 };
4521
4522 // Emit teams region as a standalone region.
4523 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004524 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004525 Action.Enter(CGF);
Alexey Bataev999277a2017-12-06 14:31:09 +00004526 OMPPrivateScope PrivateScope(CGF);
4527 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4528 (void)PrivateScope.Privatize();
4529 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4530 CodeGenDistribute);
4531 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4532 };
4533 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4534 emitPostUpdateForReductionClause(*this, S,
4535 [](CodeGenFunction &) { return nullptr; });
4536}
4537
Carlo Bertolli62fae152017-11-20 20:46:39 +00004538void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4539 const OMPTeamsDistributeParallelForDirective &S) {
4540 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4541 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4542 S.getDistInc());
4543 };
4544
4545 // Emit teams region as a standalone region.
4546 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004547 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004548 Action.Enter(CGF);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004549 OMPPrivateScope PrivateScope(CGF);
4550 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4551 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00004552 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4553 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004554 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4555 };
4556 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4557 emitPostUpdateForReductionClause(*this, S,
4558 [](CodeGenFunction &) { return nullptr; });
4559}
4560
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004561void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4562 const OMPTeamsDistributeParallelForSimdDirective &S) {
4563 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4564 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4565 S.getDistInc());
4566 };
4567
4568 // Emit teams region as a standalone region.
4569 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004570 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004571 Action.Enter(CGF);
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004572 OMPPrivateScope PrivateScope(CGF);
4573 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4574 (void)PrivateScope.Privatize();
4575 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4576 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4577 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4578 };
4579 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4580 emitPostUpdateForReductionClause(*this, S,
4581 [](CodeGenFunction &) { return nullptr; });
4582}
4583
Carlo Bertolli52978c32018-01-03 21:12:44 +00004584static void emitTargetTeamsDistributeParallelForRegion(
4585 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
4586 PrePostActionTy &Action) {
Carlo Bertolli79712092018-02-28 20:48:35 +00004587 Action.Enter(CGF);
Carlo Bertolli52978c32018-01-03 21:12:44 +00004588 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4589 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4590 S.getDistInc());
4591 };
4592
4593 // Emit teams region as a standalone region.
4594 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004595 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004596 Action.Enter(CGF);
Carlo Bertolli52978c32018-01-03 21:12:44 +00004597 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4598 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4599 (void)PrivateScope.Privatize();
4600 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4601 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4602 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4603 };
4604
4605 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
4606 CodeGenTeams);
4607 emitPostUpdateForReductionClause(CGF, S,
4608 [](CodeGenFunction &) { return nullptr; });
4609}
4610
4611void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
4612 CodeGenModule &CGM, StringRef ParentName,
4613 const OMPTargetTeamsDistributeParallelForDirective &S) {
4614 // Emit SPMD target teams distribute parallel for region as a standalone
4615 // region.
4616 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4617 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4618 };
4619 llvm::Function *Fn;
4620 llvm::Constant *Addr;
4621 // Emit target region as a standalone region.
4622 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4623 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4624 assert(Fn && Addr && "Target device function emission failed.");
4625}
4626
4627void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
4628 const OMPTargetTeamsDistributeParallelForDirective &S) {
4629 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4630 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4631 };
4632 emitCommonOMPTargetDirective(*this, S, CodeGen);
4633}
4634
Alexey Bataev647dd842018-01-15 20:59:40 +00004635static void emitTargetTeamsDistributeParallelForSimdRegion(
4636 CodeGenFunction &CGF,
4637 const OMPTargetTeamsDistributeParallelForSimdDirective &S,
4638 PrePostActionTy &Action) {
Carlo Bertolli79712092018-02-28 20:48:35 +00004639 Action.Enter(CGF);
Alexey Bataev647dd842018-01-15 20:59:40 +00004640 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4641 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4642 S.getDistInc());
4643 };
4644
4645 // Emit teams region as a standalone region.
4646 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004647 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004648 Action.Enter(CGF);
Alexey Bataev647dd842018-01-15 20:59:40 +00004649 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4650 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4651 (void)PrivateScope.Privatize();
4652 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4653 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4654 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4655 };
4656
4657 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
4658 CodeGenTeams);
4659 emitPostUpdateForReductionClause(CGF, S,
4660 [](CodeGenFunction &) { return nullptr; });
4661}
4662
4663void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
4664 CodeGenModule &CGM, StringRef ParentName,
4665 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4666 // Emit SPMD target teams distribute parallel for simd region as a standalone
4667 // region.
4668 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4669 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4670 };
4671 llvm::Function *Fn;
4672 llvm::Constant *Addr;
4673 // Emit target region as a standalone region.
4674 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4675 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4676 assert(Fn && Addr && "Target device function emission failed.");
4677}
4678
4679void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
4680 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4681 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4682 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4683 };
4684 emitCommonOMPTargetDirective(*this, S, CodeGen);
4685}
4686
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004687void CodeGenFunction::EmitOMPCancellationPointDirective(
4688 const OMPCancellationPointDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004689 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00004690 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004691}
4692
Alexey Bataev80909872015-07-02 11:25:17 +00004693void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004694 const Expr *IfCond = nullptr;
4695 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4696 if (C->getNameModifier() == OMPD_unknown ||
4697 C->getNameModifier() == OMPD_cancel) {
4698 IfCond = C->getCondition();
4699 break;
4700 }
4701 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004702 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004703 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00004704}
4705
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004706CodeGenFunction::JumpDest
4707CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00004708 if (Kind == OMPD_parallel || Kind == OMPD_task ||
4709 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004710 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004711 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00004712 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
4713 Kind == OMPD_distribute_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004714 Kind == OMPD_target_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004715 Kind == OMPD_teams_distribute_parallel_for ||
4716 Kind == OMPD_target_teams_distribute_parallel_for);
Alexey Bataev957d8562016-11-17 15:12:05 +00004717 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004718}
Michael Wong65f367f2015-07-21 13:44:28 +00004719
Samuel Antaocc10b852016-07-28 14:23:26 +00004720void CodeGenFunction::EmitOMPUseDevicePtrClause(
4721 const OMPClause &NC, OMPPrivateScope &PrivateScope,
4722 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
4723 const auto &C = cast<OMPUseDevicePtrClause>(NC);
4724 auto OrigVarIt = C.varlist_begin();
4725 auto InitIt = C.inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00004726 for (const Expr *PvtVarIt : C.private_copies()) {
4727 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
4728 const auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
4729 const auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
Samuel Antaocc10b852016-07-28 14:23:26 +00004730
4731 // In order to identify the right initializer we need to match the
4732 // declaration used by the mapping logic. In some cases we may get
4733 // OMPCapturedExprDecl that refers to the original declaration.
4734 const ValueDecl *MatchingVD = OrigVD;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004735 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004736 // OMPCapturedExprDecl are used to privative fields of the current
4737 // structure.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004738 const auto *ME = cast<MemberExpr>(OED->getInit());
Samuel Antaocc10b852016-07-28 14:23:26 +00004739 assert(isa<CXXThisExpr>(ME->getBase()) &&
4740 "Base should be the current struct!");
4741 MatchingVD = ME->getMemberDecl();
4742 }
4743
4744 // If we don't have information about the current list item, move on to
4745 // the next one.
4746 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
4747 if (InitAddrIt == CaptureDeviceAddrMap.end())
4748 continue;
4749
Alexey Bataevddf3db92018-04-13 17:31:06 +00004750 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, OrigVD,
4751 InitAddrIt, InitVD,
4752 PvtVD]() {
Samuel Antaocc10b852016-07-28 14:23:26 +00004753 // Initialize the temporary initialization variable with the address we
4754 // get from the runtime library. We have to cast the source address
4755 // because it is always a void *. References are materialized in the
4756 // privatization scope, so the initialization here disregards the fact
4757 // the original variable is a reference.
4758 QualType AddrQTy =
4759 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
4760 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
4761 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
4762 setAddrOfLocalVar(InitVD, InitAddr);
4763
4764 // Emit private declaration, it will be initialized by the value we
4765 // declaration we just added to the local declarations map.
4766 EmitDecl(*PvtVD);
4767
4768 // The initialization variables reached its purpose in the emission
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004769 // of the previous declaration, so we don't need it anymore.
Samuel Antaocc10b852016-07-28 14:23:26 +00004770 LocalDeclMap.erase(InitVD);
4771
4772 // Return the address of the private variable.
4773 return GetAddrOfLocalVar(PvtVD);
4774 });
4775 assert(IsRegistered && "firstprivate var already registered as private");
4776 // Silence the warning about unused variable.
4777 (void)IsRegistered;
4778
4779 ++OrigVarIt;
4780 ++InitIt;
4781 }
4782}
4783
Michael Wong65f367f2015-07-21 13:44:28 +00004784// Generate the instructions for '#pragma omp target data' directive.
4785void CodeGenFunction::EmitOMPTargetDataDirective(
4786 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004787 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4788
4789 // Create a pre/post action to signal the privatization of the device pointer.
4790 // This action can be replaced by the OpenMP runtime code generation to
4791 // deactivate privatization.
4792 bool PrivatizeDevicePointers = false;
4793 class DevicePointerPrivActionTy : public PrePostActionTy {
4794 bool &PrivatizeDevicePointers;
4795
4796 public:
4797 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4798 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4799 void Enter(CodeGenFunction &CGF) override {
4800 PrivatizeDevicePointers = true;
4801 }
Samuel Antaodf158d52016-04-27 22:58:19 +00004802 };
Samuel Antaocc10b852016-07-28 14:23:26 +00004803 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4804
4805 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
Alexey Bataev475a7442018-01-12 19:39:11 +00004806 CodeGenFunction &CGF, PrePostActionTy &Action) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004807 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00004808 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Samuel Antaocc10b852016-07-28 14:23:26 +00004809 };
4810
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004811 // Codegen that selects whether to generate the privatization code or not.
Samuel Antaocc10b852016-07-28 14:23:26 +00004812 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4813 &InnermostCodeGen](CodeGenFunction &CGF,
4814 PrePostActionTy &Action) {
4815 RegionCodeGenTy RCG(InnermostCodeGen);
4816 PrivatizeDevicePointers = false;
4817
4818 // Call the pre-action to change the status of PrivatizeDevicePointers if
4819 // needed.
4820 Action.Enter(CGF);
4821
4822 if (PrivatizeDevicePointers) {
4823 OMPPrivateScope PrivateScope(CGF);
4824 // Emit all instances of the use_device_ptr clause.
4825 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4826 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4827 Info.CaptureDeviceAddrMap);
4828 (void)PrivateScope.Privatize();
4829 RCG(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004830 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00004831 RCG(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004832 }
Samuel Antaocc10b852016-07-28 14:23:26 +00004833 };
4834
4835 // Forward the provided action to the privatization codegen.
4836 RegionCodeGenTy PrivRCG(PrivCodeGen);
4837 PrivRCG.setAction(Action);
4838
4839 // Notwithstanding the body of the region is emitted as inlined directive,
4840 // we don't use an inline scope as changes in the references inside the
4841 // region are expected to be visible outside, so we do not privative them.
4842 OMPLexicalScope Scope(CGF, S);
4843 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4844 PrivRCG);
4845 };
4846
4847 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004848
4849 // If we don't have target devices, don't bother emitting the data mapping
4850 // code.
4851 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004852 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004853 return;
4854 }
4855
4856 // Check if we have any if clause associated with the directive.
4857 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004858 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antaodf158d52016-04-27 22:58:19 +00004859 IfCond = C->getCondition();
4860
4861 // Check if we have any device clause associated with the directive.
4862 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004863 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaodf158d52016-04-27 22:58:19 +00004864 Device = C->getDevice();
4865
Samuel Antaocc10b852016-07-28 14:23:26 +00004866 // Set the action to signal privatization of device pointers.
4867 RCG.setAction(PrivAction);
4868
4869 // Emit region code.
4870 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4871 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004872}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004873
Samuel Antaodf67fc42016-01-19 19:15:56 +00004874void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4875 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004876 // If we don't have target devices, don't bother emitting the data mapping
4877 // code.
4878 if (CGM.getLangOpts().OMPTargetTriples.empty())
4879 return;
4880
4881 // Check if we have any if clause associated with the directive.
4882 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004883 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004884 IfCond = C->getCondition();
4885
4886 // Check if we have any device clause associated with the directive.
4887 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004888 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004889 Device = C->getDevice();
4890
Alexey Bataev475a7442018-01-12 19:39:11 +00004891 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004892 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004893}
4894
Samuel Antao72590762016-01-19 20:04:50 +00004895void CodeGenFunction::EmitOMPTargetExitDataDirective(
4896 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004897 // If we don't have target devices, don't bother emitting the data mapping
4898 // code.
4899 if (CGM.getLangOpts().OMPTargetTriples.empty())
4900 return;
4901
4902 // Check if we have any if clause associated with the directive.
4903 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004904 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antao8dd66282016-04-27 23:14:30 +00004905 IfCond = C->getCondition();
4906
4907 // Check if we have any device clause associated with the directive.
4908 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004909 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antao8dd66282016-04-27 23:14:30 +00004910 Device = C->getDevice();
4911
Alexey Bataev475a7442018-01-12 19:39:11 +00004912 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004913 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004914}
4915
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004916static void emitTargetParallelRegion(CodeGenFunction &CGF,
4917 const OMPTargetParallelDirective &S,
4918 PrePostActionTy &Action) {
4919 // Get the captured statement associated with the 'parallel' region.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004920 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004921 Action.Enter(CGF);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004922 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004923 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004924 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4925 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4926 CGF.EmitOMPPrivateClause(S, PrivateScope);
4927 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4928 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00004929 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4930 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004931 // TODO: Add support for clauses.
4932 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004933 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004934 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004935 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4936 emitEmptyBoundParameters);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004937 emitPostUpdateForReductionClause(CGF, S,
4938 [](CodeGenFunction &) { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004939}
4940
4941void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4942 CodeGenModule &CGM, StringRef ParentName,
4943 const OMPTargetParallelDirective &S) {
4944 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4945 emitTargetParallelRegion(CGF, S, Action);
4946 };
4947 llvm::Function *Fn;
4948 llvm::Constant *Addr;
4949 // Emit target region as a standalone region.
4950 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4951 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4952 assert(Fn && Addr && "Target device function emission failed.");
4953}
4954
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004955void CodeGenFunction::EmitOMPTargetParallelDirective(
4956 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004957 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4958 emitTargetParallelRegion(CGF, S, Action);
4959 };
4960 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004961}
4962
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004963static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4964 const OMPTargetParallelForDirective &S,
4965 PrePostActionTy &Action) {
4966 Action.Enter(CGF);
4967 // Emit directive as a combined directive that consists of two implicit
4968 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00004969 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4970 Action.Enter(CGF);
Alexey Bataev2139ed62017-11-16 18:20:21 +00004971 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4972 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004973 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4974 emitDispatchForLoopBounds);
4975 };
4976 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4977 emitEmptyBoundParameters);
4978}
4979
4980void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4981 CodeGenModule &CGM, StringRef ParentName,
4982 const OMPTargetParallelForDirective &S) {
4983 // Emit SPMD target parallel for region as a standalone region.
4984 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4985 emitTargetParallelForRegion(CGF, S, Action);
4986 };
4987 llvm::Function *Fn;
4988 llvm::Constant *Addr;
4989 // Emit target region as a standalone region.
4990 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4991 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4992 assert(Fn && Addr && "Target device function emission failed.");
4993}
4994
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004995void CodeGenFunction::EmitOMPTargetParallelForDirective(
4996 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004997 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4998 emitTargetParallelForRegion(CGF, S, Action);
4999 };
5000 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005001}
5002
Alexey Bataev5d7edca2017-11-09 17:32:15 +00005003static void
5004emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
5005 const OMPTargetParallelForSimdDirective &S,
5006 PrePostActionTy &Action) {
5007 Action.Enter(CGF);
5008 // Emit directive as a combined directive that consists of two implicit
5009 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00005010 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5011 Action.Enter(CGF);
Alexey Bataev5d7edca2017-11-09 17:32:15 +00005012 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
5013 emitDispatchForLoopBounds);
5014 };
5015 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
5016 emitEmptyBoundParameters);
5017}
5018
5019void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
5020 CodeGenModule &CGM, StringRef ParentName,
5021 const OMPTargetParallelForSimdDirective &S) {
5022 // Emit SPMD target parallel for region as a standalone region.
5023 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5024 emitTargetParallelForSimdRegion(CGF, S, Action);
5025 };
5026 llvm::Function *Fn;
5027 llvm::Constant *Addr;
5028 // Emit target region as a standalone region.
5029 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
5030 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
5031 assert(Fn && Addr && "Target device function emission failed.");
5032}
5033
5034void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
5035 const OMPTargetParallelForSimdDirective &S) {
5036 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5037 emitTargetParallelForSimdRegion(CGF, S, Action);
5038 };
5039 emitCommonOMPTargetDirective(*this, S, CodeGen);
5040}
5041
Alexey Bataev7292c292016-04-25 12:22:29 +00005042/// Emit a helper variable and return corresponding lvalue.
5043static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
5044 const ImplicitParamDecl *PVD,
5045 CodeGenFunction::OMPPrivateScope &Privates) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005046 const auto *VDecl = cast<VarDecl>(Helper->getDecl());
5047 Privates.addPrivate(VDecl,
5048 [&CGF, PVD]() { return CGF.GetAddrOfLocalVar(PVD); });
Alexey Bataev7292c292016-04-25 12:22:29 +00005049}
5050
5051void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
5052 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
5053 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00005054 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
Alexey Bataevddf3db92018-04-13 17:31:06 +00005055 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
5056 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev7292c292016-04-25 12:22:29 +00005057 const Expr *IfCond = nullptr;
5058 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
5059 if (C->getNameModifier() == OMPD_unknown ||
5060 C->getNameModifier() == OMPD_taskloop) {
5061 IfCond = C->getCondition();
5062 break;
5063 }
5064 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005065
5066 OMPTaskDataTy Data;
5067 // Check if taskloop must be emitted without taskgroup.
5068 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00005069 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005070 Data.Tied = true;
5071 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005072 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
5073 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005074 Data.Schedule.setInt(/*IntVal=*/false);
5075 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005076 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
5077 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005078 Data.Schedule.setInt(/*IntVal=*/true);
5079 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005080 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005081
5082 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
5083 // if (PreCond) {
5084 // for (IV in 0..LastIteration) BODY;
5085 // <Final counter/linear vars updates>;
5086 // }
5087 //
5088
5089 // Emit: if (PreCond) - begin.
5090 // If the condition constant folds and can be elided, avoid emitting the
5091 // whole loop.
5092 bool CondConstant;
5093 llvm::BasicBlock *ContBlock = nullptr;
5094 OMPLoopScope PreInitScope(CGF, S);
5095 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
5096 if (!CondConstant)
5097 return;
5098 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005099 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
Alexey Bataev7292c292016-04-25 12:22:29 +00005100 ContBlock = CGF.createBasicBlock("taskloop.if.end");
5101 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
5102 CGF.getProfileCount(&S));
5103 CGF.EmitBlock(ThenBlock);
5104 CGF.incrementProfileCounter(&S);
5105 }
5106
Alexey Bataev14a388f2019-10-25 10:27:13 -04005107 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00005108 CGF.EmitOMPSimdInit(S);
Alexey Bataev14a388f2019-10-25 10:27:13 -04005109 (void)CGF.EmitOMPLinearClauseInit(S);
5110 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00005111
Alexey Bataev7292c292016-04-25 12:22:29 +00005112 OMPPrivateScope LoopScope(CGF);
5113 // Emit helper vars inits.
5114 enum { LowerBound = 5, UpperBound, Stride, LastIter };
5115 auto *I = CS->getCapturedDecl()->param_begin();
5116 auto *LBP = std::next(I, LowerBound);
5117 auto *UBP = std::next(I, UpperBound);
5118 auto *STP = std::next(I, Stride);
5119 auto *LIP = std::next(I, LastIter);
5120 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
5121 LoopScope);
5122 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
5123 LoopScope);
5124 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
5125 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
5126 LoopScope);
5127 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataev14a388f2019-10-25 10:27:13 -04005128 CGF.EmitOMPLinearClause(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00005129 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00005130 (void)LoopScope.Privatize();
5131 // Emit the loop iteration variable.
5132 const Expr *IVExpr = S.getIterationVariable();
Alexey Bataevddf3db92018-04-13 17:31:06 +00005133 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
Alexey Bataev7292c292016-04-25 12:22:29 +00005134 CGF.EmitVarDecl(*IVDecl);
5135 CGF.EmitIgnoredExpr(S.getInit());
5136
5137 // Emit the iterations count variable.
5138 // If it is not a variable, Sema decided to calculate iterations count on
5139 // each iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00005140 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005141 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
5142 // Emit calculation of the iterations count.
5143 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
5144 }
5145
5146 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
5147 S.getInc(),
5148 [&S](CodeGenFunction &CGF) {
5149 CGF.EmitOMPLoopBody(S, JumpDest());
5150 CGF.EmitStopPoint(&S);
5151 },
5152 [](CodeGenFunction &) {});
5153 // Emit: if (PreCond) - end.
5154 if (ContBlock) {
5155 CGF.EmitBranch(ContBlock);
5156 CGF.EmitBlock(ContBlock, true);
5157 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00005158 // Emit final copy of the lastprivate variables if IsLastIter != 0.
5159 if (HasLastprivateClause) {
5160 CGF.EmitOMPLastprivateClauseFinal(
5161 S, isOpenMPSimdDirective(S.getDirectiveKind()),
5162 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
5163 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005164 (*LIP)->getType(), S.getBeginLoc())));
Alexey Bataevf93095a2016-05-05 08:46:22 +00005165 }
Alexey Bataev14a388f2019-10-25 10:27:13 -04005166 CGF.EmitOMPLinearClauseFinal(S, [LIP, &S](CodeGenFunction &CGF) {
5167 return CGF.Builder.CreateIsNotNull(
5168 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
5169 (*LIP)->getType(), S.getBeginLoc()));
5170 });
Alexey Bataev7292c292016-04-25 12:22:29 +00005171 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005172 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
James Y Knight9871db02019-02-05 16:42:33 +00005173 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005174 const OMPTaskDataTy &Data) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005175 auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond,
5176 &Data](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005177 OMPLoopScope PreInitScope(CGF, S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005178 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005179 OutlinedFn, SharedsTy,
5180 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00005181 };
5182 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
5183 CodeGen);
5184 };
Alexey Bataev475a7442018-01-12 19:39:11 +00005185 if (Data.Nogroup) {
5186 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
5187 } else {
Alexey Bataev33446032017-07-12 18:09:32 +00005188 CGM.getOpenMPRuntime().emitTaskgroupRegion(
5189 *this,
5190 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
5191 PrePostActionTy &Action) {
5192 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00005193 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
5194 Data);
Alexey Bataev33446032017-07-12 18:09:32 +00005195 },
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005196 S.getBeginLoc());
Alexey Bataev33446032017-07-12 18:09:32 +00005197 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005198}
5199
Alexey Bataev49f6e782015-12-01 04:18:41 +00005200void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005201 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00005202}
5203
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005204void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
5205 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00005206 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005207}
Samuel Antao686c70c2016-05-26 17:30:50 +00005208
Alexey Bataev60e51c42019-10-10 20:13:02 +00005209void CodeGenFunction::EmitOMPMasterTaskLoopDirective(
5210 const OMPMasterTaskLoopDirective &S) {
5211 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5212 Action.Enter(CGF);
5213 EmitOMPTaskLoopBasedDirective(S);
5214 };
5215 OMPLexicalScope Scope(*this, S, llvm::None, /*EmitPreInitStmt=*/false);
5216 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
5217}
5218
Alexey Bataevb8552ab2019-10-18 16:47:35 +00005219void CodeGenFunction::EmitOMPMasterTaskLoopSimdDirective(
5220 const OMPMasterTaskLoopSimdDirective &S) {
5221 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5222 Action.Enter(CGF);
5223 EmitOMPTaskLoopBasedDirective(S);
5224 };
5225 OMPLexicalScope Scope(*this, S, llvm::None, /*EmitPreInitStmt=*/false);
5226 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
5227}
5228
Alexey Bataev5bbcead2019-10-14 17:17:41 +00005229void CodeGenFunction::EmitOMPParallelMasterTaskLoopDirective(
5230 const OMPParallelMasterTaskLoopDirective &S) {
5231 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5232 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
5233 PrePostActionTy &Action) {
5234 Action.Enter(CGF);
5235 CGF.EmitOMPTaskLoopBasedDirective(S);
5236 };
5237 OMPLexicalScope Scope(CGF, S, llvm::None, /*EmitPreInitStmt=*/false);
5238 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
5239 S.getBeginLoc());
5240 };
5241 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop, CodeGen,
5242 emitEmptyBoundParameters);
5243}
5244
Alexey Bataev14a388f2019-10-25 10:27:13 -04005245void CodeGenFunction::EmitOMPParallelMasterTaskLoopSimdDirective(
5246 const OMPParallelMasterTaskLoopSimdDirective &S) {
5247 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5248 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
5249 PrePostActionTy &Action) {
5250 Action.Enter(CGF);
5251 CGF.EmitOMPTaskLoopBasedDirective(S);
5252 };
5253 OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false);
5254 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
5255 S.getBeginLoc());
5256 };
5257 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop_simd, CodeGen,
5258 emitEmptyBoundParameters);
5259}
5260
Samuel Antao686c70c2016-05-26 17:30:50 +00005261// Generate the instructions for '#pragma omp target update' directive.
5262void CodeGenFunction::EmitOMPTargetUpdateDirective(
5263 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00005264 // If we don't have target devices, don't bother emitting the data mapping
5265 // code.
5266 if (CGM.getLangOpts().OMPTargetTriples.empty())
5267 return;
5268
5269 // Check if we have any if clause associated with the directive.
5270 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005271 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005272 IfCond = C->getCondition();
5273
5274 // Check if we have any device clause associated with the directive.
5275 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005276 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005277 Device = C->getDevice();
5278
Alexey Bataev475a7442018-01-12 19:39:11 +00005279 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00005280 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00005281}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005282
5283void CodeGenFunction::EmitSimpleOMPExecutableDirective(
5284 const OMPExecutableDirective &D) {
5285 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
5286 return;
Akira Hatanaka9f37c0e2019-12-03 13:07:22 -08005287 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005288 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
5289 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
5290 } else {
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005291 OMPPrivateScope LoopGlobals(CGF);
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005292 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005293 for (const Expr *E : LD->counters()) {
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005294 const auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
5295 if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) {
5296 LValue GlobLVal = CGF.EmitLValue(E);
5297 LoopGlobals.addPrivate(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08005298 VD, [&GlobLVal, &CGF]() { return GlobLVal.getAddress(CGF); });
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005299 }
Bjorn Pettersson6c2d83b2018-10-30 08:49:26 +00005300 if (isa<OMPCapturedExprDecl>(VD)) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005301 // Emit only those that were not explicitly referenced in clauses.
5302 if (!CGF.LocalDeclMap.count(VD))
5303 CGF.EmitVarDecl(*VD);
5304 }
5305 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005306 for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) {
5307 if (!C->getNumForLoops())
5308 continue;
5309 for (unsigned I = LD->getCollapsedNumber(),
5310 E = C->getLoopNumIterations().size();
5311 I < E; ++I) {
5312 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
Mike Rice0ed46662018-09-20 17:19:41 +00005313 cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00005314 // Emit only those that were not explicitly referenced in clauses.
5315 if (!CGF.LocalDeclMap.count(VD))
5316 CGF.EmitVarDecl(*VD);
5317 }
5318 }
5319 }
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005320 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005321 LoopGlobals.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00005322 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005323 }
5324 };
5325 OMPSimdLexicalScope Scope(*this, D);
5326 CGM.getOpenMPRuntime().emitInlinedDirective(
5327 *this,
5328 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
5329 : D.getDirectiveKind(),
5330 CodeGen);
5331}