blob: c70244d7794059da8ef8b8f918829dbb1ef6a1f6 [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 Bataev9959db52014-05-06 10:08:46 +000021using namespace clang;
22using namespace CodeGen;
23
Alexey Bataev3392d762016-02-16 11:18:12 +000024namespace {
25/// Lexical scope for OpenMP executable constructs, that handles correct codegen
26/// for captured expressions.
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000027class OMPLexicalScope : public CodeGenFunction::LexicalScope {
Alexey Bataev3392d762016-02-16 11:18:12 +000028 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
29 for (const auto *C : S.clauses()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +000030 if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
31 if (const auto *PreInit =
32 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000033 for (const auto *I : PreInit->decls()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +000034 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000035 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataevddf3db92018-04-13 17:31:06 +000036 } else {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000037 CodeGenFunction::AutoVarEmission Emission =
38 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
39 CGF.EmitAutoVarCleanups(Emission);
40 }
41 }
Alexey Bataev3392d762016-02-16 11:18:12 +000042 }
43 }
44 }
45 }
Alexey Bataev4ba78a42016-04-27 07:56:03 +000046 CodeGenFunction::OMPPrivateScope InlinedShareds;
47
48 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
49 return CGF.LambdaCaptureFields.lookup(VD) ||
50 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
51 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
52 }
Alexey Bataev3392d762016-02-16 11:18:12 +000053
Alexey Bataev3392d762016-02-16 11:18:12 +000054public:
Alexey Bataev475a7442018-01-12 19:39:11 +000055 OMPLexicalScope(
56 CodeGenFunction &CGF, const OMPExecutableDirective &S,
57 const llvm::Optional<OpenMPDirectiveKind> CapturedRegion = llvm::None,
58 const bool EmitPreInitStmt = true)
Alexey Bataev4ba78a42016-04-27 07:56:03 +000059 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
60 InlinedShareds(CGF) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000061 if (EmitPreInitStmt)
62 emitPreInitStmt(CGF, S);
Alexey Bataev475a7442018-01-12 19:39:11 +000063 if (!CapturedRegion.hasValue())
64 return;
65 assert(S.hasAssociatedStmt() &&
66 "Expected associated statement for inlined directive.");
67 const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion);
Alexey Bataevddf3db92018-04-13 17:31:06 +000068 for (const auto &C : CS->captures()) {
Alexey Bataev475a7442018-01-12 19:39:11 +000069 if (C.capturesVariable() || C.capturesVariableByCopy()) {
70 auto *VD = C.getCapturedVar();
71 assert(VD == VD->getCanonicalDecl() &&
72 "Canonical decl must be captured.");
73 DeclRefExpr DRE(
Bruno Ricci5fc4db72018-12-21 14:10:18 +000074 CGF.getContext(), const_cast<VarDecl *>(VD),
Alexey Bataev475a7442018-01-12 19:39:11 +000075 isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo &&
76 InlinedShareds.isGlobalVarCaptured(VD)),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +000077 VD->getType().getNonReferenceType(), VK_LValue, C.getLocation());
Alexey Bataev475a7442018-01-12 19:39:11 +000078 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
79 return CGF.EmitLValue(&DRE).getAddress();
80 });
Alexey Bataev4ba78a42016-04-27 07:56:03 +000081 }
82 }
Alexey Bataev475a7442018-01-12 19:39:11 +000083 (void)InlinedShareds.Privatize();
Alexey Bataev3392d762016-02-16 11:18:12 +000084 }
85};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000086
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000087/// Lexical scope for OpenMP parallel construct, that handles correct codegen
88/// for captured expressions.
89class OMPParallelScope final : public OMPLexicalScope {
90 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
91 OpenMPDirectiveKind Kind = S.getDirectiveKind();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +000092 return !(isOpenMPTargetExecutionDirective(Kind) ||
93 isOpenMPLoopBoundSharingDirective(Kind)) &&
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000094 isOpenMPParallelDirective(Kind);
95 }
96
97public:
98 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +000099 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
100 EmitPreInitStmt(S)) {}
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +0000101};
102
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000103/// Lexical scope for OpenMP teams construct, that handles correct codegen
104/// for captured expressions.
105class OMPTeamsScope final : public OMPLexicalScope {
106 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
107 OpenMPDirectiveKind Kind = S.getDirectiveKind();
108 return !isOpenMPTargetExecutionDirective(Kind) &&
109 isOpenMPTeamsDirective(Kind);
110 }
111
112public:
113 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +0000114 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
115 EmitPreInitStmt(S)) {}
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000116};
117
Alexey Bataev5a3af132016-03-29 08:58:54 +0000118/// Private scope for OpenMP loop-based directives, that supports capturing
119/// of used expression from loop statement.
120class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
121 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
Alexey Bataevab4ea222018-03-07 18:17:06 +0000122 CodeGenFunction::OMPMapVars PreCondVars;
Alexey Bataevf71939c2019-09-18 19:24:07 +0000123 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000124 for (const auto *E : S.counters()) {
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000125 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf71939c2019-09-18 19:24:07 +0000126 EmittedAsPrivate.insert(VD->getCanonicalDecl());
Alexey Bataevab4ea222018-03-07 18:17:06 +0000127 (void)PreCondVars.setVarAddr(
128 CGF, VD, CGF.CreateMemTemp(VD->getType().getNonReferenceType()));
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000129 }
Alexey Bataevf71939c2019-09-18 19:24:07 +0000130 // Mark private vars as undefs.
131 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
132 for (const Expr *IRef : C->varlists()) {
133 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
134 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
135 (void)PreCondVars.setVarAddr(
136 CGF, OrigVD,
137 Address(llvm::UndefValue::get(
138 CGF.ConvertTypeForMem(CGF.getContext().getPointerType(
139 OrigVD->getType().getNonReferenceType()))),
140 CGF.getContext().getDeclAlign(OrigVD)));
141 }
142 }
143 }
Alexey Bataevab4ea222018-03-07 18:17:06 +0000144 (void)PreCondVars.apply(CGF);
Alexey Bataevbef93a92019-10-07 18:54:57 +0000145 // Emit init, __range and __end variables for C++ range loops.
146 const Stmt *Body =
147 S.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers();
148 for (unsigned Cnt = 0; Cnt < S.getCollapsedNumber(); ++Cnt) {
149 Body = Body->IgnoreContainers();
150 if (auto *For = dyn_cast<ForStmt>(Body)) {
151 Body = For->getBody();
152 } else {
153 assert(isa<CXXForRangeStmt>(Body) &&
154 "Expected caonical for loop or range-based for loop.");
155 auto *CXXFor = cast<CXXForRangeStmt>(Body);
156 if (const Stmt *Init = CXXFor->getInit())
157 CGF.EmitStmt(Init);
158 CGF.EmitStmt(CXXFor->getRangeStmt());
159 CGF.EmitStmt(CXXFor->getEndStmt());
160 Body = CXXFor->getBody();
161 }
162 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000163 if (const auto *PreInits = cast_or_null<DeclStmt>(S.getPreInits())) {
George Burgess IV00f70bd2018-03-01 05:43:23 +0000164 for (const auto *I : PreInits->decls())
165 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataev5a3af132016-03-29 08:58:54 +0000166 }
Alexey Bataevab4ea222018-03-07 18:17:06 +0000167 PreCondVars.restore(CGF);
Alexey Bataev5a3af132016-03-29 08:58:54 +0000168 }
169
170public:
171 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
172 : CodeGenFunction::RunCleanupsScope(CGF) {
173 emitPreInitStmt(CGF, S);
174 }
175};
176
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000177class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
178 CodeGenFunction::OMPPrivateScope InlinedShareds;
179
180 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
181 return CGF.LambdaCaptureFields.lookup(VD) ||
182 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
183 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
184 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
185 }
186
187public:
188 OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
189 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
190 InlinedShareds(CGF) {
191 for (const auto *C : S.clauses()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000192 if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
193 if (const auto *PreInit =
194 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000195 for (const auto *I : PreInit->decls()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000196 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000197 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataevddf3db92018-04-13 17:31:06 +0000198 } else {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000199 CodeGenFunction::AutoVarEmission Emission =
200 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
201 CGF.EmitAutoVarCleanups(Emission);
202 }
203 }
204 }
205 } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
206 for (const Expr *E : UDP->varlists()) {
207 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
208 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
209 CGF.EmitVarDecl(*OED);
210 }
211 }
212 }
213 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
214 CGF.EmitOMPPrivateClause(S, InlinedShareds);
215 if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
216 if (const Expr *E = TG->getReductionRef())
217 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
218 }
219 const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
220 while (CS) {
221 for (auto &C : CS->captures()) {
222 if (C.capturesVariable() || C.capturesVariableByCopy()) {
223 auto *VD = C.getCapturedVar();
224 assert(VD == VD->getCanonicalDecl() &&
225 "Canonical decl must be captured.");
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000226 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD),
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000227 isCapturedVar(CGF, VD) ||
228 (CGF.CapturedStmtInfo &&
229 InlinedShareds.isGlobalVarCaptured(VD)),
230 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000231 C.getLocation());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000232 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
233 return CGF.EmitLValue(&DRE).getAddress();
234 });
235 }
236 }
237 CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
238 }
239 (void)InlinedShareds.Privatize();
240 }
241};
242
Alexey Bataev3392d762016-02-16 11:18:12 +0000243} // namespace
244
Alexey Bataevf8365372017-11-17 17:57:25 +0000245static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
246 const OMPExecutableDirective &S,
247 const RegionCodeGenTy &CodeGen);
248
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000249LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000250 if (const auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
251 if (const auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000252 OrigVD = OrigVD->getCanonicalDecl();
253 bool IsCaptured =
254 LambdaCaptureFields.lookup(OrigVD) ||
255 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
256 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000257 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), IsCaptured,
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000258 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
259 return EmitLValue(&DRE);
260 }
261 }
262 return EmitLValue(E);
263}
264
Alexey Bataev1189bd02016-01-26 12:20:39 +0000265llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000266 ASTContext &C = getContext();
Alexey Bataev1189bd02016-01-26 12:20:39 +0000267 llvm::Value *Size = nullptr;
268 auto SizeInChars = C.getTypeSizeInChars(Ty);
269 if (SizeInChars.isZero()) {
270 // getTypeSizeInChars() returns 0 for a VLA.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000271 while (const VariableArrayType *VAT = C.getAsVariableArrayType(Ty)) {
272 VlaSizePair VlaSize = getVLASize(VAT);
Sander de Smalen891af03a2018-02-03 13:55:59 +0000273 Ty = VlaSize.Type;
274 Size = Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts)
275 : VlaSize.NumElts;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000276 }
277 SizeInChars = C.getTypeSizeInChars(Ty);
278 if (SizeInChars.isZero())
279 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000280 return Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
281 }
282 return CGM.getSize(SizeInChars);
Alexey Bataev1189bd02016-01-26 12:20:39 +0000283}
284
Alexey Bataev2377fe92015-09-10 08:12:02 +0000285void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000286 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000287 const RecordDecl *RD = S.getCapturedRecordDecl();
288 auto CurField = RD->field_begin();
289 auto CurCap = S.captures().begin();
290 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
291 E = S.capture_init_end();
292 I != E; ++I, ++CurField, ++CurCap) {
293 if (CurField->hasCapturedVLAType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000294 const VariableArrayType *VAT = CurField->getCapturedVLAType();
295 llvm::Value *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000296 CapturedVars.push_back(Val);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000297 } else if (CurCap->capturesThis()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000298 CapturedVars.push_back(CXXThisValue);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000299 } else if (CurCap->capturesVariableByCopy()) {
Alexey Bataev1e491372018-01-23 18:44:14 +0000300 llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000301
302 // If the field is not a pointer, we need to save the actual value
303 // and load it as a void pointer.
304 if (!CurField->getType()->isAnyPointerType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000305 ASTContext &Ctx = getContext();
306 Address DstAddr = CreateMemTemp(
Samuel Antao6d004262016-06-16 18:39:34 +0000307 Ctx.getUIntPtrType(),
Alexey Bataevddf3db92018-04-13 17:31:06 +0000308 Twine(CurCap->getCapturedVar()->getName(), ".casted"));
Samuel Antao6d004262016-06-16 18:39:34 +0000309 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
310
Alexey Bataevddf3db92018-04-13 17:31:06 +0000311 llvm::Value *SrcAddrVal = EmitScalarConversion(
Samuel Antao6d004262016-06-16 18:39:34 +0000312 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000313 Ctx.getPointerType(CurField->getType()), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000314 LValue SrcLV =
315 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
316
317 // Store the value using the source type pointer.
318 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
319
320 // Load the value using the destination type pointer.
Alexey Bataev1e491372018-01-23 18:44:14 +0000321 CV = EmitLoadOfScalar(DstLV, CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000322 }
323 CapturedVars.push_back(CV);
324 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000325 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000326 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000327 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000328 }
329}
330
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000331static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc,
332 QualType DstType, StringRef Name,
Alexey Bataev06e80f62019-05-23 18:19:54 +0000333 LValue AddrLV) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000334 ASTContext &Ctx = CGF.getContext();
335
Alexey Bataevddf3db92018-04-13 17:31:06 +0000336 llvm::Value *CastedPtr = CGF.EmitScalarConversion(
337 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
338 Ctx.getPointerType(DstType), Loc);
339 Address TmpAddr =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000340 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
341 .getAddress();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000342 return TmpAddr;
343}
344
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000345static QualType getCanonicalParamType(ASTContext &C, QualType T) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000346 if (T->isLValueReferenceType())
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000347 return C.getLValueReferenceType(
348 getCanonicalParamType(C, T.getNonReferenceType()),
349 /*SpelledAsLValue=*/false);
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000350 if (T->isPointerType())
351 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
Alexey Bataevddf3db92018-04-13 17:31:06 +0000352 if (const ArrayType *A = T->getAsArrayTypeUnsafe()) {
353 if (const auto *VLA = dyn_cast<VariableArrayType>(A))
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000354 return getCanonicalParamType(C, VLA->getElementType());
Alexey Bataevddf3db92018-04-13 17:31:06 +0000355 if (!A->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000356 return C.getCanonicalType(T);
357 }
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000358 return C.getCanonicalParamType(T);
359}
360
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000361namespace {
362 /// Contains required data for proper outlined function codegen.
363 struct FunctionOptions {
364 /// Captured statement for which the function is generated.
365 const CapturedStmt *S = nullptr;
366 /// true if cast to/from UIntPtr is required for variables captured by
367 /// value.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000368 const bool UIntPtrCastRequired = true;
Alexey Bataeve754b182017-08-09 19:38:53 +0000369 /// true if only casted arguments must be registered as local args or VLA
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000370 /// sizes.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000371 const bool RegisterCastedArgsOnly = false;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000372 /// Name of the generated function.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000373 const StringRef FunctionName;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000374 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
375 bool RegisterCastedArgsOnly,
Alexey Bataev4aa19052017-08-08 16:45:36 +0000376 StringRef FunctionName)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000377 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
378 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
Alexey Bataev4aa19052017-08-08 16:45:36 +0000379 FunctionName(FunctionName) {}
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000380 };
381}
382
Alexey Bataeve754b182017-08-09 19:38:53 +0000383static llvm::Function *emitOutlinedFunctionPrologue(
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000384 CodeGenFunction &CGF, FunctionArgList &Args,
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000385 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000386 &LocalAddrs,
387 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
388 &VLASizes,
389 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
390 const CapturedDecl *CD = FO.S->getCapturedDecl();
391 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000392 assert(CD->hasBody() && "missing CapturedDecl body");
393
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000394 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000395 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000396 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000397 ASTContext &Ctx = CGM.getContext();
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000398 FunctionArgList TargetArgs;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000399 Args.append(CD->param_begin(),
400 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000401 TargetArgs.append(
402 CD->param_begin(),
403 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000404 auto I = FO.S->captures().begin();
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000405 FunctionDecl *DebugFunctionDecl = nullptr;
406 if (!FO.UIntPtrCastRequired) {
407 FunctionProtoType::ExtProtoInfo EPI;
Jonas Devlieghere64a26302018-11-11 00:56:15 +0000408 QualType FunctionTy = Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000409 DebugFunctionDecl = FunctionDecl::Create(
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000410 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getBeginLoc(),
Jonas Devlieghere64a26302018-11-11 00:56:15 +0000411 SourceLocation(), DeclarationName(), FunctionTy,
412 Ctx.getTrivialTypeSourceInfo(FunctionTy), SC_Static,
413 /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000414 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000415 for (const FieldDecl *FD : RD->fields()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000416 QualType ArgType = FD->getType();
417 IdentifierInfo *II = nullptr;
418 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000419
420 // If this is a capture by copy and the type is not a pointer, the outlined
421 // function argument type should be uintptr and the value properly casted to
422 // uintptr. This is necessary given that the runtime library is only able to
423 // deal with pointers. We can pass in the same way the VLA type sizes to the
424 // outlined function.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000425 if (FO.UIntPtrCastRequired &&
426 ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
427 I->capturesVariableArrayType()))
428 ArgType = Ctx.getUIntPtrType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000429
430 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000431 CapVar = I->getCapturedVar();
432 II = CapVar->getIdentifier();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000433 } else if (I->capturesThis()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000434 II = &Ctx.Idents.get("this");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000435 } else {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000436 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000437 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000438 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000439 if (ArgType->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000440 ArgType = getCanonicalParamType(Ctx, ArgType);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000441 VarDecl *Arg;
442 if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
443 Arg = ParmVarDecl::Create(
444 Ctx, DebugFunctionDecl,
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000445 CapVar ? CapVar->getBeginLoc() : FD->getBeginLoc(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000446 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
447 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
448 } else {
449 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
450 II, ArgType, ImplicitParamDecl::Other);
451 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000452 Args.emplace_back(Arg);
453 // Do not cast arguments if we emit function with non-original types.
454 TargetArgs.emplace_back(
455 FO.UIntPtrCastRequired
456 ? Arg
457 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000458 ++I;
459 }
460 Args.append(
461 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
462 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000463 TargetArgs.append(
464 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
465 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000466
467 // Create the function declaration.
Alexey Bataev2377fe92015-09-10 08:12:02 +0000468 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000469 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000470 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
471
Alexey Bataevddf3db92018-04-13 17:31:06 +0000472 auto *F =
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000473 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
474 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000475 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
476 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000477 F->setDoesNotThrow();
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000478 F->setDoesNotRecurse();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000479
480 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000481 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000482 FO.S->getBeginLoc(), CD->getBody()->getBeginLoc());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000483 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000484 I = FO.S->captures().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000485 for (const FieldDecl *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000486 // Do not map arguments if we emit function with non-original types.
487 Address LocalAddr(Address::invalid());
488 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
489 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
490 TargetArgs[Cnt]);
491 } else {
492 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
493 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000494 // If we are capturing a pointer by copy we don't need to do anything, just
495 // use the value that we get from the arguments.
496 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000497 const VarDecl *CurVD = I->getCapturedVar();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000498 if (!FO.RegisterCastedArgsOnly)
499 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000500 ++Cnt;
501 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000502 continue;
503 }
504
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000505 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
506 AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000507 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000508 if (FO.UIntPtrCastRequired) {
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000509 ArgLVal = CGF.MakeAddrLValue(
510 castValueFromUintptr(CGF, I->getLocation(), FD->getType(),
511 Args[Cnt]->getName(), ArgLVal),
512 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000513 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000514 llvm::Value *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
515 const VariableArrayType *VAT = FD->getCapturedVLAType();
516 VLASizes.try_emplace(Args[Cnt], VAT->getSizeExpr(), ExprArg);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000517 } else if (I->capturesVariable()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000518 const VarDecl *Var = I->getCapturedVar();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000519 QualType VarTy = Var->getType();
520 Address ArgAddr = ArgLVal.getAddress();
Alexey Bataev06e80f62019-05-23 18:19:54 +0000521 if (ArgLVal.getType()->isLValueReferenceType()) {
522 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
523 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
524 assert(ArgLVal.getType()->isPointerType());
525 ArgAddr = CGF.EmitLoadOfPointer(
526 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000527 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000528 if (!FO.RegisterCastedArgsOnly) {
529 LocalAddrs.insert(
530 {Args[Cnt],
531 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
532 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000533 } else if (I->capturesVariableByCopy()) {
534 assert(!FD->getType()->isAnyPointerType() &&
535 "Not expecting a captured pointer.");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000536 const VarDecl *Var = I->getCapturedVar();
Alexey Bataev06e80f62019-05-23 18:19:54 +0000537 LocalAddrs.insert({Args[Cnt],
538 {Var, FO.UIntPtrCastRequired
539 ? castValueFromUintptr(
540 CGF, I->getLocation(), FD->getType(),
541 Args[Cnt]->getName(), ArgLVal)
542 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000543 } else {
544 // If 'this' is captured, load it into CXXThisValue.
545 assert(I->capturesThis());
Alexey Bataev1e491372018-01-23 18:44:14 +0000546 CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000547 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000548 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000549 ++Cnt;
550 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000551 }
552
Alexey Bataeve754b182017-08-09 19:38:53 +0000553 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000554}
555
556llvm::Function *
557CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
558 assert(
559 CapturedStmtInfo &&
560 "CapturedStmtInfo should be set when generating the captured function");
561 const CapturedDecl *CD = S.getCapturedDecl();
562 // Build the argument list.
563 bool NeedWrapperFunction =
564 getDebugInfo() &&
565 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
566 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000567 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000568 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000569 SmallString<256> Buffer;
570 llvm::raw_svector_ostream Out(Buffer);
571 Out << CapturedStmtInfo->getHelperName();
572 if (NeedWrapperFunction)
573 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000574 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataeve754b182017-08-09 19:38:53 +0000575 Out.str());
576 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
577 VLASizes, CXXThisValue, FO);
Alexey Bataev06e80f62019-05-23 18:19:54 +0000578 CodeGenFunction::OMPPrivateScope LocalScope(*this);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000579 for (const auto &LocalAddrPair : LocalAddrs) {
580 if (LocalAddrPair.second.first) {
Alexey Bataev06e80f62019-05-23 18:19:54 +0000581 LocalScope.addPrivate(LocalAddrPair.second.first, [&LocalAddrPair]() {
582 return LocalAddrPair.second.second;
583 });
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000584 }
585 }
Alexey Bataev06e80f62019-05-23 18:19:54 +0000586 (void)LocalScope.Privatize();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000587 for (const auto &VLASizePair : VLASizes)
588 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000589 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000590 CapturedStmtInfo->EmitBody(*this, CD->getBody());
Alexey Bataev06e80f62019-05-23 18:19:54 +0000591 (void)LocalScope.ForceCleanup();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000592 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000593 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000594 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000595
Alexey Bataevefd884d2017-08-04 21:26:25 +0000596 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000597 /*RegisterCastedArgsOnly=*/true,
598 CapturedStmtInfo->getHelperName());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000599 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000600 WrapperCGF.CapturedStmtInfo = CapturedStmtInfo;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000601 Args.clear();
602 LocalAddrs.clear();
603 VLASizes.clear();
604 llvm::Function *WrapperF =
605 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000606 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000607 llvm::SmallVector<llvm::Value *, 4> CallArgs;
608 for (const auto *Arg : Args) {
609 llvm::Value *CallArg;
610 auto I = LocalAddrs.find(Arg);
611 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000612 LValue LV = WrapperCGF.MakeAddrLValue(
613 I->second.second,
614 I->second.first ? I->second.first->getType() : Arg->getType(),
615 AlignmentSource::Decl);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000616 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000617 } else {
618 auto EI = VLASizes.find(Arg);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000619 if (EI != VLASizes.end()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000620 CallArg = EI->second.second;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000621 } else {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000622 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000623 Arg->getType(),
624 AlignmentSource::Decl);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000625 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000626 }
627 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000628 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000629 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000630 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getBeginLoc(),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000631 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000632 WrapperCGF.FinishFunction();
633 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000634}
635
Alexey Bataev9959db52014-05-06 10:08:46 +0000636//===----------------------------------------------------------------------===//
637// OpenMP Directive Emission
638//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000639void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000640 Address DestAddr, Address SrcAddr, QualType OriginalType,
Alexey Bataevddf3db92018-04-13 17:31:06 +0000641 const llvm::function_ref<void(Address, Address)> CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000642 // Perform element-by-element initialization.
643 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000644
645 // Drill down to the base element type on both arrays.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000646 const ArrayType *ArrayTy = OriginalType->getAsArrayTypeUnsafe();
647 llvm::Value *NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
John McCall7f416cc2015-09-08 08:05:57 +0000648 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
649
Alexey Bataevddf3db92018-04-13 17:31:06 +0000650 llvm::Value *SrcBegin = SrcAddr.getPointer();
651 llvm::Value *DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000652 // Cast from pointer to array type to pointer to single element.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000653 llvm::Value *DestEnd = Builder.CreateGEP(DestBegin, NumElements);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000654 // The basic structure here is a while-do loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000655 llvm::BasicBlock *BodyBB = createBasicBlock("omp.arraycpy.body");
656 llvm::BasicBlock *DoneBB = createBasicBlock("omp.arraycpy.done");
657 llvm::Value *IsEmpty =
Alexey Bataev420d45b2015-04-14 05:11:24 +0000658 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
659 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000660
Alexey Bataev420d45b2015-04-14 05:11:24 +0000661 // Enter the loop body, making that address the current address.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000662 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000663 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000664
665 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
666
667 llvm::PHINode *SrcElementPHI =
668 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
669 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
670 Address SrcElementCurrent =
671 Address(SrcElementPHI,
672 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
673
674 llvm::PHINode *DestElementPHI =
675 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
676 DestElementPHI->addIncoming(DestBegin, EntryBB);
677 Address DestElementCurrent =
678 Address(DestElementPHI,
679 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000680
Alexey Bataev420d45b2015-04-14 05:11:24 +0000681 // Emit copy.
682 CopyGen(DestElementCurrent, SrcElementCurrent);
683
684 // Shift the address forward by one element.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000685 llvm::Value *DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000686 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000687 llvm::Value *SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000688 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000689 // Check whether we've reached the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000690 llvm::Value *Done =
Alexey Bataev420d45b2015-04-14 05:11:24 +0000691 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
692 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000693 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
694 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000695
696 // Done.
697 EmitBlock(DoneBB, /*IsFinished=*/true);
698}
699
John McCall7f416cc2015-09-08 08:05:57 +0000700void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
701 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000702 const VarDecl *SrcVD, const Expr *Copy) {
703 if (OriginalType->isArrayType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000704 const auto *BO = dyn_cast<BinaryOperator>(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000705 if (BO && BO->getOpcode() == BO_Assign) {
706 // Perform simple memcpy for simple copying.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000707 LValue Dest = MakeAddrLValue(DestAddr, OriginalType);
708 LValue Src = MakeAddrLValue(SrcAddr, OriginalType);
709 EmitAggregateAssign(Dest, Src, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000710 } else {
711 // For arrays with complex element types perform element by element
712 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000713 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000714 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000715 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000716 // Working with the single array element, so have to remap
717 // destination and source variables to corresponding array
718 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000719 CodeGenFunction::OMPPrivateScope Remap(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000720 Remap.addPrivate(DestVD, [DestElement]() { return DestElement; });
721 Remap.addPrivate(SrcVD, [SrcElement]() { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000722 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000723 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000724 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000725 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000726 } else {
727 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000728 CodeGenFunction::OMPPrivateScope Remap(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000729 Remap.addPrivate(SrcVD, [SrcAddr]() { return SrcAddr; });
730 Remap.addPrivate(DestVD, [DestAddr]() { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000731 (void)Remap.Privatize();
732 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000733 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000734 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000735}
736
Alexey Bataev69c62a92015-04-15 04:52:20 +0000737bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
738 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000739 if (!HaveInsertPoint())
740 return false;
Alexey Bataev1af5bd52019-03-05 17:47:18 +0000741 bool DeviceConstTarget =
742 getLangOpts().OpenMPIsDevice &&
743 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000744 bool FirstprivateIsLastprivate = false;
745 llvm::DenseSet<const VarDecl *> Lastprivates;
746 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
747 for (const auto *D : C->varlists())
748 Lastprivates.insert(
749 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
750 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000751 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev475a7442018-01-12 19:39:11 +0000752 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
753 getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind());
754 // Force emission of the firstprivate copy if the directive does not emit
755 // outlined function, like omp for, omp simd, omp distribute etc.
756 bool MustEmitFirstprivateCopy =
757 CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000758 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000759 auto IRef = C->varlist_begin();
760 auto InitsRef = C->inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000761 for (const Expr *IInit : C->private_copies()) {
762 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000763 bool ThisFirstprivateIsLastprivate =
764 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000765 const FieldDecl *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9c397812019-04-03 17:57:06 +0000766 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataev475a7442018-01-12 19:39:11 +0000767 if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
Alexey Bataev9c397812019-04-03 17:57:06 +0000768 !FD->getType()->isReferenceType() &&
769 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000770 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
771 ++IRef;
772 ++InitsRef;
773 continue;
774 }
Alexey Bataev1af5bd52019-03-05 17:47:18 +0000775 // Do not emit copy for firstprivate constant variables in target regions,
776 // captured by reference.
777 if (DeviceConstTarget && OrigVD->getType().isConstant(getContext()) &&
Alexey Bataev9c397812019-04-03 17:57:06 +0000778 FD && FD->getType()->isReferenceType() &&
779 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
Alexey Bataev1af5bd52019-03-05 17:47:18 +0000780 (void)CGM.getOpenMPRuntime().registerTargetFirstprivateCopy(*this,
781 OrigVD);
782 ++IRef;
783 ++InitsRef;
784 continue;
785 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000786 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000787 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000788 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000789 const auto *VDInit =
790 cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000791 bool IsRegistered;
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000792 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000793 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
794 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Alexey Bataeve0ef04f2019-05-23 22:30:43 +0000795 LValue OriginalLVal;
796 if (!FD) {
797 // Check if the firstprivate variable is just a constant value.
798 ConstantEmission CE = tryEmitAsConstant(&DRE);
799 if (CE && !CE.isReference()) {
800 // Constant value, no need to create a copy.
801 ++IRef;
802 ++InitsRef;
803 continue;
804 }
805 if (CE && CE.isReference()) {
806 OriginalLVal = CE.getReferenceLValue(*this, &DRE);
807 } else {
808 assert(!CE && "Expected non-constant firstprivate.");
809 OriginalLVal = EmitLValue(&DRE);
810 }
811 } else {
812 OriginalLVal = EmitLValue(&DRE);
813 }
Alexey Bataevfeddd642016-04-22 09:05:03 +0000814 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000815 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000816 // Emit VarDecl with copy init for arrays.
817 // Get the address of the original variable captured in current
818 // captured region.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000819 IsRegistered = PrivateScope.addPrivate(
820 OrigVD, [this, VD, Type, OriginalLVal, VDInit]() {
821 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
822 const Expr *Init = VD->getInit();
823 if (!isa<CXXConstructExpr>(Init) ||
824 isTrivialInitializer(Init)) {
825 // Perform simple memcpy.
826 LValue Dest =
827 MakeAddrLValue(Emission.getAllocatedAddress(), Type);
828 EmitAggregateAssign(Dest, OriginalLVal, Type);
829 } else {
830 EmitOMPAggregateAssign(
831 Emission.getAllocatedAddress(), OriginalLVal.getAddress(),
832 Type,
833 [this, VDInit, Init](Address DestElement,
834 Address SrcElement) {
835 // Clean up any temporaries needed by the
836 // initialization.
837 RunCleanupsScope InitScope(*this);
838 // Emit initialization for single element.
839 setAddrOfLocalVar(VDInit, SrcElement);
840 EmitAnyExprToMem(Init, DestElement,
841 Init->getType().getQualifiers(),
842 /*IsInitializer*/ false);
843 LocalDeclMap.erase(VDInit);
844 });
845 }
846 EmitAutoVarCleanups(Emission);
847 return Emission.getAllocatedAddress();
848 });
Alexey Bataev69c62a92015-04-15 04:52:20 +0000849 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000850 Address OriginalAddr = OriginalLVal.getAddress();
851 IsRegistered = PrivateScope.addPrivate(
852 OrigVD, [this, VDInit, OriginalAddr, VD]() {
853 // Emit private VarDecl with copy init.
854 // Remap temp VDInit variable to the address of the original
855 // variable (for proper handling of captured global variables).
856 setAddrOfLocalVar(VDInit, OriginalAddr);
857 EmitDecl(*VD);
858 LocalDeclMap.erase(VDInit);
859 return GetAddrOfLocalVar(VD);
860 });
Alexey Bataev69c62a92015-04-15 04:52:20 +0000861 }
862 assert(IsRegistered &&
863 "firstprivate var already registered as private");
864 // Silence the warning about unused variable.
865 (void)IsRegistered;
866 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000867 ++IRef;
868 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000869 }
870 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000871 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000872}
873
Alexey Bataev03b340a2014-10-21 03:16:40 +0000874void CodeGenFunction::EmitOMPPrivateClause(
875 const OMPExecutableDirective &D,
876 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000877 if (!HaveInsertPoint())
878 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000879 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000880 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000881 auto IRef = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000882 for (const Expr *IInit : C->private_copies()) {
883 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000884 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000885 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
886 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() {
887 // Emit private VarDecl with copy init.
888 EmitDecl(*VD);
889 return GetAddrOfLocalVar(VD);
890 });
Alexey Bataev50a64582015-04-22 12:24:45 +0000891 assert(IsRegistered && "private var already registered as private");
892 // Silence the warning about unused variable.
893 (void)IsRegistered;
894 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000895 ++IRef;
896 }
897 }
898}
899
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000900bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000901 if (!HaveInsertPoint())
902 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000903 // threadprivate_var1 = master_threadprivate_var1;
904 // operator=(threadprivate_var2, master_threadprivate_var2);
905 // ...
906 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000907 llvm::DenseSet<const VarDecl *> CopiedVars;
908 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000909 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000910 auto IRef = C->varlist_begin();
911 auto ISrcRef = C->source_exprs().begin();
912 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000913 for (const Expr *AssignOp : C->assignment_ops()) {
914 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000915 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000916 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000917 // Get the address of the master variable. If we are emitting code with
918 // TLS support, the address is passed from the master as field in the
919 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000920 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000921 if (getLangOpts().OpenMPUseTLS &&
922 getContext().getTargetInfo().isTLSSupported()) {
923 assert(CapturedStmtInfo->lookup(VD) &&
924 "Copyin threadprivates should have been captured!");
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000925 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), true,
926 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000927 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000928 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000929 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000930 MasterAddr =
931 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
932 : CGM.GetAddrOfGlobal(VD),
933 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000934 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000935 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000936 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000937 if (CopiedVars.size() == 1) {
938 // At first check if current thread is a master thread. If it is, no
939 // need to copy data.
940 CopyBegin = createBasicBlock("copyin.not.master");
941 CopyEnd = createBasicBlock("copyin.not.master.end");
942 Builder.CreateCondBr(
943 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000944 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
Alexey Bataevddf3db92018-04-13 17:31:06 +0000945 Builder.CreatePtrToInt(PrivateAddr.getPointer(),
946 CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000947 CopyBegin, CopyEnd);
948 EmitBlock(CopyBegin);
949 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000950 const auto *SrcVD =
951 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
952 const auto *DestVD =
953 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000954 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000955 }
956 ++IRef;
957 ++ISrcRef;
958 ++IDestRef;
959 }
960 }
961 if (CopyEnd) {
962 // Exit out of copying procedure for non-master thread.
963 EmitBlock(CopyEnd, /*IsFinished=*/true);
964 return true;
965 }
966 return false;
967}
968
Alexey Bataev38e89532015-04-16 04:54:05 +0000969bool CodeGenFunction::EmitOMPLastprivateClauseInit(
970 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000971 if (!HaveInsertPoint())
972 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000973 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000974 llvm::DenseSet<const VarDecl *> SIMDLCVs;
975 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000976 const auto *LoopDirective = cast<OMPLoopDirective>(&D);
977 for (const Expr *C : LoopDirective->counters()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000978 SIMDLCVs.insert(
979 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
980 }
981 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000982 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000983 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000984 HasAtLeastOneLastprivate = true;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000985 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
986 !getLangOpts().OpenMPSimd)
Alexey Bataevf93095a2016-05-05 08:46:22 +0000987 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000988 auto IRef = C->varlist_begin();
989 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000990 for (const Expr *IInit : C->private_copies()) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000991 // Keep the address of the original variable for future update at the end
992 // of the loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000993 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000994 // Taskloops do not require additional initialization, it is done in
995 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000996 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000997 const auto *DestVD =
998 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
999 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() {
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001000 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
1001 /*RefersToEnclosingVariableOrCapture=*/
1002 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1003 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00001004 return EmitLValue(&DRE).getAddress();
1005 });
1006 // Check if the variable is also a firstprivate: in this case IInit is
1007 // not generated. Initialization of this variable will happen in codegen
1008 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001009 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001010 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
1011 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() {
Alexey Bataevf93095a2016-05-05 08:46:22 +00001012 // Emit private VarDecl with copy init.
1013 EmitDecl(*VD);
1014 return GetAddrOfLocalVar(VD);
1015 });
Alexey Bataevd130fd12015-05-13 10:23:02 +00001016 assert(IsRegistered &&
1017 "lastprivate var already registered as private");
1018 (void)IsRegistered;
1019 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001020 }
Richard Trieucc3949d2016-02-18 22:34:54 +00001021 ++IRef;
1022 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +00001023 }
1024 }
1025 return HasAtLeastOneLastprivate;
1026}
1027
1028void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001029 const OMPExecutableDirective &D, bool NoFinals,
1030 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001031 if (!HaveInsertPoint())
1032 return;
Alexey Bataev38e89532015-04-16 04:54:05 +00001033 // Emit following code:
1034 // if (<IsLastIterCond>) {
1035 // orig_var1 = private_orig_var1;
1036 // ...
1037 // orig_varn = private_orig_varn;
1038 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001039 llvm::BasicBlock *ThenBB = nullptr;
1040 llvm::BasicBlock *DoneBB = nullptr;
1041 if (IsLastIterCond) {
1042 ThenBB = createBasicBlock(".omp.lastprivate.then");
1043 DoneBB = createBasicBlock(".omp.lastprivate.done");
1044 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
1045 EmitBlock(ThenBB);
1046 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001047 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
1048 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001049 if (const auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001050 auto IC = LoopDirective->counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001051 for (const Expr *F : LoopDirective->finals()) {
1052 const auto *D =
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001053 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1054 if (NoFinals)
1055 AlreadyEmittedVars.insert(D);
1056 else
1057 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001058 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001059 }
1060 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001061 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1062 auto IRef = C->varlist_begin();
1063 auto ISrcRef = C->source_exprs().begin();
1064 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001065 for (const Expr *AssignOp : C->assignment_ops()) {
1066 const auto *PrivateVD =
1067 cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001068 QualType Type = PrivateVD->getType();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001069 const auto *CanonicalVD = PrivateVD->getCanonicalDecl();
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001070 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1071 // If lastprivate variable is a loop control variable for loop-based
1072 // directive, update its value before copyin back to original
1073 // variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001074 if (const Expr *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001075 EmitIgnoredExpr(FinalExpr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001076 const auto *SrcVD =
1077 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1078 const auto *DestVD =
1079 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001080 // Get the address of the original variable.
1081 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
1082 // Get the address of the private variable.
1083 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001084 if (const auto *RefTy = PrivateVD->getType()->getAs<ReferenceType>())
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001085 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +00001086 Address(Builder.CreateLoad(PrivateAddr),
1087 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001088 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +00001089 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001090 ++IRef;
1091 ++ISrcRef;
1092 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +00001093 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001094 if (const Expr *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00001095 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001096 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001097 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001098 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +00001099}
1100
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001101void CodeGenFunction::EmitOMPReductionClauseInit(
1102 const OMPExecutableDirective &D,
1103 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001104 if (!HaveInsertPoint())
1105 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001106 SmallVector<const Expr *, 4> Shareds;
1107 SmallVector<const Expr *, 4> Privates;
1108 SmallVector<const Expr *, 4> ReductionOps;
1109 SmallVector<const Expr *, 4> LHSs;
1110 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001111 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001112 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001113 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001114 auto ILHS = C->lhs_exprs().begin();
1115 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001116 for (const Expr *Ref : C->varlists()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001117 Shareds.emplace_back(Ref);
1118 Privates.emplace_back(*IPriv);
1119 ReductionOps.emplace_back(*IRed);
1120 LHSs.emplace_back(*ILHS);
1121 RHSs.emplace_back(*IRHS);
1122 std::advance(IPriv, 1);
1123 std::advance(IRed, 1);
1124 std::advance(ILHS, 1);
1125 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001126 }
1127 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001128 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1129 unsigned Count = 0;
1130 auto ILHS = LHSs.begin();
1131 auto IRHS = RHSs.begin();
1132 auto IPriv = Privates.begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001133 for (const Expr *IRef : Shareds) {
1134 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001135 // Emit private VarDecl with reduction init.
1136 RedCG.emitSharedLValue(*this, Count);
1137 RedCG.emitAggregateType(*this, Count);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001138 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001139 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1140 RedCG.getSharedLValue(Count),
1141 [&Emission](CodeGenFunction &CGF) {
1142 CGF.EmitAutoVarInit(Emission);
1143 return true;
1144 });
1145 EmitAutoVarCleanups(Emission);
1146 Address BaseAddr = RedCG.adjustPrivateAddress(
1147 *this, Count, Emission.getAllocatedAddress());
1148 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataevddf3db92018-04-13 17:31:06 +00001149 RedCG.getBaseDecl(Count), [BaseAddr]() { return BaseAddr; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001150 assert(IsRegistered && "private var already registered as private");
1151 // Silence the warning about unused variable.
1152 (void)IsRegistered;
1153
Alexey Bataevddf3db92018-04-13 17:31:06 +00001154 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1155 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001156 QualType Type = PrivateVD->getType();
1157 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1158 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001159 // Store the address of the original variable associated with the LHS
1160 // implicit variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001161 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001162 return RedCG.getSharedLValue(Count).getAddress();
1163 });
Alexey Bataevddf3db92018-04-13 17:31:06 +00001164 PrivateScope.addPrivate(
1165 RHSVD, [this, PrivateVD]() { return GetAddrOfLocalVar(PrivateVD); });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001166 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1167 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001168 // Store the address of the original variable associated with the LHS
1169 // implicit variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001170 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001171 return RedCG.getSharedLValue(Count).getAddress();
1172 });
Alexey Bataevddf3db92018-04-13 17:31:06 +00001173 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001174 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1175 ConvertTypeForMem(RHSVD->getType()),
1176 "rhs.begin");
1177 });
1178 } else {
1179 QualType Type = PrivateVD->getType();
1180 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1181 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1182 // Store the address of the original variable associated with the LHS
1183 // implicit variable.
1184 if (IsArray) {
1185 OriginalAddr = Builder.CreateElementBitCast(
1186 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1187 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001188 PrivateScope.addPrivate(LHSVD, [OriginalAddr]() { return OriginalAddr; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001189 PrivateScope.addPrivate(
Alexey Bataevddf3db92018-04-13 17:31:06 +00001190 RHSVD, [this, PrivateVD, RHSVD, IsArray]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001191 return IsArray
1192 ? Builder.CreateElementBitCast(
1193 GetAddrOfLocalVar(PrivateVD),
1194 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1195 : GetAddrOfLocalVar(PrivateVD);
1196 });
1197 }
1198 ++ILHS;
1199 ++IRHS;
1200 ++IPriv;
1201 ++Count;
1202 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001203}
1204
1205void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001206 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001207 if (!HaveInsertPoint())
1208 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001209 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001210 llvm::SmallVector<const Expr *, 8> LHSExprs;
1211 llvm::SmallVector<const Expr *, 8> RHSExprs;
1212 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001213 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001214 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001215 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001216 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001217 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1218 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1219 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1220 }
1221 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001222 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1223 isOpenMPParallelDirective(D.getDirectiveKind()) ||
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001224 ReductionKind == OMPD_simd;
1225 bool SimpleReduction = ReductionKind == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001226 // Emit nowait reduction if nowait clause is present or directive is a
1227 // parallel directive (it always has implicit barrier).
1228 CGM.getOpenMPRuntime().emitReduction(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001229 *this, D.getEndLoc(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001230 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001231 }
1232}
1233
Alexey Bataev61205072016-03-02 04:57:40 +00001234static void emitPostUpdateForReductionClause(
1235 CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001236 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev61205072016-03-02 04:57:40 +00001237 if (!CGF.HaveInsertPoint())
1238 return;
1239 llvm::BasicBlock *DoneBB = nullptr;
1240 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001241 if (const Expr *PostUpdate = C->getPostUpdateExpr()) {
Alexey Bataev61205072016-03-02 04:57:40 +00001242 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001243 if (llvm::Value *Cond = CondGen(CGF)) {
Alexey Bataev61205072016-03-02 04:57:40 +00001244 // If the first post-update expression is found, emit conditional
1245 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001246 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
Alexey Bataev61205072016-03-02 04:57:40 +00001247 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1248 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1249 CGF.EmitBlock(ThenBB);
1250 }
1251 }
1252 CGF.EmitIgnoredExpr(PostUpdate);
1253 }
1254 }
1255 if (DoneBB)
1256 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1257}
1258
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001259namespace {
1260/// Codegen lambda for appending distribute lower and upper bounds to outlined
1261/// parallel function. This is necessary for combined constructs such as
1262/// 'distribute parallel for'
1263typedef llvm::function_ref<void(CodeGenFunction &,
1264 const OMPExecutableDirective &,
1265 llvm::SmallVectorImpl<llvm::Value *> &)>
1266 CodeGenBoundParametersTy;
1267} // anonymous namespace
1268
1269static void emitCommonOMPParallelDirective(
1270 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1271 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1272 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001273 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
James Y Knight9871db02019-02-05 16:42:33 +00001274 llvm::Function *OutlinedFn =
Alexey Bataevddf3db92018-04-13 17:31:06 +00001275 CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1276 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001277 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001278 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001279 llvm::Value *NumThreads =
1280 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1281 /*IgnoreResultAssign=*/true);
Alexey Bataev1d677132015-04-22 13:57:31 +00001282 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001283 CGF, NumThreads, NumThreadsClause->getBeginLoc());
Alexey Bataev1d677132015-04-22 13:57:31 +00001284 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001285 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001286 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001287 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001288 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getBeginLoc());
Alexey Bataev7f210c62015-06-18 13:40:03 +00001289 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001290 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001291 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1292 if (C->getNameModifier() == OMPD_unknown ||
1293 C->getNameModifier() == OMPD_parallel) {
1294 IfCond = C->getCondition();
1295 break;
1296 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001297 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001298
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001299 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001300 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001301 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1302 // lower and upper bounds with the pragma 'for' chunking mechanism.
1303 // The following lambda takes care of appending the lower and upper bound
1304 // parameters when necessary
1305 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001306 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001307 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getBeginLoc(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001308 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001309}
1310
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001311static void emitEmptyBoundParameters(CodeGenFunction &,
1312 const OMPExecutableDirective &,
1313 llvm::SmallVectorImpl<llvm::Value *> &) {}
1314
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001315void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001316 // Emit parallel region as a standalone region.
Alexey Bataevc99042b2018-03-15 18:10:54 +00001317 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001318 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001319 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001320 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001321 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1322 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001323 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001324 // propagation master's thread values of threadprivate variables to local
1325 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001326 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001327 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev25e5b442015-09-15 12:52:43 +00001328 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001329 }
1330 CGF.EmitOMPPrivateClause(S, PrivateScope);
1331 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1332 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00001333 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001334 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001335 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001336 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1337 emitEmptyBoundParameters);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001338 emitPostUpdateForReductionClause(*this, S,
1339 [](CodeGenFunction &) { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001340}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001341
Alexey Bataev0f34da12015-07-02 04:17:07 +00001342void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1343 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001344 RunCleanupsScope BodyScope(*this);
1345 // Update counters values on current iteration.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001346 for (const Expr *UE : D.updates())
1347 EmitIgnoredExpr(UE);
Alexander Musman3276a272015-03-21 10:12:56 +00001348 // Update the linear variables.
Alexey Bataev617db5f2017-12-04 15:38:33 +00001349 // In distribute directives only loop counters may be marked as linear, no
1350 // need to generate the code for them.
1351 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1352 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001353 for (const Expr *UE : C->updates())
1354 EmitIgnoredExpr(UE);
Alexey Bataev617db5f2017-12-04 15:38:33 +00001355 }
Alexander Musman3276a272015-03-21 10:12:56 +00001356 }
1357
Alexander Musmana5f070a2014-10-01 06:03:56 +00001358 // On a continue in the body, jump to the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001359 JumpDest Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001360 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexey Bataevf8be4762019-08-14 19:30:06 +00001361 for (const Expr *E : D.finals_conditions()) {
1362 if (!E)
1363 continue;
1364 // Check that loop counter in non-rectangular nest fits into the iteration
1365 // space.
1366 llvm::BasicBlock *NextBB = createBasicBlock("omp.body.next");
1367 EmitBranchOnBoolExpr(E, NextBB, Continue.getBlock(),
1368 getProfileCount(D.getBody()));
1369 EmitBlock(NextBB);
1370 }
Alexey Bataevbef93a92019-10-07 18:54:57 +00001371 // Emit loop variables for C++ range loops.
1372 const Stmt *Body =
1373 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers();
1374 for (unsigned Cnt = 0; Cnt < D.getCollapsedNumber(); ++Cnt) {
1375 Body = Body->IgnoreContainers();
1376 if (auto *For = dyn_cast<ForStmt>(Body)) {
1377 Body = For->getBody();
1378 } else {
1379 assert(isa<CXXForRangeStmt>(Body) &&
1380 "Expected caonical for loop or range-based for loop.");
1381 auto *CXXFor = cast<CXXForRangeStmt>(Body);
1382 EmitStmt(CXXFor->getLoopVarStmt());
1383 Body = CXXFor->getBody();
1384 }
1385 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001386 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001387 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001388 // The end (updates/cleanups).
1389 EmitBlock(Continue.getBlock());
1390 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001391}
1392
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001393void CodeGenFunction::EmitOMPInnerLoop(
1394 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1395 const Expr *IncExpr,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001396 const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
1397 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001398 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001399
1400 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001401 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001402 EmitBlock(CondBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001403 const SourceRange R = S.getSourceRange();
Amara Emerson652795d2016-11-10 14:44:30 +00001404 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1405 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001406
1407 // If there are any cleanups between here and the loop-exit scope,
1408 // create a block to stage a loop exit along.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001409 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001410 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001411 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001412
Alexey Bataevddf3db92018-04-13 17:31:06 +00001413 llvm::BasicBlock *LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001414
Alexey Bataev2df54a02015-03-12 08:53:29 +00001415 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001416 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001417 if (ExitBlock != LoopExit.getBlock()) {
1418 EmitBlock(ExitBlock);
1419 EmitBranchThroughCleanup(LoopExit);
1420 }
1421
1422 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001423 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001424
1425 // Create a block for the increment.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001426 JumpDest Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001427 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1428
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001429 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001430
1431 // Emit "IV = IV + 1" and a back-edge to the condition block.
1432 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001433 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001434 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001435 BreakContinueStack.pop_back();
1436 EmitBranch(CondBlock);
1437 LoopStack.pop();
1438 // Emit the fall-through block.
1439 EmitBlock(LoopExit.getBlock());
1440}
1441
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001442bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001443 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001444 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001445 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001446 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001447 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001448 for (const Expr *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001449 HasLinears = true;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001450 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
1451 if (const auto *Ref =
1452 dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001453 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001454 const auto *OrigVD = cast<VarDecl>(Ref->getDecl());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001455 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
Alexey Bataevef549a82016-03-09 09:49:09 +00001456 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1457 VD->getInit()->getType(), VK_LValue,
1458 VD->getInit()->getExprLoc());
1459 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1460 VD->getType()),
1461 /*capturedByInit=*/false);
1462 EmitAutoVarCleanups(Emission);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001463 } else {
Alexey Bataevef549a82016-03-09 09:49:09 +00001464 EmitVarDecl(*VD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001465 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001466 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001467 // Emit the linear steps for the linear clauses.
1468 // If a step is not constant, it is pre-calculated before the loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001469 if (const auto *CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1470 if (const auto *SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001471 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001472 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001473 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001474 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001475 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001476 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001477}
1478
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001479void CodeGenFunction::EmitOMPLinearClauseFinal(
1480 const OMPLoopDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001481 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001482 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001483 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001484 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001485 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001486 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001487 auto IC = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001488 for (const Expr *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001489 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001490 if (llvm::Value *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001491 // If the first post-update expression is found, emit conditional
1492 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001493 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.linear.pu");
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001494 DoneBB = createBasicBlock(".omp.linear.pu.done");
1495 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1496 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001497 }
1498 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001499 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001500 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001501 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001502 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001503 Address OrigAddr = EmitLValue(&DRE).getAddress();
1504 CodeGenFunction::OMPPrivateScope VarScope(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001505 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001506 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001507 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001508 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001509 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001510 if (const Expr *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001511 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001512 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001513 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001514 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001515}
1516
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001517static void emitAlignedClause(CodeGenFunction &CGF,
1518 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001519 if (!CGF.HaveInsertPoint())
1520 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001521 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001522 unsigned ClauseAlignment = 0;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001523 if (const Expr *AlignmentExpr = Clause->getAlignment()) {
1524 auto *AlignmentCI =
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001525 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1526 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001527 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001528 for (const Expr *E : Clause->varlists()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001529 unsigned Alignment = ClauseAlignment;
1530 if (Alignment == 0) {
1531 // OpenMP [2.8.1, Description]
1532 // If no optional parameter is specified, implementation-defined default
1533 // alignments for SIMD instructions on the target platforms are assumed.
1534 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001535 CGF.getContext()
1536 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1537 E->getType()->getPointeeType()))
1538 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001539 }
1540 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1541 "alignment is not power of 2");
1542 if (Alignment != 0) {
1543 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
Roman Lebedevbd1c0872019-01-15 09:44:25 +00001544 CGF.EmitAlignmentAssumption(
1545 PtrValue, E, /*No second loc needed*/ SourceLocation(), Alignment);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001546 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001547 }
1548 }
1549}
1550
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001551void CodeGenFunction::EmitOMPPrivateLoopCounters(
1552 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1553 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001554 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001555 auto I = S.private_counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001556 for (const Expr *E : S.counters()) {
1557 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1558 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataevab4ea222018-03-07 18:17:06 +00001559 // Emit var without initialization.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001560 AutoVarEmission VarEmission = EmitAutoVarAlloca(*PrivateVD);
Alexey Bataevab4ea222018-03-07 18:17:06 +00001561 EmitAutoVarCleanups(VarEmission);
1562 LocalDeclMap.erase(PrivateVD);
1563 (void)LoopScope.addPrivate(VD, [&VarEmission]() {
1564 return VarEmission.getAllocatedAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001565 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001566 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1567 VD->hasGlobalStorage()) {
Alexey Bataevab4ea222018-03-07 18:17:06 +00001568 (void)LoopScope.addPrivate(PrivateVD, [this, VD, E]() {
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001569 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001570 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1571 E->getType(), VK_LValue, E->getExprLoc());
1572 return EmitLValue(&DRE).getAddress();
1573 });
Alexey Bataevab4ea222018-03-07 18:17:06 +00001574 } else {
1575 (void)LoopScope.addPrivate(PrivateVD, [&VarEmission]() {
1576 return VarEmission.getAllocatedAddress();
1577 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001578 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001579 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001580 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00001581 // Privatize extra loop counters used in loops for ordered(n) clauses.
1582 for (const auto *C : S.getClausesOfKind<OMPOrderedClause>()) {
1583 if (!C->getNumForLoops())
1584 continue;
1585 for (unsigned I = S.getCollapsedNumber(),
1586 E = C->getLoopNumIterations().size();
1587 I < E; ++I) {
Mike Rice0ed46662018-09-20 17:19:41 +00001588 const auto *DRE = cast<DeclRefExpr>(C->getLoopCounter(I));
Alexey Bataevf138fda2018-08-13 19:04:24 +00001589 const auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00001590 // Override only those variables that can be captured to avoid re-emission
1591 // of the variables declared within the loops.
1592 if (DRE->refersToEnclosingVariableOrCapture()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00001593 (void)LoopScope.addPrivate(VD, [this, DRE, VD]() {
1594 return CreateMemTemp(DRE->getType(), VD->getName());
1595 });
1596 }
1597 }
1598 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001599}
1600
Alexey Bataev62dbb972015-04-22 11:59:37 +00001601static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1602 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1603 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001604 if (!CGF.HaveInsertPoint())
1605 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001606 {
1607 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001608 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001609 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001610 // Get initial values of real counters.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001611 for (const Expr *I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001612 CGF.EmitIgnoredExpr(I);
1613 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001614 }
Alexey Bataevf8be4762019-08-14 19:30:06 +00001615 // Create temp loop control variables with their init values to support
1616 // non-rectangular loops.
1617 CodeGenFunction::OMPMapVars PreCondVars;
1618 for (const Expr * E: S.dependent_counters()) {
1619 if (!E)
1620 continue;
1621 assert(!E->getType().getNonReferenceType()->isRecordType() &&
1622 "dependent counter must not be an iterator.");
1623 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1624 Address CounterAddr =
1625 CGF.CreateMemTemp(VD->getType().getNonReferenceType());
1626 (void)PreCondVars.setVarAddr(CGF, VD, CounterAddr);
1627 }
1628 (void)PreCondVars.apply(CGF);
1629 for (const Expr *E : S.dependent_inits()) {
1630 if (!E)
1631 continue;
1632 CGF.EmitIgnoredExpr(E);
1633 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001634 // Check that loop is executed at least one time.
1635 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
Alexey Bataevf8be4762019-08-14 19:30:06 +00001636 PreCondVars.restore(CGF);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001637}
1638
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001639void CodeGenFunction::EmitOMPLinearClause(
1640 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1641 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001642 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001643 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1644 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001645 const auto *LoopDirective = cast<OMPLoopDirective>(&D);
1646 for (const Expr *C : LoopDirective->counters()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001647 SIMDLCVs.insert(
1648 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1649 }
1650 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001651 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001652 auto CurPrivate = C->privates().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001653 for (const Expr *E : C->varlists()) {
1654 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1655 const auto *PrivateVD =
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001656 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001657 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001658 bool IsRegistered = PrivateScope.addPrivate(VD, [this, PrivateVD]() {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001659 // Emit private VarDecl with copy init.
1660 EmitVarDecl(*PrivateVD);
1661 return GetAddrOfLocalVar(PrivateVD);
1662 });
1663 assert(IsRegistered && "linear var already registered as private");
1664 // Silence the warning about unused variable.
1665 (void)IsRegistered;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001666 } else {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001667 EmitVarDecl(*PrivateVD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001668 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001669 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001670 }
1671 }
1672}
1673
Alexey Bataev45bfad52015-08-21 12:19:04 +00001674static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001675 const OMPExecutableDirective &D,
1676 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001677 if (!CGF.HaveInsertPoint())
1678 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001679 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001680 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1681 /*ignoreResult=*/true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001682 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Alexey Bataev45bfad52015-08-21 12:19:04 +00001683 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1684 // In presence of finite 'safelen', it may be unsafe to mark all
1685 // the memory instructions parallel, because loop-carried
1686 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001687 if (!IsMonotonic)
1688 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001689 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001690 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1691 /*ignoreResult=*/true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001692 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001693 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001694 // In presence of finite 'safelen', it may be unsafe to mark all
1695 // the memory instructions parallel, because loop-carried
1696 // dependences of 'safelen' iterations are possible.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001697 CGF.LoopStack.setParallel(/*Enable=*/false);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001698 }
1699}
1700
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001701void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1702 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001703 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001704 LoopStack.setParallel(!IsMonotonic);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001705 LoopStack.setVectorizeEnable();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001706 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001707}
1708
Alexey Bataevef549a82016-03-09 09:49:09 +00001709void CodeGenFunction::EmitOMPSimdFinal(
1710 const OMPLoopDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001711 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001712 if (!HaveInsertPoint())
1713 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001714 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001715 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001716 auto IPC = D.private_counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001717 for (const Expr *F : D.finals()) {
1718 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
1719 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1720 const auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001721 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1722 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001723 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001724 if (llvm::Value *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001725 // If the first post-update expression is found, emit conditional
1726 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001727 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.final.then");
Alexey Bataevef549a82016-03-09 09:49:09 +00001728 DoneBB = createBasicBlock(".omp.final.done");
1729 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1730 EmitBlock(ThenBB);
1731 }
1732 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001733 Address OrigAddr = Address::invalid();
Alexey Bataevab4ea222018-03-07 18:17:06 +00001734 if (CED) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001735 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
Alexey Bataevab4ea222018-03-07 18:17:06 +00001736 } else {
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001737 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(PrivateVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001738 /*RefersToEnclosingVariableOrCapture=*/false,
1739 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1740 OrigAddr = EmitLValue(&DRE).getAddress();
1741 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001742 OMPPrivateScope VarScope(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001743 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001744 (void)VarScope.Privatize();
1745 EmitIgnoredExpr(F);
1746 }
1747 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001748 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001749 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001750 if (DoneBB)
1751 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001752}
1753
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001754static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1755 const OMPLoopDirective &S,
1756 CodeGenFunction::JumpDest LoopExit) {
1757 CGF.EmitOMPLoopBody(S, LoopExit);
1758 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001759}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001760
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001761/// Emit a helper variable and return corresponding lvalue.
1762static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1763 const DeclRefExpr *Helper) {
1764 auto VDecl = cast<VarDecl>(Helper->getDecl());
1765 CGF.EmitVarDecl(*VDecl);
1766 return CGF.EmitLValue(Helper);
1767}
1768
Alexey Bataevf8365372017-11-17 17:57:25 +00001769static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1770 PrePostActionTy &Action) {
1771 Action.Enter(CGF);
1772 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1773 "Expected simd directive");
1774 OMPLoopScope PreInitScope(CGF, S);
1775 // if (PreCond) {
1776 // for (IV in 0..LastIteration) BODY;
1777 // <Final counter/linear vars updates>;
1778 // }
1779 //
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001780 if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
1781 isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
1782 isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
1783 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1784 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1785 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001786
Alexey Bataevf8365372017-11-17 17:57:25 +00001787 // Emit: if (PreCond) - begin.
1788 // If the condition constant folds and can be elided, avoid emitting the
1789 // whole loop.
1790 bool CondConstant;
1791 llvm::BasicBlock *ContBlock = nullptr;
1792 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1793 if (!CondConstant)
1794 return;
1795 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001796 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("simd.if.then");
Alexey Bataevf8365372017-11-17 17:57:25 +00001797 ContBlock = CGF.createBasicBlock("simd.if.end");
1798 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1799 CGF.getProfileCount(&S));
1800 CGF.EmitBlock(ThenBlock);
1801 CGF.incrementProfileCounter(&S);
1802 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001803
Alexey Bataevf8365372017-11-17 17:57:25 +00001804 // Emit the loop iteration variable.
1805 const Expr *IVExpr = S.getIterationVariable();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001806 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
Alexey Bataevf8365372017-11-17 17:57:25 +00001807 CGF.EmitVarDecl(*IVDecl);
1808 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001809
Alexey Bataevf8365372017-11-17 17:57:25 +00001810 // Emit the iterations count variable.
1811 // If it is not a variable, Sema decided to calculate iterations count on
1812 // each iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00001813 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexey Bataevf8365372017-11-17 17:57:25 +00001814 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1815 // Emit calculation of the iterations count.
1816 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1817 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001818
Alexey Bataevf8365372017-11-17 17:57:25 +00001819 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001820
Alexey Bataevf8365372017-11-17 17:57:25 +00001821 emitAlignedClause(CGF, S);
1822 (void)CGF.EmitOMPLinearClauseInit(S);
1823 {
1824 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1825 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1826 CGF.EmitOMPLinearClause(S, LoopScope);
1827 CGF.EmitOMPPrivateClause(S, LoopScope);
1828 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1829 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1830 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00001831 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
1832 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Alexey Bataevf8365372017-11-17 17:57:25 +00001833 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1834 S.getInc(),
1835 [&S](CodeGenFunction &CGF) {
1836 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1837 CGF.EmitStopPoint(&S);
1838 },
1839 [](CodeGenFunction &) {});
Alexey Bataevddf3db92018-04-13 17:31:06 +00001840 CGF.EmitOMPSimdFinal(S, [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001841 // Emit final copy of the lastprivate variables at the end of loops.
1842 if (HasLastprivateClause)
1843 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1844 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001845 emitPostUpdateForReductionClause(CGF, S,
1846 [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001847 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001848 CGF.EmitOMPLinearClauseFinal(S, [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001849 // Emit: if (PreCond) - end.
1850 if (ContBlock) {
1851 CGF.EmitBranch(ContBlock);
1852 CGF.EmitBlock(ContBlock, true);
1853 }
1854}
1855
1856void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1857 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1858 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001859 };
Alexey Bataev475a7442018-01-12 19:39:11 +00001860 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001861 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001862}
1863
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001864void CodeGenFunction::EmitOMPOuterLoop(
1865 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1866 CodeGenFunction::OMPPrivateScope &LoopScope,
1867 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1868 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1869 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001870 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001871
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001872 const Expr *IVExpr = S.getIterationVariable();
1873 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1874 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1875
Alexey Bataevddf3db92018-04-13 17:31:06 +00001876 JumpDest LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001877
1878 // Start the loop with a block that tests the condition.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001879 llvm::BasicBlock *CondBlock = createBasicBlock("omp.dispatch.cond");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001880 EmitBlock(CondBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001881 const SourceRange R = S.getSourceRange();
Amara Emerson652795d2016-11-10 14:44:30 +00001882 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1883 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001884
1885 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001886 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001887 // UB = min(UB, GlobalUB) or
1888 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1889 // 'distribute parallel for')
1890 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001891 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001892 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001893 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001894 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001895 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001896 BoolCondVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001897 RT.emitForNext(*this, S.getBeginLoc(), IVSize, IVSigned, LoopArgs.IL,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001898 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001899 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001900
1901 // If there are any cleanups between here and the loop-exit scope,
1902 // create a block to stage a loop exit along.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001903 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001904 if (LoopScope.requiresCleanups())
1905 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1906
Alexey Bataevddf3db92018-04-13 17:31:06 +00001907 llvm::BasicBlock *LoopBody = createBasicBlock("omp.dispatch.body");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001908 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1909 if (ExitBlock != LoopExit.getBlock()) {
1910 EmitBlock(ExitBlock);
1911 EmitBranchThroughCleanup(LoopExit);
1912 }
1913 EmitBlock(LoopBody);
1914
Alexander Musman92bdaab2015-03-12 13:37:50 +00001915 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1916 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001917 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001918 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001919
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001920 // Create a block for the increment.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001921 JumpDest Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001922 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1923
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001924 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1925 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001926 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1927 LoopStack.setParallel(!IsMonotonic);
1928 else
1929 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001930
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001931 SourceLocation Loc = S.getBeginLoc();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001932
1933 // when 'distribute' is not combined with a 'for':
1934 // while (idx <= UB) { BODY; ++idx; }
1935 // when 'distribute' is combined with a 'for'
1936 // (e.g. 'distribute parallel for')
1937 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1938 EmitOMPInnerLoop(
1939 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1940 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1941 CodeGenLoop(CGF, S, LoopExit);
1942 },
1943 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1944 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1945 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001946
1947 EmitBlock(Continue.getBlock());
1948 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001949 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001950 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001951 EmitIgnoredExpr(LoopArgs.NextLB);
1952 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001953 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001954
1955 EmitBranch(CondBlock);
1956 LoopStack.pop();
1957 // Emit the fall-through block.
1958 EmitBlock(LoopExit.getBlock());
1959
1960 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001961 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1962 if (!DynamicOrOrdered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001963 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00001964 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00001965 };
1966 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001967}
1968
1969void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001970 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001971 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001972 const OMPLoopArguments &LoopArgs,
1973 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001974 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001975
1976 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001977 const bool DynamicOrOrdered =
1978 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001979
1980 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001981 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001982 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001983 "static non-chunked schedule does not need outer loop");
1984
1985 // Emit outer loop.
1986 //
1987 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1988 // When schedule(dynamic,chunk_size) is specified, the iterations are
1989 // distributed to threads in the team in chunks as the threads request them.
1990 // Each thread executes a chunk of iterations, then requests another chunk,
1991 // until no chunks remain to be distributed. Each chunk contains chunk_size
1992 // iterations, except for the last chunk to be distributed, which may have
1993 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1994 //
1995 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1996 // to threads in the team in chunks as the executing threads request them.
1997 // Each thread executes a chunk of iterations, then requests another chunk,
1998 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1999 // each chunk is proportional to the number of unassigned iterations divided
2000 // by the number of threads in the team, decreasing to 1. For a chunk_size
2001 // with value k (greater than 1), the size of each chunk is determined in the
2002 // same way, with the restriction that the chunks do not contain fewer than k
2003 // iterations (except for the last chunk to be assigned, which may have fewer
2004 // than k iterations).
2005 //
2006 // When schedule(auto) is specified, the decision regarding scheduling is
2007 // delegated to the compiler and/or runtime system. The programmer gives the
2008 // implementation the freedom to choose any possible mapping of iterations to
2009 // threads in the team.
2010 //
2011 // When schedule(runtime) is specified, the decision regarding scheduling is
2012 // deferred until run time, and the schedule and chunk size are taken from the
2013 // run-sched-var ICV. If the ICV is set to auto, the schedule is
2014 // implementation defined
2015 //
2016 // while(__kmpc_dispatch_next(&LB, &UB)) {
2017 // idx = LB;
2018 // while (idx <= UB) { BODY; ++idx;
2019 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
2020 // } // inner loop
2021 // }
2022 //
2023 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2024 // When schedule(static, chunk_size) is specified, iterations are divided into
2025 // chunks of size chunk_size, and the chunks are assigned to the threads in
2026 // the team in a round-robin fashion in the order of the thread number.
2027 //
2028 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
2029 // while (idx <= UB) { BODY; ++idx; } // inner loop
2030 // LB = LB + ST;
2031 // UB = UB + ST;
2032 // }
2033 //
2034
2035 const Expr *IVExpr = S.getIterationVariable();
2036 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2037 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2038
2039 if (DynamicOrOrdered) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002040 const std::pair<llvm::Value *, llvm::Value *> DispatchBounds =
2041 CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002042 llvm::Value *LBVal = DispatchBounds.first;
2043 llvm::Value *UBVal = DispatchBounds.second;
2044 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
2045 LoopArgs.Chunk};
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002046 RT.emitForDispatchInit(*this, S.getBeginLoc(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002047 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002048 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002049 CGOpenMPRuntime::StaticRTInput StaticInit(
2050 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
2051 LoopArgs.ST, LoopArgs.Chunk);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002052 RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(),
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002053 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002054 }
2055
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002056 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
2057 const unsigned IVSize,
2058 const bool IVSigned) {
2059 if (Ordered) {
2060 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
2061 IVSigned);
2062 }
2063 };
2064
2065 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
2066 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
2067 OuterLoopArgs.IncExpr = S.getInc();
2068 OuterLoopArgs.Init = S.getInit();
2069 OuterLoopArgs.Cond = S.getCond();
2070 OuterLoopArgs.NextLB = S.getNextLowerBound();
2071 OuterLoopArgs.NextUB = S.getNextUpperBound();
2072 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
2073 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002074}
2075
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002076static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
2077 const unsigned IVSize, const bool IVSigned) {}
2078
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002079void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002080 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
2081 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
2082 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002083
Alexey Bataevddf3db92018-04-13 17:31:06 +00002084 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002085
2086 // Emit outer loop.
2087 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
2088 // dynamic
2089 //
2090
2091 const Expr *IVExpr = S.getIterationVariable();
2092 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2093 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2094
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002095 CGOpenMPRuntime::StaticRTInput StaticInit(
2096 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
2097 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002098 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002099
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002100 // for combined 'distribute' and 'for' the increment expression of distribute
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002101 // is stored in DistInc. For 'distribute' alone, it is in Inc.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002102 Expr *IncExpr;
2103 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
2104 IncExpr = S.getDistInc();
2105 else
2106 IncExpr = S.getInc();
2107
2108 // this routine is shared by 'omp distribute parallel for' and
2109 // 'omp distribute': select the right EUB expression depending on the
2110 // directive
2111 OMPLoopArguments OuterLoopArgs;
2112 OuterLoopArgs.LB = LoopArgs.LB;
2113 OuterLoopArgs.UB = LoopArgs.UB;
2114 OuterLoopArgs.ST = LoopArgs.ST;
2115 OuterLoopArgs.IL = LoopArgs.IL;
2116 OuterLoopArgs.Chunk = LoopArgs.Chunk;
2117 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2118 ? S.getCombinedEnsureUpperBound()
2119 : S.getEnsureUpperBound();
2120 OuterLoopArgs.IncExpr = IncExpr;
2121 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2122 ? S.getCombinedInit()
2123 : S.getInit();
2124 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2125 ? S.getCombinedCond()
2126 : S.getCond();
2127 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2128 ? S.getCombinedNextLowerBound()
2129 : S.getNextLowerBound();
2130 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2131 ? S.getCombinedNextUpperBound()
2132 : S.getNextUpperBound();
2133
2134 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
2135 LoopScope, OuterLoopArgs, CodeGenLoopContent,
2136 emitEmptyOrdered);
2137}
2138
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002139static std::pair<LValue, LValue>
2140emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
2141 const OMPExecutableDirective &S) {
2142 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2143 LValue LB =
2144 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2145 LValue UB =
2146 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2147
2148 // When composing 'distribute' with 'for' (e.g. as in 'distribute
2149 // parallel for') we need to use the 'distribute'
2150 // chunk lower and upper bounds rather than the whole loop iteration
2151 // space. These are parameters to the outlined function for 'parallel'
2152 // and we copy the bounds of the previous schedule into the
2153 // the current ones.
2154 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
2155 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002156 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
2157 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002158 PrevLBVal = CGF.EmitScalarConversion(
2159 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002160 LS.getIterationVariable()->getType(),
2161 LS.getPrevLowerBoundVariable()->getExprLoc());
2162 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
2163 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002164 PrevUBVal = CGF.EmitScalarConversion(
2165 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002166 LS.getIterationVariable()->getType(),
2167 LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002168
2169 CGF.EmitStoreOfScalar(PrevLBVal, LB);
2170 CGF.EmitStoreOfScalar(PrevUBVal, UB);
2171
2172 return {LB, UB};
2173}
2174
2175/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
2176/// we need to use the LB and UB expressions generated by the worksharing
2177/// code generation support, whereas in non combined situations we would
2178/// just emit 0 and the LastIteration expression
2179/// This function is necessary due to the difference of the LB and UB
2180/// types for the RT emission routines for 'for_static_init' and
2181/// 'for_dispatch_init'
2182static std::pair<llvm::Value *, llvm::Value *>
2183emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
2184 const OMPExecutableDirective &S,
2185 Address LB, Address UB) {
2186 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2187 const Expr *IVExpr = LS.getIterationVariable();
2188 // when implementing a dynamic schedule for a 'for' combined with a
2189 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
2190 // is not normalized as each team only executes its own assigned
2191 // distribute chunk
2192 QualType IteratorTy = IVExpr->getType();
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002193 llvm::Value *LBVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002194 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002195 llvm::Value *UBVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002196 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002197 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00002198}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002199
2200static void emitDistributeParallelForDistributeInnerBoundParams(
2201 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2202 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2203 const auto &Dir = cast<OMPLoopDirective>(S);
2204 LValue LB =
2205 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
Alexey Bataevddf3db92018-04-13 17:31:06 +00002206 llvm::Value *LBCast = CGF.Builder.CreateIntCast(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002207 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2208 CapturedVars.push_back(LBCast);
2209 LValue UB =
2210 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2211
Alexey Bataevddf3db92018-04-13 17:31:06 +00002212 llvm::Value *UBCast = CGF.Builder.CreateIntCast(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002213 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2214 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00002215}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002216
2217static void
2218emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2219 const OMPLoopDirective &S,
2220 CodeGenFunction::JumpDest LoopExit) {
2221 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00002222 PrePostActionTy &Action) {
2223 Action.Enter(CGF);
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002224 bool HasCancel = false;
2225 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2226 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2227 HasCancel = D->hasCancel();
2228 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2229 HasCancel = D->hasCancel();
Alexey Bataev16e79882017-11-22 21:12:03 +00002230 else if (const auto *D =
2231 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2232 HasCancel = D->hasCancel();
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002233 }
2234 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2235 HasCancel);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002236 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2237 emitDistributeParallelForInnerBounds,
2238 emitDistributeParallelForDispatchBounds);
2239 };
2240
2241 emitCommonOMPParallelDirective(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002242 CGF, S,
2243 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2244 CGInlinedWorksharingLoop,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002245 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002246}
2247
Carlo Bertolli9925f152016-06-27 14:55:37 +00002248void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2249 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002250 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2251 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2252 S.getDistInc());
2253 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002254 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev10a54312017-11-27 16:54:08 +00002255 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002256}
2257
Kelvin Li4a39add2016-07-05 05:00:15 +00002258void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2259 const OMPDistributeParallelForSimdDirective &S) {
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002260 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2261 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2262 S.getDistInc());
2263 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002264 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002265 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Kelvin Li4a39add2016-07-05 05:00:15 +00002266}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002267
2268void CodeGenFunction::EmitOMPDistributeSimdDirective(
2269 const OMPDistributeSimdDirective &S) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00002270 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2271 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2272 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002273 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev617db5f2017-12-04 15:38:33 +00002274 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002275}
2276
Alexey Bataevf8365372017-11-17 17:57:25 +00002277void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2278 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2279 // Emit SPMD target parallel for region as a standalone region.
2280 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2281 emitOMPSimdRegion(CGF, S, Action);
2282 };
2283 llvm::Function *Fn;
2284 llvm::Constant *Addr;
2285 // Emit target region as a standalone region.
2286 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2287 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2288 assert(Fn && Addr && "Target device function emission failed.");
2289}
2290
Kelvin Li986330c2016-07-20 22:57:10 +00002291void CodeGenFunction::EmitOMPTargetSimdDirective(
2292 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002293 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2294 emitOMPSimdRegion(CGF, S, Action);
2295 };
2296 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002297}
2298
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002299namespace {
2300 struct ScheduleKindModifiersTy {
2301 OpenMPScheduleClauseKind Kind;
2302 OpenMPScheduleClauseModifier M1;
2303 OpenMPScheduleClauseModifier M2;
2304 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2305 OpenMPScheduleClauseModifier M1,
2306 OpenMPScheduleClauseModifier M2)
2307 : Kind(Kind), M1(M1), M2(M2) {}
2308 };
2309} // namespace
2310
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002311bool CodeGenFunction::EmitOMPWorksharingLoop(
2312 const OMPLoopDirective &S, Expr *EUB,
2313 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2314 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002315 // Emit the loop iteration variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002316 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2317 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
Alexander Musmanc6388682014-12-15 07:07:06 +00002318 EmitVarDecl(*IVDecl);
2319
2320 // Emit the iterations count variable.
2321 // If it is not a variable, Sema decided to calculate iterations count on each
2322 // iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00002323 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002324 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2325 // Emit calculation of the iterations count.
2326 EmitIgnoredExpr(S.getCalcLastIteration());
2327 }
2328
Alexey Bataevddf3db92018-04-13 17:31:06 +00002329 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Alexander Musmanc6388682014-12-15 07:07:06 +00002330
Alexey Bataev38e89532015-04-16 04:54:05 +00002331 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002332 // Check pre-condition.
2333 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002334 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002335 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002336 // If the condition constant folds and can be elided, avoid emitting the
2337 // whole loop.
2338 bool CondConstant;
2339 llvm::BasicBlock *ContBlock = nullptr;
2340 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2341 if (!CondConstant)
2342 return false;
2343 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002344 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
Alexey Bataev62dbb972015-04-22 11:59:37 +00002345 ContBlock = createBasicBlock("omp.precond.end");
2346 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002347 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002348 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002349 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002350 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002351
Alexey Bataevea33dee2018-02-15 23:39:43 +00002352 RunCleanupsScope DoacrossCleanupScope(*this);
Alexey Bataev8b427062016-05-25 12:36:08 +00002353 bool Ordered = false;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002354 if (const auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
Alexey Bataev8b427062016-05-25 12:36:08 +00002355 if (OrderedClause->getNumForLoops())
Alexey Bataevf138fda2018-08-13 19:04:24 +00002356 RT.emitDoacrossInit(*this, S, OrderedClause->getLoopNumIterations());
Alexey Bataev8b427062016-05-25 12:36:08 +00002357 else
2358 Ordered = true;
2359 }
2360
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002361 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002362 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002363 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002364 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002365
2366 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2367 LValue LB = Bounds.first;
2368 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002369 LValue ST =
2370 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2371 LValue IL =
2372 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2373
Alexander Musmanc6388682014-12-15 07:07:06 +00002374 // Emit 'then' code.
2375 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002376 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002377 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002378 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002379 // initialization of firstprivate variables and post-update of
2380 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002381 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002382 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002383 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002384 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002385 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002386 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002387 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002388 EmitOMPPrivateLoopCounters(S, LoopScope);
2389 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002390 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00002391 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2392 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002393
2394 // Detect the loop schedule kind and chunk.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002395 const Expr *ChunkExpr = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002396 OpenMPScheduleTy ScheduleKind;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002397 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002398 ScheduleKind.Schedule = C->getScheduleKind();
2399 ScheduleKind.M1 = C->getFirstScheduleModifier();
2400 ScheduleKind.M2 = C->getSecondScheduleModifier();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002401 ChunkExpr = C->getChunkSize();
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00002402 } else {
2403 // Default behaviour for schedule clause.
2404 CGM.getOpenMPRuntime().getDefaultScheduleAndChunk(
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002405 *this, S, ScheduleKind.Schedule, ChunkExpr);
2406 }
2407 bool HasChunkSizeOne = false;
2408 llvm::Value *Chunk = nullptr;
2409 if (ChunkExpr) {
2410 Chunk = EmitScalarExpr(ChunkExpr);
2411 Chunk = EmitScalarConversion(Chunk, ChunkExpr->getType(),
2412 S.getIterationVariable()->getType(),
2413 S.getBeginLoc());
Fangrui Song407659a2018-11-30 23:41:18 +00002414 Expr::EvalResult Result;
2415 if (ChunkExpr->EvaluateAsInt(Result, getContext())) {
2416 llvm::APSInt EvaluatedChunk = Result.Val.getInt();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002417 HasChunkSizeOne = (EvaluatedChunk.getLimitedValue() == 1);
Fangrui Song407659a2018-11-30 23:41:18 +00002418 }
Alexey Bataev3392d762016-02-16 11:18:12 +00002419 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002420 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2421 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002422 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2423 // If the static schedule kind is specified or if the ordered clause is
2424 // specified, and if no monotonic modifier is specified, the effect will
2425 // be as if the monotonic modifier was specified.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002426 bool StaticChunkedOne = RT.isStaticChunked(ScheduleKind.Schedule,
2427 /* Chunked */ Chunk != nullptr) && HasChunkSizeOne &&
2428 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
2429 if ((RT.isStaticNonchunked(ScheduleKind.Schedule,
2430 /* Chunked */ Chunk != nullptr) ||
2431 StaticChunkedOne) &&
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002432 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002433 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2434 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002435 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2436 // When no chunk_size is specified, the iteration space is divided into
2437 // chunks that are approximately equal in size, and at most one chunk is
2438 // distributed to each thread. Note that the size of the chunks is
2439 // unspecified in this case.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002440 CGOpenMPRuntime::StaticRTInput StaticInit(
2441 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002442 UB.getAddress(), ST.getAddress(),
2443 StaticChunkedOne ? Chunk : nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002444 RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(),
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002445 ScheduleKind, StaticInit);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002446 JumpDest LoopExit =
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002447 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002448 // UB = min(UB, GlobalUB);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002449 if (!StaticChunkedOne)
2450 EmitIgnoredExpr(S.getEnsureUpperBound());
Alexander Musmanc6388682014-12-15 07:07:06 +00002451 // IV = LB;
2452 EmitIgnoredExpr(S.getInit());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00002453 // For unchunked static schedule generate:
2454 //
2455 // while (idx <= UB) {
2456 // BODY;
2457 // ++idx;
2458 // }
2459 //
2460 // For static schedule with chunk one:
2461 //
2462 // while (IV <= PrevUB) {
2463 // BODY;
2464 // IV += ST;
2465 // }
2466 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
2467 StaticChunkedOne ? S.getCombinedParForInDistCond() : S.getCond(),
2468 StaticChunkedOne ? S.getDistInc() : S.getInc(),
2469 [&S, LoopExit](CodeGenFunction &CGF) {
2470 CGF.EmitOMPLoopBody(S, LoopExit);
2471 CGF.EmitStopPoint(&S);
2472 },
2473 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002474 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002475 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002476 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002477 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00002478 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002479 };
2480 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002481 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002482 const bool IsMonotonic =
2483 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2484 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2485 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2486 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002487 // Emit the outer loop, which requests its work chunk [LB..UB] from
2488 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002489 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2490 ST.getAddress(), IL.getAddress(),
2491 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002492 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002493 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002494 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002495 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002496 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
2497 return CGF.Builder.CreateIsNotNull(
2498 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
2499 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002500 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002501 EmitOMPReductionClauseFinal(
2502 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2503 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2504 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002505 // Emit post-update of the reduction variables if IsLastIter != 0.
2506 emitPostUpdateForReductionClause(
Alexey Bataevddf3db92018-04-13 17:31:06 +00002507 *this, S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataev61205072016-03-02 04:57:40 +00002508 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002509 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataev61205072016-03-02 04:57:40 +00002510 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002511 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2512 if (HasLastprivateClause)
2513 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002514 S, isOpenMPSimdDirective(S.getDirectiveKind()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002515 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002516 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00002517 EmitOMPLinearClauseFinal(S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataevef549a82016-03-09 09:49:09 +00002518 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002519 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataevef549a82016-03-09 09:49:09 +00002520 });
Alexey Bataevea33dee2018-02-15 23:39:43 +00002521 DoacrossCleanupScope.ForceCleanup();
Alexander Musmanc6388682014-12-15 07:07:06 +00002522 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002523 if (ContBlock) {
2524 EmitBranch(ContBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002525 EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002526 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002527 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002528 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002529}
2530
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002531/// The following two functions generate expressions for the loop lower
2532/// and upper bounds in case of static and dynamic (dispatch) schedule
2533/// of the associated 'for' or 'distribute' loop.
2534static std::pair<LValue, LValue>
2535emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002536 const auto &LS = cast<OMPLoopDirective>(S);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002537 LValue LB =
2538 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2539 LValue UB =
2540 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2541 return {LB, UB};
2542}
2543
2544/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2545/// consider the lower and upper bound expressions generated by the
2546/// worksharing loop support, but we use 0 and the iteration space size as
2547/// constants
2548static std::pair<llvm::Value *, llvm::Value *>
2549emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2550 Address LB, Address UB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002551 const auto &LS = cast<OMPLoopDirective>(S);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002552 const Expr *IVExpr = LS.getIterationVariable();
2553 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2554 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2555 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2556 return {LBVal, UBVal};
2557}
2558
Alexander Musmanc6388682014-12-15 07:07:06 +00002559void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002560 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002561 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2562 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002563 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002564 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2565 emitForLoopBounds,
2566 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002567 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002568 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002569 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002570 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2571 S.hasCancel());
2572 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002573
2574 // Emit an implicit barrier at the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002575 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002576 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002577}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002578
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002579void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002580 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002581 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2582 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002583 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2584 emitForLoopBounds,
2585 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002586 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002587 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002588 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002589 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2590 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002591
2592 // Emit an implicit barrier at the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002593 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002594 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002595}
2596
Alexey Bataev2df54a02015-03-12 08:53:29 +00002597static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2598 const Twine &Name,
2599 llvm::Value *Init = nullptr) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002600 LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002601 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002602 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002603 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002604}
2605
Alexey Bataev3392d762016-02-16 11:18:12 +00002606void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002607 const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
2608 const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002609 bool HasLastprivates = false;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002610 auto &&CodeGen = [&S, CapturedStmt, CS,
2611 &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) {
2612 ASTContext &C = CGF.getContext();
2613 QualType KmpInt32Ty =
2614 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002615 // Emit helper vars inits.
2616 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2617 CGF.Builder.getInt32(0));
Alexey Bataevddf3db92018-04-13 17:31:06 +00002618 llvm::ConstantInt *GlobalUBVal = CS != nullptr
2619 ? CGF.Builder.getInt32(CS->size() - 1)
2620 : CGF.Builder.getInt32(0);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002621 LValue UB =
2622 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2623 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2624 CGF.Builder.getInt32(1));
2625 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2626 CGF.Builder.getInt32(0));
2627 // Loop counter.
2628 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002629 OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002630 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002631 OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002632 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2633 // Generate condition for loop.
2634 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002635 OK_Ordinary, S.getBeginLoc(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002636 // Increment for loop counter.
2637 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002638 S.getBeginLoc(), true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002639 auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002640 // Iterate through all sections and emit a switch construct:
2641 // switch (IV) {
2642 // case 0:
2643 // <SectionStmt[0]>;
2644 // break;
2645 // ...
2646 // case <NumSection> - 1:
2647 // <SectionStmt[<NumSection> - 1]>;
2648 // break;
2649 // }
2650 // .omp.sections.exit:
Alexey Bataevddf3db92018-04-13 17:31:06 +00002651 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2652 llvm::SwitchInst *SwitchStmt =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002653 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002654 ExitBB, CS == nullptr ? 1 : CS->size());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002655 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002656 unsigned CaseNumber = 0;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002657 for (const Stmt *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002658 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2659 CGF.EmitBlock(CaseBB);
2660 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002661 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002662 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002663 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002664 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002665 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002666 llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case");
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002667 CGF.EmitBlock(CaseBB);
2668 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002669 CGF.EmitStmt(CapturedStmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002670 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002671 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002672 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002673 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002674
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002675 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2676 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002677 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002678 // initialization of firstprivate variables and post-update of lastprivate
2679 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002680 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002681 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002682 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002683 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002684 CGF.EmitOMPPrivateClause(S, LoopScope);
2685 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2686 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2687 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00002688 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2689 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002690
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002691 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002692 OpenMPScheduleTy ScheduleKind;
2693 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002694 CGOpenMPRuntime::StaticRTInput StaticInit(
2695 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2696 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002697 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002698 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002699 // UB = min(UB, GlobalUB);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002700 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc());
Alexey Bataevddf3db92018-04-13 17:31:06 +00002701 llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect(
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002702 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2703 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2704 // IV = LB;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002705 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002706 // while (idx <= UB) { BODY; ++idx; }
2707 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2708 [](CodeGenFunction &) {});
2709 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002710 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002711 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00002712 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002713 };
2714 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002715 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002716 // Emit post-update of the reduction variables if IsLastIter != 0.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002717 emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) {
2718 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002719 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataevddf3db92018-04-13 17:31:06 +00002720 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002721
2722 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2723 if (HasLastprivates)
2724 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002725 S, /*NoFinals=*/false,
2726 CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002727 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002728 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002729
2730 bool HasCancel = false;
2731 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2732 HasCancel = OSD->hasCancel();
2733 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2734 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002735 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002736 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2737 HasCancel);
2738 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2739 // clause. Otherwise the barrier will be generated by the codegen for the
2740 // directive.
2741 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002742 // Emit implicit barrier to synchronize threads and avoid data races on
2743 // initialization of firstprivate variables.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002744 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002745 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002746 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002747}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002748
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002749void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002750 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002751 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002752 EmitSections(S);
2753 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002754 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002755 if (!S.getSingleClause<OMPNowaitClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002756 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
Alexey Bataev3392d762016-02-16 11:18:12 +00002757 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002758 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002759}
2760
2761void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002762 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002763 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002764 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002765 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002766 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2767 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002768}
2769
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002770void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002771 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002772 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002773 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002774 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002775 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002776 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002777 // Build a list of copyprivate variables along with helper expressions
2778 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002779 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002780 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002781 DestExprs.append(C->destination_exprs().begin(),
2782 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002783 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002784 AssignmentOps.append(C->assignment_ops().begin(),
2785 C->assignment_ops().end());
2786 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002787 // Emit code for 'single' region along with 'copyprivate' clauses
2788 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2789 Action.Enter(CGF);
2790 OMPPrivateScope SingleScope(CGF);
2791 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2792 CGF.EmitOMPPrivateClause(S, SingleScope);
2793 (void)SingleScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00002794 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002795 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002796 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002797 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002798 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(),
Alexey Bataev3392d762016-02-16 11:18:12 +00002799 CopyprivateVars, DestExprs,
2800 SrcExprs, AssignmentOps);
2801 }
2802 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2803 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002804 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002805 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002806 *this, S.getBeginLoc(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002807 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002808 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002809}
2810
Alexey Bataev8d690652014-12-04 07:23:53 +00002811void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002812 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2813 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002814 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002815 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002816 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002817 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
Alexander Musman80c22892014-07-17 08:54:58 +00002818}
2819
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002820void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002821 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2822 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002823 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002824 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00002825 const Expr *Hint = nullptr;
2826 if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
Alexey Bataevfc57d162015-12-15 10:55:09 +00002827 Hint = HintClause->getHint();
Alexey Bataev475a7442018-01-12 19:39:11 +00002828 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002829 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2830 S.getDirectiveName().getAsString(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002831 CodeGen, S.getBeginLoc(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002832}
2833
Alexey Bataev671605e2015-04-13 05:28:11 +00002834void CodeGenFunction::EmitOMPParallelForDirective(
2835 const OMPParallelForDirective &S) {
2836 // Emit directive as a combined directive that consists of two implicit
2837 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00002838 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2839 Action.Enter(CGF);
Alexey Bataev957d8562016-11-17 15:12:05 +00002840 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002841 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2842 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002843 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002844 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2845 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002846}
2847
Alexander Musmane4e893b2014-09-23 09:33:00 +00002848void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002849 const OMPParallelForSimdDirective &S) {
2850 // Emit directive as a combined directive that consists of two implicit
2851 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00002852 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2853 Action.Enter(CGF);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002854 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2855 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002856 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002857 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2858 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002859}
2860
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002861void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002862 const OMPParallelSectionsDirective &S) {
2863 // Emit directive as a combined directive that consists of two implicit
2864 // directives: 'parallel' with 'sections' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00002865 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2866 Action.Enter(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002867 CGF.EmitSections(S);
2868 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002869 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2870 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002871}
2872
Alexey Bataev475a7442018-01-12 19:39:11 +00002873void CodeGenFunction::EmitOMPTaskBasedDirective(
2874 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
2875 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
2876 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002877 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00002878 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002879 auto I = CS->getCapturedDecl()->param_begin();
2880 auto PartId = std::next(I);
2881 auto TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002882 // Check if the task is final
2883 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2884 // If the condition constant folds and can be elided, try to avoid emitting
2885 // the condition and the dead arm of the if/else.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002886 const Expr *Cond = Clause->getCondition();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002887 bool CondConstant;
2888 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2889 Data.Final.setInt(CondConstant);
2890 else
2891 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2892 } else {
2893 // By default the task is not final.
2894 Data.Final.setInt(/*IntVal=*/false);
2895 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002896 // Check if the task has 'priority' clause.
2897 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002898 const Expr *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002899 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002900 Data.Priority.setPointer(EmitScalarConversion(
2901 EmitScalarExpr(Prio), Prio->getType(),
2902 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2903 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002904 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002905 // The first function argument for tasks is a thread id, the second one is a
2906 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002907 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2908 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002909 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002910 auto IRef = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002911 for (const Expr *IInit : C->private_copies()) {
2912 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002913 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002914 Data.PrivateVars.push_back(*IRef);
2915 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002916 }
2917 ++IRef;
2918 }
2919 }
2920 EmittedAsPrivate.clear();
2921 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002922 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002923 auto IRef = C->varlist_begin();
2924 auto IElemInitRef = C->inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002925 for (const Expr *IInit : C->private_copies()) {
2926 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002927 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002928 Data.FirstprivateVars.push_back(*IRef);
2929 Data.FirstprivateCopies.push_back(IInit);
2930 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002931 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002932 ++IRef;
2933 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002934 }
2935 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002936 // Get list of lastprivate variables (for taskloops).
2937 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2938 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2939 auto IRef = C->varlist_begin();
2940 auto ID = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002941 for (const Expr *IInit : C->private_copies()) {
2942 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00002943 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2944 Data.LastprivateVars.push_back(*IRef);
2945 Data.LastprivateCopies.push_back(IInit);
2946 }
2947 LastprivateDstsOrigs.insert(
2948 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2949 cast<DeclRefExpr>(*IRef)});
2950 ++IRef;
2951 ++ID;
2952 }
2953 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002954 SmallVector<const Expr *, 4> LHSs;
2955 SmallVector<const Expr *, 4> RHSs;
2956 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2957 auto IPriv = C->privates().begin();
2958 auto IRed = C->reduction_ops().begin();
2959 auto ILHS = C->lhs_exprs().begin();
2960 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002961 for (const Expr *Ref : C->varlists()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002962 Data.ReductionVars.emplace_back(Ref);
2963 Data.ReductionCopies.emplace_back(*IPriv);
2964 Data.ReductionOps.emplace_back(*IRed);
2965 LHSs.emplace_back(*ILHS);
2966 RHSs.emplace_back(*IRHS);
2967 std::advance(IPriv, 1);
2968 std::advance(IRed, 1);
2969 std::advance(ILHS, 1);
2970 std::advance(IRHS, 1);
2971 }
2972 }
2973 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002974 *this, S.getBeginLoc(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002975 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002976 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
Alexey Bataevddf3db92018-04-13 17:31:06 +00002977 for (const Expr *IRef : C->varlists())
Alexey Bataev43a919f2018-04-13 17:48:43 +00002978 Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
Alexey Bataev475a7442018-01-12 19:39:11 +00002979 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
2980 CapturedRegion](CodeGenFunction &CGF,
2981 PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002982 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002983 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002984 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2985 !Data.LastprivateVars.empty()) {
James Y Knight9871db02019-02-05 16:42:33 +00002986 llvm::FunctionType *CopyFnTy = llvm::FunctionType::get(
2987 CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true);
Alexey Bataev3c595a62017-08-14 15:01:03 +00002988 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00002989 llvm::Value *CopyFn = CGF.Builder.CreateLoad(
2990 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
2991 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
2992 CS->getCapturedDecl()->getParam(PrivatesParam)));
Alexey Bataev48591dd2016-04-20 04:01:36 +00002993 // Map privates.
2994 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2995 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2996 CallArgs.push_back(PrivatesPtr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002997 for (const Expr *E : Data.PrivateVars) {
2998 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev48591dd2016-04-20 04:01:36 +00002999 Address PrivatePtr = CGF.CreateMemTemp(
3000 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003001 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003002 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003003 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003004 for (const Expr *E : Data.FirstprivateVars) {
3005 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev48591dd2016-04-20 04:01:36 +00003006 Address PrivatePtr =
3007 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3008 ".firstpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003009 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003010 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003011 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003012 for (const Expr *E : Data.LastprivateVars) {
3013 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003014 Address PrivatePtr =
3015 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3016 ".lastpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003017 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003018 CallArgs.push_back(PrivatePtr.getPointer());
3019 }
James Y Knight9871db02019-02-05 16:42:33 +00003020 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3021 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003022 for (const auto &Pair : LastprivateDstsOrigs) {
3023 const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003024 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(OrigVD),
3025 /*RefersToEnclosingVariableOrCapture=*/
3026 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
3027 Pair.second->getType(), VK_LValue,
3028 Pair.second->getExprLoc());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003029 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
3030 return CGF.EmitLValue(&DRE).getAddress();
3031 });
3032 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003033 for (const auto &Pair : PrivatePtrs) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003034 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3035 CGF.getContext().getDeclAlign(Pair.first));
3036 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3037 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003038 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003039 if (Data.Reductions) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003040 OMPLexicalScope LexScope(CGF, S, CapturedRegion);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003041 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
3042 Data.ReductionOps);
3043 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
3044 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
3045 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
3046 RedCG.emitSharedLValue(CGF, Cnt);
3047 RedCG.emitAggregateType(CGF, Cnt);
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003048 // FIXME: This must removed once the runtime library is fixed.
3049 // Emit required threadprivate variables for
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003050 // initializer/combiner/finalizer.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003051 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003052 RedCG, Cnt);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003053 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003054 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003055 Replacement =
3056 Address(CGF.EmitScalarConversion(
3057 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
3058 CGF.getContext().getPointerType(
3059 Data.ReductionCopies[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003060 Data.ReductionCopies[Cnt]->getExprLoc()),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003061 Replacement.getAlignment());
3062 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
3063 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
3064 [Replacement]() { return Replacement; });
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003065 }
3066 }
Alexey Bataev88202be2017-07-27 13:20:36 +00003067 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00003068 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00003069 SmallVector<const Expr *, 4> InRedVars;
3070 SmallVector<const Expr *, 4> InRedPrivs;
3071 SmallVector<const Expr *, 4> InRedOps;
3072 SmallVector<const Expr *, 4> TaskgroupDescriptors;
3073 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
3074 auto IPriv = C->privates().begin();
3075 auto IRed = C->reduction_ops().begin();
3076 auto ITD = C->taskgroup_descriptors().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003077 for (const Expr *Ref : C->varlists()) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003078 InRedVars.emplace_back(Ref);
3079 InRedPrivs.emplace_back(*IPriv);
3080 InRedOps.emplace_back(*IRed);
3081 TaskgroupDescriptors.emplace_back(*ITD);
3082 std::advance(IPriv, 1);
3083 std::advance(IRed, 1);
3084 std::advance(ITD, 1);
3085 }
3086 }
3087 // Privatize in_reduction items here, because taskgroup descriptors must be
3088 // privatized earlier.
3089 OMPPrivateScope InRedScope(CGF);
3090 if (!InRedVars.empty()) {
3091 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
3092 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
3093 RedCG.emitSharedLValue(CGF, Cnt);
3094 RedCG.emitAggregateType(CGF, Cnt);
3095 // The taskgroup descriptor variable is always implicit firstprivate and
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003096 // privatized already during processing of the firstprivates.
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003097 // FIXME: This must removed once the runtime library is fixed.
3098 // Emit required threadprivate variables for
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003099 // initializer/combiner/finalizer.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003100 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00003101 RedCG, Cnt);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003102 llvm::Value *ReductionsPtr =
3103 CGF.EmitLoadOfScalar(CGF.EmitLValue(TaskgroupDescriptors[Cnt]),
3104 TaskgroupDescriptors[Cnt]->getExprLoc());
Alexey Bataev88202be2017-07-27 13:20:36 +00003105 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003106 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
Alexey Bataev88202be2017-07-27 13:20:36 +00003107 Replacement = Address(
3108 CGF.EmitScalarConversion(
3109 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
3110 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003111 InRedPrivs[Cnt]->getExprLoc()),
Alexey Bataev88202be2017-07-27 13:20:36 +00003112 Replacement.getAlignment());
3113 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
3114 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
3115 [Replacement]() { return Replacement; });
Alexey Bataev88202be2017-07-27 13:20:36 +00003116 }
3117 }
3118 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00003119
3120 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00003121 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003122 };
James Y Knight9871db02019-02-05 16:42:33 +00003123 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00003124 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
3125 Data.NumberOfParts);
3126 OMPLexicalScope Scope(*this, S);
3127 TaskGen(*this, OutlinedFn, Data);
3128}
3129
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003130static ImplicitParamDecl *
3131createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003132 QualType Ty, CapturedDecl *CD,
3133 SourceLocation Loc) {
3134 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3135 ImplicitParamDecl::Other);
3136 auto *OrigRef = DeclRefExpr::Create(
3137 C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
3138 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
3139 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3140 ImplicitParamDecl::Other);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003141 auto *PrivateRef = DeclRefExpr::Create(
3142 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003143 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003144 QualType ElemType = C.getBaseElementType(Ty);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003145 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
3146 ImplicitParamDecl::Other);
3147 auto *InitRef = DeclRefExpr::Create(
3148 C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
3149 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003150 PrivateVD->setInitStyle(VarDecl::CInit);
3151 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
3152 InitRef, /*BasePath=*/nullptr,
3153 VK_RValue));
3154 Data.FirstprivateVars.emplace_back(OrigRef);
3155 Data.FirstprivateCopies.emplace_back(PrivateRef);
3156 Data.FirstprivateInits.emplace_back(InitRef);
3157 return OrigVD;
3158}
3159
3160void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
3161 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
3162 OMPTargetDataInfo &InputInfo) {
3163 // Emit outlined function for task construct.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003164 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
3165 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3166 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3167 auto I = CS->getCapturedDecl()->param_begin();
3168 auto PartId = std::next(I);
3169 auto TaskT = std::next(I, 4);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003170 OMPTaskDataTy Data;
3171 // The task is not final.
3172 Data.Final.setInt(/*IntVal=*/false);
3173 // Get list of firstprivate variables.
3174 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3175 auto IRef = C->varlist_begin();
3176 auto IElemInitRef = C->inits().begin();
3177 for (auto *IInit : C->private_copies()) {
3178 Data.FirstprivateVars.push_back(*IRef);
3179 Data.FirstprivateCopies.push_back(IInit);
3180 Data.FirstprivateInits.push_back(*IElemInitRef);
3181 ++IRef;
3182 ++IElemInitRef;
3183 }
3184 }
3185 OMPPrivateScope TargetScope(*this);
3186 VarDecl *BPVD = nullptr;
3187 VarDecl *PVD = nullptr;
3188 VarDecl *SVD = nullptr;
3189 if (InputInfo.NumberOfTargetItems > 0) {
3190 auto *CD = CapturedDecl::Create(
3191 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
3192 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
3193 QualType BaseAndPointersType = getContext().getConstantArrayType(
Richard Smith772e2662019-10-04 01:25:59 +00003194 getContext().VoidPtrTy, ArrSize, nullptr, ArrayType::Normal,
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003195 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003196 BPVD = createImplicitFirstprivateForType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003197 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003198 PVD = createImplicitFirstprivateForType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003199 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003200 QualType SizesType = getContext().getConstantArrayType(
Alexey Bataeva90fc662019-06-25 16:00:43 +00003201 getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1),
Richard Smith772e2662019-10-04 01:25:59 +00003202 ArrSize, nullptr, ArrayType::Normal,
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003203 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003204 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003205 S.getBeginLoc());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003206 TargetScope.addPrivate(
3207 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
3208 TargetScope.addPrivate(PVD,
3209 [&InputInfo]() { return InputInfo.PointersArray; });
3210 TargetScope.addPrivate(SVD,
3211 [&InputInfo]() { return InputInfo.SizesArray; });
3212 }
3213 (void)TargetScope.Privatize();
3214 // Build list of dependences.
3215 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
Alexey Bataevddf3db92018-04-13 17:31:06 +00003216 for (const Expr *IRef : C->varlists())
Alexey Bataev43a919f2018-04-13 17:48:43 +00003217 Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003218 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3219 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3220 // Set proper addresses for generated private copies.
3221 OMPPrivateScope Scope(CGF);
3222 if (!Data.FirstprivateVars.empty()) {
James Y Knight9871db02019-02-05 16:42:33 +00003223 llvm::FunctionType *CopyFnTy = llvm::FunctionType::get(
3224 CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003225 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00003226 llvm::Value *CopyFn = CGF.Builder.CreateLoad(
3227 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
3228 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
3229 CS->getCapturedDecl()->getParam(PrivatesParam)));
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003230 // Map privates.
3231 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3232 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3233 CallArgs.push_back(PrivatesPtr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003234 for (const Expr *E : Data.FirstprivateVars) {
3235 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003236 Address PrivatePtr =
3237 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3238 ".firstpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003239 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003240 CallArgs.push_back(PrivatePtr.getPointer());
3241 }
James Y Knight9871db02019-02-05 16:42:33 +00003242 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3243 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003244 for (const auto &Pair : PrivatePtrs) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003245 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3246 CGF.getContext().getDeclAlign(Pair.first));
3247 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3248 }
3249 }
3250 // Privatize all private variables except for in_reduction items.
3251 (void)Scope.Privatize();
Alexey Bataev8451efa2018-01-15 19:06:12 +00003252 if (InputInfo.NumberOfTargetItems > 0) {
3253 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
James Y Knight751fe282019-02-09 22:22:28 +00003254 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003255 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
James Y Knight751fe282019-02-09 22:22:28 +00003256 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003257 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
James Y Knight751fe282019-02-09 22:22:28 +00003258 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003259 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003260
3261 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003262 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003263 BodyGen(CGF);
3264 };
James Y Knight9871db02019-02-05 16:42:33 +00003265 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003266 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3267 Data.NumberOfParts);
3268 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3269 IntegerLiteral IfCond(getContext(), TrueOrFalse,
3270 getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3271 SourceLocation());
3272
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003273 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn,
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003274 SharedsTy, CapturedStruct, &IfCond, Data);
3275}
3276
Alexey Bataev7292c292016-04-25 12:22:29 +00003277void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3278 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00003279 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003280 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3281 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00003282 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00003283 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3284 if (C->getNameModifier() == OMPD_unknown ||
3285 C->getNameModifier() == OMPD_task) {
3286 IfCond = C->getCondition();
3287 break;
3288 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003289 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003290
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003291 OMPTaskDataTy Data;
3292 // Check if we should emit tied or untied task.
3293 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003294 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3295 CGF.EmitStmt(CS->getCapturedStmt());
3296 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003297 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
James Y Knight9871db02019-02-05 16:42:33 +00003298 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003299 const OMPTaskDataTy &Data) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003300 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003301 SharedsTy, CapturedStruct, IfCond,
3302 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003303 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003304 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003305}
3306
Alexey Bataev9f797f32015-02-05 05:57:51 +00003307void CodeGenFunction::EmitOMPTaskyieldDirective(
3308 const OMPTaskyieldDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003309 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc());
Alexey Bataev68446b72014-07-18 07:47:19 +00003310}
3311
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003312void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003313 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003314}
3315
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003316void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003317 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc());
Alexey Bataev2df347a2014-07-18 10:17:07 +00003318}
3319
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003320void CodeGenFunction::EmitOMPTaskgroupDirective(
3321 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003322 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3323 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003324 if (const Expr *E = S.getReductionRef()) {
3325 SmallVector<const Expr *, 4> LHSs;
3326 SmallVector<const Expr *, 4> RHSs;
3327 OMPTaskDataTy Data;
3328 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3329 auto IPriv = C->privates().begin();
3330 auto IRed = C->reduction_ops().begin();
3331 auto ILHS = C->lhs_exprs().begin();
3332 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003333 for (const Expr *Ref : C->varlists()) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003334 Data.ReductionVars.emplace_back(Ref);
3335 Data.ReductionCopies.emplace_back(*IPriv);
3336 Data.ReductionOps.emplace_back(*IRed);
3337 LHSs.emplace_back(*ILHS);
3338 RHSs.emplace_back(*IRHS);
3339 std::advance(IPriv, 1);
3340 std::advance(IRed, 1);
3341 std::advance(ILHS, 1);
3342 std::advance(IRHS, 1);
3343 }
3344 }
3345 llvm::Value *ReductionDesc =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003346 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(),
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003347 LHSs, RHSs, Data);
3348 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3349 CGF.EmitVarDecl(*VD);
3350 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3351 /*Volatile=*/false, E->getType());
3352 }
Alexey Bataev475a7442018-01-12 19:39:11 +00003353 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003354 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003355 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003356 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003357}
3358
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003359void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003360 CGM.getOpenMPRuntime().emitFlush(
3361 *this,
3362 [&S]() -> ArrayRef<const Expr *> {
3363 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>())
3364 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3365 FlushClause->varlist_end());
3366 return llvm::None;
3367 }(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003368 S.getBeginLoc());
Alexey Bataev6125da92014-07-21 11:26:11 +00003369}
3370
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003371void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3372 const CodeGenLoopTy &CodeGenLoop,
3373 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003374 // Emit the loop iteration variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003375 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3376 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003377 EmitVarDecl(*IVDecl);
3378
3379 // Emit the iterations count variable.
3380 // If it is not a variable, Sema decided to calculate iterations count on each
3381 // iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00003382 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003383 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3384 // Emit calculation of the iterations count.
3385 EmitIgnoredExpr(S.getCalcLastIteration());
3386 }
3387
Alexey Bataevddf3db92018-04-13 17:31:06 +00003388 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003389
Carlo Bertolli962bb802017-01-03 18:24:42 +00003390 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003391 // Check pre-condition.
3392 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003393 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003394 // Skip the entire loop if we don't meet the precondition.
3395 // If the condition constant folds and can be elided, avoid emitting the
3396 // whole loop.
3397 bool CondConstant;
3398 llvm::BasicBlock *ContBlock = nullptr;
3399 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3400 if (!CondConstant)
3401 return;
3402 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003403 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003404 ContBlock = createBasicBlock("omp.precond.end");
3405 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3406 getProfileCount(&S));
3407 EmitBlock(ThenBlock);
3408 incrementProfileCounter(&S);
3409 }
3410
Alexey Bataev617db5f2017-12-04 15:38:33 +00003411 emitAlignedClause(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003412 // Emit 'then' code.
3413 {
3414 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003415
3416 LValue LB = EmitOMPHelperVar(
3417 *this, cast<DeclRefExpr>(
3418 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3419 ? S.getCombinedLowerBoundVariable()
3420 : S.getLowerBoundVariable())));
3421 LValue UB = EmitOMPHelperVar(
3422 *this, cast<DeclRefExpr>(
3423 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3424 ? S.getCombinedUpperBoundVariable()
3425 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003426 LValue ST =
3427 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3428 LValue IL =
3429 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3430
3431 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003432 if (EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003433 // Emit implicit barrier to synchronize threads and avoid data races
3434 // on initialization of firstprivate variables and post-update of
Carlo Bertolli962bb802017-01-03 18:24:42 +00003435 // lastprivate variables.
3436 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003437 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev617db5f2017-12-04 15:38:33 +00003438 /*ForceSimpleCall=*/true);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003439 }
3440 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev617db5f2017-12-04 15:38:33 +00003441 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
Alexey Bataev999277a2017-12-06 14:31:09 +00003442 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3443 !isOpenMPTeamsDirective(S.getDirectiveKind()))
Alexey Bataev617db5f2017-12-04 15:38:33 +00003444 EmitOMPReductionClauseInit(S, LoopScope);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003445 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003446 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003447 (void)LoopScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00003448 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
3449 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003450
3451 // Detect the distribute schedule kind and chunk.
3452 llvm::Value *Chunk = nullptr;
3453 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003454 if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003455 ScheduleKind = C->getDistScheduleKind();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003456 if (const Expr *Ch = C->getChunkSize()) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003457 Chunk = EmitScalarExpr(Ch);
3458 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
Alexey Bataev617db5f2017-12-04 15:38:33 +00003459 S.getIterationVariable()->getType(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003460 S.getBeginLoc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003461 }
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00003462 } else {
3463 // Default behaviour for dist_schedule clause.
3464 CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk(
3465 *this, S, ScheduleKind, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003466 }
3467 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3468 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3469
3470 // OpenMP [2.10.8, distribute Construct, Description]
3471 // If dist_schedule is specified, kind must be static. If specified,
3472 // iterations are divided into chunks of size chunk_size, chunks are
3473 // assigned to the teams of the league in a round-robin fashion in the
3474 // order of the team number. When no chunk_size is specified, the
3475 // iteration space is divided into chunks that are approximately equal
3476 // in size, and at most one chunk is distributed to each team of the
3477 // league. The size of the chunks is unspecified in this case.
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003478 bool StaticChunked = RT.isStaticChunked(
3479 ScheduleKind, /* Chunked */ Chunk != nullptr) &&
3480 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003481 if (RT.isStaticNonchunked(ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003482 /* Chunked */ Chunk != nullptr) ||
3483 StaticChunked) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003484 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3485 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003486 CGOpenMPRuntime::StaticRTInput StaticInit(
3487 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003488 LB.getAddress(), UB.getAddress(), ST.getAddress(),
3489 StaticChunked ? Chunk : nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003490 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003491 StaticInit);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003492 JumpDest LoopExit =
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003493 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3494 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003495 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3496 ? S.getCombinedEnsureUpperBound()
3497 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003498 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003499 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3500 ? S.getCombinedInit()
3501 : S.getInit());
3502
Alexey Bataevddf3db92018-04-13 17:31:06 +00003503 const Expr *Cond =
3504 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3505 ? S.getCombinedCond()
3506 : S.getCond();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003507
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003508 if (StaticChunked)
3509 Cond = S.getCombinedDistCond();
3510
3511 // For static unchunked schedules generate:
3512 //
3513 // 1. For distribute alone, codegen
3514 // while (idx <= UB) {
3515 // BODY;
3516 // ++idx;
3517 // }
3518 //
3519 // 2. When combined with 'for' (e.g. as in 'distribute parallel for')
3520 // while (idx <= UB) {
3521 // <CodeGen rest of pragma>(LB, UB);
3522 // idx += ST;
3523 // }
3524 //
3525 // For static chunk one schedule generate:
3526 //
3527 // while (IV <= GlobalUB) {
3528 // <CodeGen rest of pragma>(LB, UB);
3529 // LB += ST;
3530 // UB += ST;
3531 // UB = min(UB, GlobalUB);
3532 // IV = LB;
3533 // }
3534 //
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003535 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3536 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3537 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003538 },
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003539 [&S, StaticChunked](CodeGenFunction &CGF) {
3540 if (StaticChunked) {
3541 CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound());
3542 CGF.EmitIgnoredExpr(S.getCombinedNextUpperBound());
3543 CGF.EmitIgnoredExpr(S.getCombinedEnsureUpperBound());
3544 CGF.EmitIgnoredExpr(S.getCombinedInit());
3545 }
3546 });
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003547 EmitBlock(LoopExit.getBlock());
3548 // Tell the runtime we are done.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003549 RT.emitForStaticFinish(*this, S.getBeginLoc(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003550 } else {
3551 // Emit the outer loop, which requests its work chunk [LB..UB] from
3552 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003553 const OMPLoopArguments LoopArguments = {
3554 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3555 Chunk};
3556 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3557 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003558 }
Alexey Bataev617db5f2017-12-04 15:38:33 +00003559 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003560 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003561 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003562 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataev617db5f2017-12-04 15:38:33 +00003563 });
3564 }
Carlo Bertollibeda2142018-02-22 19:38:14 +00003565 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
3566 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3567 !isOpenMPTeamsDirective(S.getDirectiveKind())) {
Jonas Hahnfeld5aaaece2018-10-02 19:12:47 +00003568 EmitOMPReductionClauseFinal(S, OMPD_simd);
Carlo Bertollibeda2142018-02-22 19:38:14 +00003569 // Emit post-update of the reduction variables if IsLastIter != 0.
3570 emitPostUpdateForReductionClause(
Alexey Bataevddf3db92018-04-13 17:31:06 +00003571 *this, S, [IL, &S](CodeGenFunction &CGF) {
Carlo Bertollibeda2142018-02-22 19:38:14 +00003572 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003573 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Carlo Bertollibeda2142018-02-22 19:38:14 +00003574 });
Alexey Bataev617db5f2017-12-04 15:38:33 +00003575 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00003576 // Emit final copy of the lastprivate variables if IsLastIter != 0.
Alexey Bataev617db5f2017-12-04 15:38:33 +00003577 if (HasLastprivateClause) {
Carlo Bertolli962bb802017-01-03 18:24:42 +00003578 EmitOMPLastprivateClauseFinal(
3579 S, /*NoFinals=*/false,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003580 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexey Bataev617db5f2017-12-04 15:38:33 +00003581 }
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003582 }
3583
3584 // We're now done with the loop, so jump to the continuation block.
3585 if (ContBlock) {
3586 EmitBranch(ContBlock);
3587 EmitBlock(ContBlock, true);
3588 }
3589 }
3590}
3591
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003592void CodeGenFunction::EmitOMPDistributeDirective(
3593 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003594 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003595 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003596 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003597 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev10a54312017-11-27 16:54:08 +00003598 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003599}
3600
Alexey Bataev5f600d62015-09-29 03:48:57 +00003601static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3602 const CapturedStmt *S) {
3603 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3604 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3605 CGF.CapturedStmtInfo = &CapStmtInfo;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003606 llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003607 Fn->setDoesNotRecurse();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003608 return Fn;
3609}
3610
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003611void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003612 if (S.hasClausesOfKind<OMPDependClause>()) {
3613 assert(!S.getAssociatedStmt() &&
3614 "No associated statement must be in ordered depend construct.");
Alexey Bataev8b427062016-05-25 12:36:08 +00003615 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3616 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003617 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003618 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003619 const auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003620 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3621 PrePostActionTy &Action) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003622 const CapturedStmt *CS = S.getInnermostCapturedStmt();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003623 if (C) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003624 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3625 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003626 llvm::Function *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003627 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
Alexey Bataev3c595a62017-08-14 15:01:03 +00003628 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003629 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003630 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003631 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev5f600d62015-09-29 03:48:57 +00003632 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003633 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003634 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003635 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003636}
3637
Alexey Bataevb57056f2015-01-22 06:17:56 +00003638static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003639 QualType SrcType, QualType DestType,
3640 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003641 assert(CGF.hasScalarEvaluationKind(DestType) &&
3642 "DestType must have scalar evaluation kind.");
3643 assert(!Val.isAggregate() && "Must be a scalar or complex.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003644 return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3645 DestType, Loc)
3646 : CGF.EmitComplexToScalarConversion(
3647 Val.getComplexVal(), SrcType, DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003648}
3649
3650static CodeGenFunction::ComplexPairTy
3651convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003652 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003653 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3654 "DestType must have complex evaluation kind.");
3655 CodeGenFunction::ComplexPairTy ComplexVal;
3656 if (Val.isScalar()) {
3657 // Convert the input element to the element type of the complex.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003658 QualType DestElementType =
3659 DestType->castAs<ComplexType>()->getElementType();
3660 llvm::Value *ScalarVal = CGF.EmitScalarConversion(
3661 Val.getScalarVal(), SrcType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003662 ComplexVal = CodeGenFunction::ComplexPairTy(
3663 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3664 } else {
3665 assert(Val.isComplex() && "Must be a scalar or complex.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003666 QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3667 QualType DestElementType =
3668 DestType->castAs<ComplexType>()->getElementType();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003669 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003670 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003671 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003672 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003673 }
3674 return ComplexVal;
3675}
3676
Alexey Bataev5e018f92015-04-23 06:35:10 +00003677static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3678 LValue LVal, RValue RVal) {
3679 if (LVal.isGlobalReg()) {
3680 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3681 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003682 CGF.EmitAtomicStore(RVal, LVal,
3683 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3684 : llvm::AtomicOrdering::Monotonic,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003685 LVal.isVolatile(), /*isInit=*/false);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003686 }
3687}
3688
Alexey Bataev8524d152016-01-21 12:35:58 +00003689void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3690 QualType RValTy, SourceLocation Loc) {
3691 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003692 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003693 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3694 *this, RVal, RValTy, LVal.getType(), Loc)),
3695 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003696 break;
3697 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003698 EmitStoreOfComplex(
3699 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003700 /*isInit=*/false);
3701 break;
3702 case TEK_Aggregate:
3703 llvm_unreachable("Must be a scalar or complex.");
3704 }
3705}
3706
Alexey Bataevddf3db92018-04-13 17:31:06 +00003707static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb57056f2015-01-22 06:17:56 +00003708 const Expr *X, const Expr *V,
3709 SourceLocation Loc) {
3710 // v = x;
3711 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3712 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3713 LValue XLValue = CGF.EmitLValue(X);
3714 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003715 RValue Res = XLValue.isGlobalReg()
3716 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003717 : CGF.EmitAtomicLoad(
3718 XLValue, Loc,
3719 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3720 : llvm::AtomicOrdering::Monotonic,
3721 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003722 // OpenMP, 2.12.6, atomic Construct
3723 // Any atomic construct with a seq_cst clause forces the atomically
3724 // performed operation to include an implicit flush operation without a
3725 // list.
3726 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003727 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003728 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003729}
3730
Alexey Bataevddf3db92018-04-13 17:31:06 +00003731static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb8329262015-02-27 06:33:30 +00003732 const Expr *X, const Expr *E,
3733 SourceLocation Loc) {
3734 // x = expr;
3735 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003736 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003737 // OpenMP, 2.12.6, atomic Construct
3738 // Any atomic construct with a seq_cst clause forces the atomically
3739 // performed operation to include an implicit flush operation without a
3740 // list.
3741 if (IsSeqCst)
3742 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3743}
3744
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003745static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3746 RValue Update,
3747 BinaryOperatorKind BO,
3748 llvm::AtomicOrdering AO,
3749 bool IsXLHSInRHSPart) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003750 ASTContext &Context = CGF.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003751 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003752 // expression is simple and atomic is allowed for the given type for the
3753 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003754 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003755 !Update.getScalarVal()->getType()->isIntegerTy() ||
3756 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3757 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003758 X.getAddress().getElementType())) ||
3759 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003760 !Context.getTargetInfo().hasBuiltinAtomic(
3761 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003762 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003763
3764 llvm::AtomicRMWInst::BinOp RMWOp;
3765 switch (BO) {
3766 case BO_Add:
3767 RMWOp = llvm::AtomicRMWInst::Add;
3768 break;
3769 case BO_Sub:
3770 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003771 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003772 RMWOp = llvm::AtomicRMWInst::Sub;
3773 break;
3774 case BO_And:
3775 RMWOp = llvm::AtomicRMWInst::And;
3776 break;
3777 case BO_Or:
3778 RMWOp = llvm::AtomicRMWInst::Or;
3779 break;
3780 case BO_Xor:
3781 RMWOp = llvm::AtomicRMWInst::Xor;
3782 break;
3783 case BO_LT:
3784 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3785 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3786 : llvm::AtomicRMWInst::Max)
3787 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3788 : llvm::AtomicRMWInst::UMax);
3789 break;
3790 case BO_GT:
3791 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3792 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3793 : llvm::AtomicRMWInst::Min)
3794 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3795 : llvm::AtomicRMWInst::UMin);
3796 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003797 case BO_Assign:
3798 RMWOp = llvm::AtomicRMWInst::Xchg;
3799 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003800 case BO_Mul:
3801 case BO_Div:
3802 case BO_Rem:
3803 case BO_Shl:
3804 case BO_Shr:
3805 case BO_LAnd:
3806 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003807 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003808 case BO_PtrMemD:
3809 case BO_PtrMemI:
3810 case BO_LE:
3811 case BO_GE:
3812 case BO_EQ:
3813 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00003814 case BO_Cmp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003815 case BO_AddAssign:
3816 case BO_SubAssign:
3817 case BO_AndAssign:
3818 case BO_OrAssign:
3819 case BO_XorAssign:
3820 case BO_MulAssign:
3821 case BO_DivAssign:
3822 case BO_RemAssign:
3823 case BO_ShlAssign:
3824 case BO_ShrAssign:
3825 case BO_Comma:
3826 llvm_unreachable("Unsupported atomic update operation");
3827 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003828 llvm::Value *UpdateVal = Update.getScalarVal();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003829 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3830 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003831 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003832 X.getType()->hasSignedIntegerRepresentation());
3833 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003834 llvm::Value *Res =
3835 CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003836 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003837}
3838
Alexey Bataev5e018f92015-04-23 06:35:10 +00003839std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003840 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3841 llvm::AtomicOrdering AO, SourceLocation Loc,
Alexey Bataevddf3db92018-04-13 17:31:06 +00003842 const llvm::function_ref<RValue(RValue)> CommonGen) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003843 // Update expressions are allowed to have the following forms:
3844 // x binop= expr; -> xrval + expr;
3845 // x++, ++x -> xrval + 1;
3846 // x--, --x -> xrval - 1;
3847 // x = x binop expr; -> xrval binop expr
3848 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003849 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3850 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003851 if (X.isGlobalReg()) {
3852 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3853 // 'xrval'.
3854 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3855 } else {
3856 // Perform compare-and-swap procedure.
3857 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003858 }
3859 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003860 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003861}
3862
Alexey Bataevddf3db92018-04-13 17:31:06 +00003863static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb4505a72015-03-30 05:20:59 +00003864 const Expr *X, const Expr *E,
3865 const Expr *UE, bool IsXLHSInRHSPart,
3866 SourceLocation Loc) {
3867 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3868 "Update expr in 'atomic update' must be a binary operator.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003869 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003870 // Update expressions are allowed to have the following forms:
3871 // x binop= expr; -> xrval + expr;
3872 // x++, ++x -> xrval + 1;
3873 // x--, --x -> xrval - 1;
3874 // x = x binop expr; -> xrval binop expr
3875 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003876 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003877 LValue XLValue = CGF.EmitLValue(X);
3878 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003879 llvm::AtomicOrdering AO = IsSeqCst
3880 ? llvm::AtomicOrdering::SequentiallyConsistent
3881 : llvm::AtomicOrdering::Monotonic;
3882 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3883 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3884 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3885 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3886 auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) {
3887 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3888 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3889 return CGF.EmitAnyExpr(UE);
3890 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003891 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3892 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3893 // OpenMP, 2.12.6, atomic Construct
3894 // Any atomic construct with a seq_cst clause forces the atomically
3895 // performed operation to include an implicit flush operation without a
3896 // list.
3897 if (IsSeqCst)
3898 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3899}
3900
3901static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003902 QualType SourceType, QualType ResType,
3903 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003904 switch (CGF.getEvaluationKind(ResType)) {
3905 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003906 return RValue::get(
3907 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003908 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003909 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003910 return RValue::getComplex(Res.first, Res.second);
3911 }
3912 case TEK_Aggregate:
3913 break;
3914 }
3915 llvm_unreachable("Must be a scalar or complex.");
3916}
3917
Alexey Bataevddf3db92018-04-13 17:31:06 +00003918static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003919 bool IsPostfixUpdate, const Expr *V,
3920 const Expr *X, const Expr *E,
3921 const Expr *UE, bool IsXLHSInRHSPart,
3922 SourceLocation Loc) {
3923 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3924 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3925 RValue NewVVal;
3926 LValue VLValue = CGF.EmitLValue(V);
3927 LValue XLValue = CGF.EmitLValue(X);
3928 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003929 llvm::AtomicOrdering AO = IsSeqCst
3930 ? llvm::AtomicOrdering::SequentiallyConsistent
3931 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003932 QualType NewVValType;
3933 if (UE) {
3934 // 'x' is updated with some additional value.
3935 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3936 "Update expr in 'atomic capture' must be a binary operator.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003937 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
Alexey Bataev5e018f92015-04-23 06:35:10 +00003938 // Update expressions are allowed to have the following forms:
3939 // x binop= expr; -> xrval + expr;
3940 // x++, ++x -> xrval + 1;
3941 // x--, --x -> xrval - 1;
3942 // x = x binop expr; -> xrval binop expr
3943 // x = expr Op x; - > expr binop xrval;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003944 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3945 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3946 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003947 NewVValType = XRValExpr->getType();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003948 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003949 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Alexey Bataevddf3db92018-04-13 17:31:06 +00003950 IsPostfixUpdate](RValue XRValue) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003951 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3952 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3953 RValue Res = CGF.EmitAnyExpr(UE);
3954 NewVVal = IsPostfixUpdate ? XRValue : Res;
3955 return Res;
3956 };
3957 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3958 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3959 if (Res.first) {
3960 // 'atomicrmw' instruction was generated.
3961 if (IsPostfixUpdate) {
3962 // Use old value from 'atomicrmw'.
3963 NewVVal = Res.second;
3964 } else {
3965 // 'atomicrmw' does not provide new value, so evaluate it using old
3966 // value of 'x'.
3967 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3968 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3969 NewVVal = CGF.EmitAnyExpr(UE);
3970 }
3971 }
3972 } else {
3973 // 'x' is simply rewritten with some 'expr'.
3974 NewVValType = X->getType().getNonReferenceType();
3975 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003976 X->getType().getNonReferenceType(), Loc);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003977 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003978 NewVVal = XRValue;
3979 return ExprRValue;
3980 };
3981 // Try to perform atomicrmw xchg, otherwise simple exchange.
3982 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3983 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3984 Loc, Gen);
3985 if (Res.first) {
3986 // 'atomicrmw' instruction was generated.
3987 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3988 }
3989 }
3990 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003991 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003992 // OpenMP, 2.12.6, atomic Construct
3993 // Any atomic construct with a seq_cst clause forces the atomically
3994 // performed operation to include an implicit flush operation without a
3995 // list.
3996 if (IsSeqCst)
3997 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3998}
3999
Alexey Bataevddf3db92018-04-13 17:31:06 +00004000static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00004001 bool IsSeqCst, bool IsPostfixUpdate,
4002 const Expr *X, const Expr *V, const Expr *E,
4003 const Expr *UE, bool IsXLHSInRHSPart,
4004 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00004005 switch (Kind) {
4006 case OMPC_read:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004007 emitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00004008 break;
4009 case OMPC_write:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004010 emitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
Alexey Bataevb8329262015-02-27 06:33:30 +00004011 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004012 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004013 case OMPC_update:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004014 emitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00004015 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00004016 case OMPC_capture:
Alexey Bataevddf3db92018-04-13 17:31:06 +00004017 emitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
Alexey Bataev5e018f92015-04-23 06:35:10 +00004018 IsXLHSInRHSPart, Loc);
4019 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00004020 case OMPC_if:
4021 case OMPC_final:
4022 case OMPC_num_threads:
4023 case OMPC_private:
4024 case OMPC_firstprivate:
4025 case OMPC_lastprivate:
4026 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004027 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00004028 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004029 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00004030 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00004031 case OMPC_allocator:
Alexey Bataeve04483e2019-03-27 14:14:31 +00004032 case OMPC_allocate:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004033 case OMPC_collapse:
4034 case OMPC_default:
4035 case OMPC_seq_cst:
4036 case OMPC_shared:
4037 case OMPC_linear:
4038 case OMPC_aligned:
4039 case OMPC_copyin:
4040 case OMPC_copyprivate:
4041 case OMPC_flush:
4042 case OMPC_proc_bind:
4043 case OMPC_schedule:
4044 case OMPC_ordered:
4045 case OMPC_nowait:
4046 case OMPC_untied:
4047 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00004048 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004049 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00004050 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00004051 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004052 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00004053 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00004054 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00004055 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00004056 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00004057 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00004058 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00004059 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00004060 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00004061 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00004062 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004063 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00004064 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00004065 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00004066 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00004067 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00004068 case OMPC_unified_address:
Alexey Bataev94c50642018-10-01 14:26:31 +00004069 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00004070 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00004071 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00004072 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +00004073 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +00004074 case OMPC_match:
Alexey Bataevb57056f2015-01-22 06:17:56 +00004075 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
4076 }
4077}
4078
4079void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004080 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00004081 OpenMPClauseKind Kind = OMPC_unknown;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004082 for (const OMPClause *C : S.clauses()) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00004083 // Find first clause (skip seq_cst clause, if it is first).
4084 if (C->getClauseKind() != OMPC_seq_cst) {
4085 Kind = C->getClauseKind();
4086 break;
4087 }
4088 }
Alexey Bataev10fec572015-03-11 04:48:56 +00004089
Alexey Bataevddf3db92018-04-13 17:31:06 +00004090 const Stmt *CS = S.getInnermostCapturedStmt()->IgnoreContainers();
Bill Wendling7c44da22018-10-31 03:48:47 +00004091 if (const auto *FE = dyn_cast<FullExpr>(CS))
4092 enterFullExpression(FE);
Alexey Bataev5e018f92015-04-23 06:35:10 +00004093 // Processing for statements under 'atomic capture'.
4094 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004095 for (const Stmt *C : Compound->body()) {
Bill Wendling7c44da22018-10-31 03:48:47 +00004096 if (const auto *FE = dyn_cast<FullExpr>(C))
4097 enterFullExpression(FE);
Alexey Bataev5e018f92015-04-23 06:35:10 +00004098 }
4099 }
Alexey Bataev10fec572015-03-11 04:48:56 +00004100
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004101 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
4102 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00004103 CGF.EmitStopPoint(CS);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004104 emitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
Alexey Bataev5e018f92015-04-23 06:35:10 +00004105 S.getV(), S.getExpr(), S.getUpdateExpr(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004106 S.isXLHSInRHSPart(), S.getBeginLoc());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004107 };
Alexey Bataev475a7442018-01-12 19:39:11 +00004108 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004109 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00004110}
4111
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004112static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
4113 const OMPExecutableDirective &S,
4114 const RegionCodeGenTy &CodeGen) {
4115 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
4116 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00004117
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00004118 // On device emit this construct as inlined code.
4119 if (CGM.getLangOpts().OpenMPIsDevice) {
4120 OMPLexicalScope Scope(CGF, S, OMPD_target);
4121 CGM.getOpenMPRuntime().emitInlinedDirective(
4122 CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev4ac68a22018-05-16 15:08:32 +00004123 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00004124 });
4125 return;
4126 }
4127
Samuel Antaoee8fb302016-01-06 13:42:12 +00004128 llvm::Function *Fn = nullptr;
4129 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00004130
Samuel Antaobed3c462015-10-02 16:14:20 +00004131 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00004132 // Check for the at most one if clause associated with the target region.
4133 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4134 if (C->getNameModifier() == OMPD_unknown ||
4135 C->getNameModifier() == OMPD_target) {
4136 IfCond = C->getCondition();
4137 break;
4138 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004139 }
4140
4141 // Check if we have any device clause associated with the directive.
4142 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004143 if (auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaobed3c462015-10-02 16:14:20 +00004144 Device = C->getDevice();
Samuel Antaobed3c462015-10-02 16:14:20 +00004145
Samuel Antaoee8fb302016-01-06 13:42:12 +00004146 // Check if we have an if clause whose conditional always evaluates to false
4147 // or if we do not have any targets specified. If so the target region is not
4148 // an offload entry point.
4149 bool IsOffloadEntry = true;
4150 if (IfCond) {
4151 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004152 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00004153 IsOffloadEntry = false;
4154 }
4155 if (CGM.getLangOpts().OMPTargetTriples.empty())
4156 IsOffloadEntry = false;
4157
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004158 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004159 StringRef ParentName;
4160 // In case we have Ctors/Dtors we use the complete type variant to produce
4161 // the mangling of the device outlined kernel.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004162 if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00004163 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Alexey Bataevddf3db92018-04-13 17:31:06 +00004164 else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00004165 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
4166 else
4167 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004168 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004169
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004170 // Emit target region as a standalone region.
4171 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
4172 IsOffloadEntry, CodeGen);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004173 OMPLexicalScope Scope(CGF, S, OMPD_task);
Alexey Bataevec7946e2019-09-23 14:06:51 +00004174 auto &&SizeEmitter =
4175 [IsOffloadEntry](CodeGenFunction &CGF,
4176 const OMPLoopDirective &D) -> llvm::Value * {
4177 if (IsOffloadEntry) {
4178 OMPLoopScope(CGF, D);
4179 // Emit calculation of the iterations count.
4180 llvm::Value *NumIterations = CGF.EmitScalarExpr(D.getNumIterations());
4181 NumIterations = CGF.Builder.CreateIntCast(NumIterations, CGF.Int64Ty,
4182 /*isSigned=*/false);
4183 return NumIterations;
4184 }
4185 return nullptr;
Alexey Bataev7bb33532019-01-07 21:30:43 +00004186 };
Alexey Bataevec7946e2019-09-23 14:06:51 +00004187 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
4188 SizeEmitter);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004189}
4190
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004191static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
4192 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004193 Action.Enter(CGF);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004194 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4195 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4196 CGF.EmitOMPPrivateClause(S, PrivateScope);
4197 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00004198 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4199 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004200
Alexey Bataev475a7442018-01-12 19:39:11 +00004201 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004202}
4203
4204void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
4205 StringRef ParentName,
4206 const OMPTargetDirective &S) {
4207 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4208 emitTargetRegion(CGF, S, Action);
4209 };
4210 llvm::Function *Fn;
4211 llvm::Constant *Addr;
4212 // Emit target region as a standalone region.
4213 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4214 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4215 assert(Fn && Addr && "Target device function emission failed.");
4216}
4217
4218void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
4219 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4220 emitTargetRegion(CGF, S, Action);
4221 };
4222 emitCommonOMPTargetDirective(*this, S, CodeGen);
4223}
4224
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004225static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
4226 const OMPExecutableDirective &S,
4227 OpenMPDirectiveKind InnermostKind,
4228 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004229 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
James Y Knight9871db02019-02-05 16:42:33 +00004230 llvm::Function *OutlinedFn =
Alexey Bataevddf3db92018-04-13 17:31:06 +00004231 CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
4232 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004233
Alexey Bataevddf3db92018-04-13 17:31:06 +00004234 const auto *NT = S.getSingleClause<OMPNumTeamsClause>();
4235 const auto *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004236 if (NT || TL) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004237 const Expr *NumTeams = NT ? NT->getNumTeams() : nullptr;
4238 const Expr *ThreadLimit = TL ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004239
Carlo Bertollic6872252016-04-04 15:55:02 +00004240 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004241 S.getBeginLoc());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004242 }
4243
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004244 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004245 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4246 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004247 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004248 CapturedVars);
4249}
4250
4251void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00004252 // Emit teams region as a standalone region.
Alexey Bataevc99042b2018-03-15 18:10:54 +00004253 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004254 Action.Enter(CGF);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004255 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00004256 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4257 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004258 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004259 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00004260 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004261 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004262 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00004263 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004264 emitPostUpdateForReductionClause(*this, S,
4265 [](CodeGenFunction &) { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00004266}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004267
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004268static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4269 const OMPTargetTeamsDirective &S) {
4270 auto *CS = S.getCapturedStmt(OMPD_teams);
4271 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004272 // Emit teams region as a standalone region.
4273 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004274 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004275 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4276 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4277 CGF.EmitOMPPrivateClause(S, PrivateScope);
4278 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4279 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00004280 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4281 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004282 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004283 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004284 };
4285 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004286 emitPostUpdateForReductionClause(CGF, S,
4287 [](CodeGenFunction &) { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004288}
4289
4290void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4291 CodeGenModule &CGM, StringRef ParentName,
4292 const OMPTargetTeamsDirective &S) {
4293 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4294 emitTargetTeamsRegion(CGF, Action, S);
4295 };
4296 llvm::Function *Fn;
4297 llvm::Constant *Addr;
4298 // Emit target region as a standalone region.
4299 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4300 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4301 assert(Fn && Addr && "Target device function emission failed.");
4302}
4303
4304void CodeGenFunction::EmitOMPTargetTeamsDirective(
4305 const OMPTargetTeamsDirective &S) {
4306 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4307 emitTargetTeamsRegion(CGF, Action, S);
4308 };
4309 emitCommonOMPTargetDirective(*this, S, CodeGen);
4310}
4311
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004312static void
4313emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4314 const OMPTargetTeamsDistributeDirective &S) {
4315 Action.Enter(CGF);
4316 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4317 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4318 };
4319
4320 // Emit teams region as a standalone region.
4321 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004322 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004323 Action.Enter(CGF);
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004324 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4325 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4326 (void)PrivateScope.Privatize();
4327 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4328 CodeGenDistribute);
4329 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4330 };
4331 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4332 emitPostUpdateForReductionClause(CGF, S,
4333 [](CodeGenFunction &) { return nullptr; });
4334}
4335
4336void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4337 CodeGenModule &CGM, StringRef ParentName,
4338 const OMPTargetTeamsDistributeDirective &S) {
4339 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4340 emitTargetTeamsDistributeRegion(CGF, Action, S);
4341 };
4342 llvm::Function *Fn;
4343 llvm::Constant *Addr;
4344 // Emit target region as a standalone region.
4345 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4346 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4347 assert(Fn && Addr && "Target device function emission failed.");
4348}
4349
4350void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4351 const OMPTargetTeamsDistributeDirective &S) {
4352 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4353 emitTargetTeamsDistributeRegion(CGF, Action, S);
4354 };
4355 emitCommonOMPTargetDirective(*this, S, CodeGen);
4356}
4357
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004358static void emitTargetTeamsDistributeSimdRegion(
4359 CodeGenFunction &CGF, PrePostActionTy &Action,
4360 const OMPTargetTeamsDistributeSimdDirective &S) {
4361 Action.Enter(CGF);
4362 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4363 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4364 };
4365
4366 // Emit teams region as a standalone region.
4367 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004368 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004369 Action.Enter(CGF);
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004370 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4371 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4372 (void)PrivateScope.Privatize();
4373 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4374 CodeGenDistribute);
4375 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4376 };
4377 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4378 emitPostUpdateForReductionClause(CGF, S,
4379 [](CodeGenFunction &) { return nullptr; });
4380}
4381
4382void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4383 CodeGenModule &CGM, StringRef ParentName,
4384 const OMPTargetTeamsDistributeSimdDirective &S) {
4385 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4386 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4387 };
4388 llvm::Function *Fn;
4389 llvm::Constant *Addr;
4390 // Emit target region as a standalone region.
4391 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4392 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4393 assert(Fn && Addr && "Target device function emission failed.");
4394}
4395
4396void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4397 const OMPTargetTeamsDistributeSimdDirective &S) {
4398 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4399 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4400 };
4401 emitCommonOMPTargetDirective(*this, S, CodeGen);
4402}
4403
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004404void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4405 const OMPTeamsDistributeDirective &S) {
4406
4407 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4408 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4409 };
4410
4411 // Emit teams region as a standalone region.
4412 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004413 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004414 Action.Enter(CGF);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004415 OMPPrivateScope PrivateScope(CGF);
4416 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4417 (void)PrivateScope.Privatize();
4418 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4419 CodeGenDistribute);
4420 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4421 };
Alexey Bataev95c6dd42017-11-29 15:14:16 +00004422 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004423 emitPostUpdateForReductionClause(*this, S,
4424 [](CodeGenFunction &) { return nullptr; });
4425}
4426
Alexey Bataev999277a2017-12-06 14:31:09 +00004427void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4428 const OMPTeamsDistributeSimdDirective &S) {
4429 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4430 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4431 };
4432
4433 // Emit teams region as a standalone region.
4434 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004435 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004436 Action.Enter(CGF);
Alexey Bataev999277a2017-12-06 14:31:09 +00004437 OMPPrivateScope PrivateScope(CGF);
4438 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4439 (void)PrivateScope.Privatize();
4440 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4441 CodeGenDistribute);
4442 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4443 };
4444 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4445 emitPostUpdateForReductionClause(*this, S,
4446 [](CodeGenFunction &) { return nullptr; });
4447}
4448
Carlo Bertolli62fae152017-11-20 20:46:39 +00004449void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4450 const OMPTeamsDistributeParallelForDirective &S) {
4451 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4452 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4453 S.getDistInc());
4454 };
4455
4456 // Emit teams region as a standalone region.
4457 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004458 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004459 Action.Enter(CGF);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004460 OMPPrivateScope PrivateScope(CGF);
4461 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4462 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00004463 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4464 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004465 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4466 };
4467 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4468 emitPostUpdateForReductionClause(*this, S,
4469 [](CodeGenFunction &) { return nullptr; });
4470}
4471
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004472void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4473 const OMPTeamsDistributeParallelForSimdDirective &S) {
4474 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4475 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4476 S.getDistInc());
4477 };
4478
4479 // Emit teams region as a standalone region.
4480 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004481 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004482 Action.Enter(CGF);
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004483 OMPPrivateScope PrivateScope(CGF);
4484 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4485 (void)PrivateScope.Privatize();
4486 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4487 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4488 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4489 };
4490 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4491 emitPostUpdateForReductionClause(*this, S,
4492 [](CodeGenFunction &) { return nullptr; });
4493}
4494
Carlo Bertolli52978c32018-01-03 21:12:44 +00004495static void emitTargetTeamsDistributeParallelForRegion(
4496 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
4497 PrePostActionTy &Action) {
Carlo Bertolli79712092018-02-28 20:48:35 +00004498 Action.Enter(CGF);
Carlo Bertolli52978c32018-01-03 21:12:44 +00004499 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4500 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4501 S.getDistInc());
4502 };
4503
4504 // Emit teams region as a standalone region.
4505 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004506 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004507 Action.Enter(CGF);
Carlo Bertolli52978c32018-01-03 21:12:44 +00004508 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4509 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4510 (void)PrivateScope.Privatize();
4511 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4512 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4513 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4514 };
4515
4516 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
4517 CodeGenTeams);
4518 emitPostUpdateForReductionClause(CGF, S,
4519 [](CodeGenFunction &) { return nullptr; });
4520}
4521
4522void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
4523 CodeGenModule &CGM, StringRef ParentName,
4524 const OMPTargetTeamsDistributeParallelForDirective &S) {
4525 // Emit SPMD target teams distribute parallel for region as a standalone
4526 // region.
4527 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4528 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4529 };
4530 llvm::Function *Fn;
4531 llvm::Constant *Addr;
4532 // Emit target region as a standalone region.
4533 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4534 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4535 assert(Fn && Addr && "Target device function emission failed.");
4536}
4537
4538void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
4539 const OMPTargetTeamsDistributeParallelForDirective &S) {
4540 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4541 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4542 };
4543 emitCommonOMPTargetDirective(*this, S, CodeGen);
4544}
4545
Alexey Bataev647dd842018-01-15 20:59:40 +00004546static void emitTargetTeamsDistributeParallelForSimdRegion(
4547 CodeGenFunction &CGF,
4548 const OMPTargetTeamsDistributeParallelForSimdDirective &S,
4549 PrePostActionTy &Action) {
Carlo Bertolli79712092018-02-28 20:48:35 +00004550 Action.Enter(CGF);
Alexey Bataev647dd842018-01-15 20:59:40 +00004551 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4552 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4553 S.getDistInc());
4554 };
4555
4556 // Emit teams region as a standalone region.
4557 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004558 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004559 Action.Enter(CGF);
Alexey Bataev647dd842018-01-15 20:59:40 +00004560 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4561 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4562 (void)PrivateScope.Privatize();
4563 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4564 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4565 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4566 };
4567
4568 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
4569 CodeGenTeams);
4570 emitPostUpdateForReductionClause(CGF, S,
4571 [](CodeGenFunction &) { return nullptr; });
4572}
4573
4574void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
4575 CodeGenModule &CGM, StringRef ParentName,
4576 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4577 // Emit SPMD target teams distribute parallel for simd region as a standalone
4578 // region.
4579 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4580 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4581 };
4582 llvm::Function *Fn;
4583 llvm::Constant *Addr;
4584 // Emit target region as a standalone region.
4585 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4586 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4587 assert(Fn && Addr && "Target device function emission failed.");
4588}
4589
4590void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
4591 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4592 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4593 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4594 };
4595 emitCommonOMPTargetDirective(*this, S, CodeGen);
4596}
4597
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004598void CodeGenFunction::EmitOMPCancellationPointDirective(
4599 const OMPCancellationPointDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004600 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00004601 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004602}
4603
Alexey Bataev80909872015-07-02 11:25:17 +00004604void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004605 const Expr *IfCond = nullptr;
4606 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4607 if (C->getNameModifier() == OMPD_unknown ||
4608 C->getNameModifier() == OMPD_cancel) {
4609 IfCond = C->getCondition();
4610 break;
4611 }
4612 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004613 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004614 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00004615}
4616
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004617CodeGenFunction::JumpDest
4618CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00004619 if (Kind == OMPD_parallel || Kind == OMPD_task ||
4620 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004621 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004622 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00004623 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
4624 Kind == OMPD_distribute_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004625 Kind == OMPD_target_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004626 Kind == OMPD_teams_distribute_parallel_for ||
4627 Kind == OMPD_target_teams_distribute_parallel_for);
Alexey Bataev957d8562016-11-17 15:12:05 +00004628 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004629}
Michael Wong65f367f2015-07-21 13:44:28 +00004630
Samuel Antaocc10b852016-07-28 14:23:26 +00004631void CodeGenFunction::EmitOMPUseDevicePtrClause(
4632 const OMPClause &NC, OMPPrivateScope &PrivateScope,
4633 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
4634 const auto &C = cast<OMPUseDevicePtrClause>(NC);
4635 auto OrigVarIt = C.varlist_begin();
4636 auto InitIt = C.inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00004637 for (const Expr *PvtVarIt : C.private_copies()) {
4638 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
4639 const auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
4640 const auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
Samuel Antaocc10b852016-07-28 14:23:26 +00004641
4642 // In order to identify the right initializer we need to match the
4643 // declaration used by the mapping logic. In some cases we may get
4644 // OMPCapturedExprDecl that refers to the original declaration.
4645 const ValueDecl *MatchingVD = OrigVD;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004646 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004647 // OMPCapturedExprDecl are used to privative fields of the current
4648 // structure.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004649 const auto *ME = cast<MemberExpr>(OED->getInit());
Samuel Antaocc10b852016-07-28 14:23:26 +00004650 assert(isa<CXXThisExpr>(ME->getBase()) &&
4651 "Base should be the current struct!");
4652 MatchingVD = ME->getMemberDecl();
4653 }
4654
4655 // If we don't have information about the current list item, move on to
4656 // the next one.
4657 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
4658 if (InitAddrIt == CaptureDeviceAddrMap.end())
4659 continue;
4660
Alexey Bataevddf3db92018-04-13 17:31:06 +00004661 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, OrigVD,
4662 InitAddrIt, InitVD,
4663 PvtVD]() {
Samuel Antaocc10b852016-07-28 14:23:26 +00004664 // Initialize the temporary initialization variable with the address we
4665 // get from the runtime library. We have to cast the source address
4666 // because it is always a void *. References are materialized in the
4667 // privatization scope, so the initialization here disregards the fact
4668 // the original variable is a reference.
4669 QualType AddrQTy =
4670 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
4671 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
4672 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
4673 setAddrOfLocalVar(InitVD, InitAddr);
4674
4675 // Emit private declaration, it will be initialized by the value we
4676 // declaration we just added to the local declarations map.
4677 EmitDecl(*PvtVD);
4678
4679 // The initialization variables reached its purpose in the emission
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004680 // of the previous declaration, so we don't need it anymore.
Samuel Antaocc10b852016-07-28 14:23:26 +00004681 LocalDeclMap.erase(InitVD);
4682
4683 // Return the address of the private variable.
4684 return GetAddrOfLocalVar(PvtVD);
4685 });
4686 assert(IsRegistered && "firstprivate var already registered as private");
4687 // Silence the warning about unused variable.
4688 (void)IsRegistered;
4689
4690 ++OrigVarIt;
4691 ++InitIt;
4692 }
4693}
4694
Michael Wong65f367f2015-07-21 13:44:28 +00004695// Generate the instructions for '#pragma omp target data' directive.
4696void CodeGenFunction::EmitOMPTargetDataDirective(
4697 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004698 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4699
4700 // Create a pre/post action to signal the privatization of the device pointer.
4701 // This action can be replaced by the OpenMP runtime code generation to
4702 // deactivate privatization.
4703 bool PrivatizeDevicePointers = false;
4704 class DevicePointerPrivActionTy : public PrePostActionTy {
4705 bool &PrivatizeDevicePointers;
4706
4707 public:
4708 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4709 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4710 void Enter(CodeGenFunction &CGF) override {
4711 PrivatizeDevicePointers = true;
4712 }
Samuel Antaodf158d52016-04-27 22:58:19 +00004713 };
Samuel Antaocc10b852016-07-28 14:23:26 +00004714 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4715
4716 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
Alexey Bataev475a7442018-01-12 19:39:11 +00004717 CodeGenFunction &CGF, PrePostActionTy &Action) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004718 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00004719 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Samuel Antaocc10b852016-07-28 14:23:26 +00004720 };
4721
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004722 // Codegen that selects whether to generate the privatization code or not.
Samuel Antaocc10b852016-07-28 14:23:26 +00004723 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4724 &InnermostCodeGen](CodeGenFunction &CGF,
4725 PrePostActionTy &Action) {
4726 RegionCodeGenTy RCG(InnermostCodeGen);
4727 PrivatizeDevicePointers = false;
4728
4729 // Call the pre-action to change the status of PrivatizeDevicePointers if
4730 // needed.
4731 Action.Enter(CGF);
4732
4733 if (PrivatizeDevicePointers) {
4734 OMPPrivateScope PrivateScope(CGF);
4735 // Emit all instances of the use_device_ptr clause.
4736 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4737 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4738 Info.CaptureDeviceAddrMap);
4739 (void)PrivateScope.Privatize();
4740 RCG(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004741 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00004742 RCG(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004743 }
Samuel Antaocc10b852016-07-28 14:23:26 +00004744 };
4745
4746 // Forward the provided action to the privatization codegen.
4747 RegionCodeGenTy PrivRCG(PrivCodeGen);
4748 PrivRCG.setAction(Action);
4749
4750 // Notwithstanding the body of the region is emitted as inlined directive,
4751 // we don't use an inline scope as changes in the references inside the
4752 // region are expected to be visible outside, so we do not privative them.
4753 OMPLexicalScope Scope(CGF, S);
4754 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4755 PrivRCG);
4756 };
4757
4758 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004759
4760 // If we don't have target devices, don't bother emitting the data mapping
4761 // code.
4762 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004763 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004764 return;
4765 }
4766
4767 // Check if we have any if clause associated with the directive.
4768 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004769 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antaodf158d52016-04-27 22:58:19 +00004770 IfCond = C->getCondition();
4771
4772 // Check if we have any device clause associated with the directive.
4773 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004774 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaodf158d52016-04-27 22:58:19 +00004775 Device = C->getDevice();
4776
Samuel Antaocc10b852016-07-28 14:23:26 +00004777 // Set the action to signal privatization of device pointers.
4778 RCG.setAction(PrivAction);
4779
4780 // Emit region code.
4781 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4782 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004783}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004784
Samuel Antaodf67fc42016-01-19 19:15:56 +00004785void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4786 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004787 // If we don't have target devices, don't bother emitting the data mapping
4788 // code.
4789 if (CGM.getLangOpts().OMPTargetTriples.empty())
4790 return;
4791
4792 // Check if we have any if clause associated with the directive.
4793 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004794 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004795 IfCond = C->getCondition();
4796
4797 // Check if we have any device clause associated with the directive.
4798 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004799 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004800 Device = C->getDevice();
4801
Alexey Bataev475a7442018-01-12 19:39:11 +00004802 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004803 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004804}
4805
Samuel Antao72590762016-01-19 20:04:50 +00004806void CodeGenFunction::EmitOMPTargetExitDataDirective(
4807 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004808 // If we don't have target devices, don't bother emitting the data mapping
4809 // code.
4810 if (CGM.getLangOpts().OMPTargetTriples.empty())
4811 return;
4812
4813 // Check if we have any if clause associated with the directive.
4814 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004815 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antao8dd66282016-04-27 23:14:30 +00004816 IfCond = C->getCondition();
4817
4818 // Check if we have any device clause associated with the directive.
4819 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004820 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antao8dd66282016-04-27 23:14:30 +00004821 Device = C->getDevice();
4822
Alexey Bataev475a7442018-01-12 19:39:11 +00004823 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004824 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004825}
4826
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004827static void emitTargetParallelRegion(CodeGenFunction &CGF,
4828 const OMPTargetParallelDirective &S,
4829 PrePostActionTy &Action) {
4830 // Get the captured statement associated with the 'parallel' region.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004831 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004832 Action.Enter(CGF);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004833 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004834 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004835 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4836 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4837 CGF.EmitOMPPrivateClause(S, PrivateScope);
4838 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4839 (void)PrivateScope.Privatize();
Alexey Bataev60705422018-10-30 15:50:12 +00004840 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4841 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004842 // TODO: Add support for clauses.
4843 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004844 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004845 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004846 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4847 emitEmptyBoundParameters);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004848 emitPostUpdateForReductionClause(CGF, S,
4849 [](CodeGenFunction &) { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004850}
4851
4852void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4853 CodeGenModule &CGM, StringRef ParentName,
4854 const OMPTargetParallelDirective &S) {
4855 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4856 emitTargetParallelRegion(CGF, S, Action);
4857 };
4858 llvm::Function *Fn;
4859 llvm::Constant *Addr;
4860 // Emit target region as a standalone region.
4861 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4862 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4863 assert(Fn && Addr && "Target device function emission failed.");
4864}
4865
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004866void CodeGenFunction::EmitOMPTargetParallelDirective(
4867 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004868 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4869 emitTargetParallelRegion(CGF, S, Action);
4870 };
4871 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004872}
4873
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004874static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4875 const OMPTargetParallelForDirective &S,
4876 PrePostActionTy &Action) {
4877 Action.Enter(CGF);
4878 // Emit directive as a combined directive that consists of two implicit
4879 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00004880 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4881 Action.Enter(CGF);
Alexey Bataev2139ed62017-11-16 18:20:21 +00004882 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4883 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004884 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4885 emitDispatchForLoopBounds);
4886 };
4887 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4888 emitEmptyBoundParameters);
4889}
4890
4891void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4892 CodeGenModule &CGM, StringRef ParentName,
4893 const OMPTargetParallelForDirective &S) {
4894 // Emit SPMD target parallel for region as a standalone region.
4895 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4896 emitTargetParallelForRegion(CGF, S, Action);
4897 };
4898 llvm::Function *Fn;
4899 llvm::Constant *Addr;
4900 // Emit target region as a standalone region.
4901 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4902 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4903 assert(Fn && Addr && "Target device function emission failed.");
4904}
4905
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004906void CodeGenFunction::EmitOMPTargetParallelForDirective(
4907 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004908 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4909 emitTargetParallelForRegion(CGF, S, Action);
4910 };
4911 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004912}
4913
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004914static void
4915emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4916 const OMPTargetParallelForSimdDirective &S,
4917 PrePostActionTy &Action) {
4918 Action.Enter(CGF);
4919 // Emit directive as a combined directive that consists of two implicit
4920 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00004921 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4922 Action.Enter(CGF);
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004923 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4924 emitDispatchForLoopBounds);
4925 };
4926 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4927 emitEmptyBoundParameters);
4928}
4929
4930void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4931 CodeGenModule &CGM, StringRef ParentName,
4932 const OMPTargetParallelForSimdDirective &S) {
4933 // Emit SPMD target parallel for region as a standalone region.
4934 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4935 emitTargetParallelForSimdRegion(CGF, S, Action);
4936 };
4937 llvm::Function *Fn;
4938 llvm::Constant *Addr;
4939 // Emit target region as a standalone region.
4940 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4941 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4942 assert(Fn && Addr && "Target device function emission failed.");
4943}
4944
4945void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4946 const OMPTargetParallelForSimdDirective &S) {
4947 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4948 emitTargetParallelForSimdRegion(CGF, S, Action);
4949 };
4950 emitCommonOMPTargetDirective(*this, S, CodeGen);
4951}
4952
Alexey Bataev7292c292016-04-25 12:22:29 +00004953/// Emit a helper variable and return corresponding lvalue.
4954static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4955 const ImplicitParamDecl *PVD,
4956 CodeGenFunction::OMPPrivateScope &Privates) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004957 const auto *VDecl = cast<VarDecl>(Helper->getDecl());
4958 Privates.addPrivate(VDecl,
4959 [&CGF, PVD]() { return CGF.GetAddrOfLocalVar(PVD); });
Alexey Bataev7292c292016-04-25 12:22:29 +00004960}
4961
4962void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4963 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4964 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00004965 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004966 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
4967 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev7292c292016-04-25 12:22:29 +00004968 const Expr *IfCond = nullptr;
4969 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4970 if (C->getNameModifier() == OMPD_unknown ||
4971 C->getNameModifier() == OMPD_taskloop) {
4972 IfCond = C->getCondition();
4973 break;
4974 }
4975 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004976
4977 OMPTaskDataTy Data;
4978 // Check if taskloop must be emitted without taskgroup.
4979 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004980 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004981 Data.Tied = true;
4982 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004983 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4984 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004985 Data.Schedule.setInt(/*IntVal=*/false);
4986 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004987 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4988 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004989 Data.Schedule.setInt(/*IntVal=*/true);
4990 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004991 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004992
4993 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4994 // if (PreCond) {
4995 // for (IV in 0..LastIteration) BODY;
4996 // <Final counter/linear vars updates>;
4997 // }
4998 //
4999
5000 // Emit: if (PreCond) - begin.
5001 // If the condition constant folds and can be elided, avoid emitting the
5002 // whole loop.
5003 bool CondConstant;
5004 llvm::BasicBlock *ContBlock = nullptr;
5005 OMPLoopScope PreInitScope(CGF, S);
5006 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
5007 if (!CondConstant)
5008 return;
5009 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005010 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
Alexey Bataev7292c292016-04-25 12:22:29 +00005011 ContBlock = CGF.createBasicBlock("taskloop.if.end");
5012 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
5013 CGF.getProfileCount(&S));
5014 CGF.EmitBlock(ThenBlock);
5015 CGF.incrementProfileCounter(&S);
5016 }
5017
Alexey Bataev1e73ef32016-04-28 12:14:51 +00005018 if (isOpenMPSimdDirective(S.getDirectiveKind()))
5019 CGF.EmitOMPSimdInit(S);
5020
Alexey Bataev7292c292016-04-25 12:22:29 +00005021 OMPPrivateScope LoopScope(CGF);
5022 // Emit helper vars inits.
5023 enum { LowerBound = 5, UpperBound, Stride, LastIter };
5024 auto *I = CS->getCapturedDecl()->param_begin();
5025 auto *LBP = std::next(I, LowerBound);
5026 auto *UBP = std::next(I, UpperBound);
5027 auto *STP = std::next(I, Stride);
5028 auto *LIP = std::next(I, LastIter);
5029 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
5030 LoopScope);
5031 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
5032 LoopScope);
5033 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
5034 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
5035 LoopScope);
5036 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00005037 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00005038 (void)LoopScope.Privatize();
5039 // Emit the loop iteration variable.
5040 const Expr *IVExpr = S.getIterationVariable();
Alexey Bataevddf3db92018-04-13 17:31:06 +00005041 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
Alexey Bataev7292c292016-04-25 12:22:29 +00005042 CGF.EmitVarDecl(*IVDecl);
5043 CGF.EmitIgnoredExpr(S.getInit());
5044
5045 // Emit the iterations count variable.
5046 // If it is not a variable, Sema decided to calculate iterations count on
5047 // each iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00005048 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005049 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
5050 // Emit calculation of the iterations count.
5051 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
5052 }
5053
5054 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
5055 S.getInc(),
5056 [&S](CodeGenFunction &CGF) {
5057 CGF.EmitOMPLoopBody(S, JumpDest());
5058 CGF.EmitStopPoint(&S);
5059 },
5060 [](CodeGenFunction &) {});
5061 // Emit: if (PreCond) - end.
5062 if (ContBlock) {
5063 CGF.EmitBranch(ContBlock);
5064 CGF.EmitBlock(ContBlock, true);
5065 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00005066 // Emit final copy of the lastprivate variables if IsLastIter != 0.
5067 if (HasLastprivateClause) {
5068 CGF.EmitOMPLastprivateClauseFinal(
5069 S, isOpenMPSimdDirective(S.getDirectiveKind()),
5070 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
5071 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005072 (*LIP)->getType(), S.getBeginLoc())));
Alexey Bataevf93095a2016-05-05 08:46:22 +00005073 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005074 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005075 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
James Y Knight9871db02019-02-05 16:42:33 +00005076 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005077 const OMPTaskDataTy &Data) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005078 auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond,
5079 &Data](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005080 OMPLoopScope PreInitScope(CGF, S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005081 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005082 OutlinedFn, SharedsTy,
5083 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00005084 };
5085 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
5086 CodeGen);
5087 };
Alexey Bataev475a7442018-01-12 19:39:11 +00005088 if (Data.Nogroup) {
5089 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
5090 } else {
Alexey Bataev33446032017-07-12 18:09:32 +00005091 CGM.getOpenMPRuntime().emitTaskgroupRegion(
5092 *this,
5093 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
5094 PrePostActionTy &Action) {
5095 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00005096 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
5097 Data);
Alexey Bataev33446032017-07-12 18:09:32 +00005098 },
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005099 S.getBeginLoc());
Alexey Bataev33446032017-07-12 18:09:32 +00005100 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005101}
5102
Alexey Bataev49f6e782015-12-01 04:18:41 +00005103void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005104 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00005105}
5106
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005107void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
5108 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00005109 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005110}
Samuel Antao686c70c2016-05-26 17:30:50 +00005111
5112// Generate the instructions for '#pragma omp target update' directive.
5113void CodeGenFunction::EmitOMPTargetUpdateDirective(
5114 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00005115 // If we don't have target devices, don't bother emitting the data mapping
5116 // code.
5117 if (CGM.getLangOpts().OMPTargetTriples.empty())
5118 return;
5119
5120 // Check if we have any if clause associated with the directive.
5121 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005122 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005123 IfCond = C->getCondition();
5124
5125 // Check if we have any device clause associated with the directive.
5126 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00005127 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005128 Device = C->getDevice();
5129
Alexey Bataev475a7442018-01-12 19:39:11 +00005130 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00005131 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00005132}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005133
5134void CodeGenFunction::EmitSimpleOMPExecutableDirective(
5135 const OMPExecutableDirective &D) {
5136 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
5137 return;
5138 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
5139 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
5140 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
5141 } else {
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005142 OMPPrivateScope LoopGlobals(CGF);
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005143 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00005144 for (const Expr *E : LD->counters()) {
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005145 const auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
5146 if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) {
5147 LValue GlobLVal = CGF.EmitLValue(E);
5148 LoopGlobals.addPrivate(
5149 VD, [&GlobLVal]() { return GlobLVal.getAddress(); });
5150 }
Bjorn Pettersson6c2d83b2018-10-30 08:49:26 +00005151 if (isa<OMPCapturedExprDecl>(VD)) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005152 // Emit only those that were not explicitly referenced in clauses.
5153 if (!CGF.LocalDeclMap.count(VD))
5154 CGF.EmitVarDecl(*VD);
5155 }
5156 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005157 for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) {
5158 if (!C->getNumForLoops())
5159 continue;
5160 for (unsigned I = LD->getCollapsedNumber(),
5161 E = C->getLoopNumIterations().size();
5162 I < E; ++I) {
5163 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
Mike Rice0ed46662018-09-20 17:19:41 +00005164 cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00005165 // Emit only those that were not explicitly referenced in clauses.
5166 if (!CGF.LocalDeclMap.count(VD))
5167 CGF.EmitVarDecl(*VD);
5168 }
5169 }
5170 }
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005171 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005172 LoopGlobals.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00005173 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005174 }
5175 };
5176 OMPSimdLexicalScope Scope(*this, D);
5177 CGM.getOpenMPRuntime().emitInlinedDirective(
5178 *this,
5179 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
5180 : D.getDirectiveKind(),
5181 CodeGen);
5182}