blob: 7872a805cc3560a8fe0d8834bae3f5566a2a1033 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit OpenMP nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Alexey Bataev3392d762016-02-16 11:18:12 +000014#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "CGOpenMPRuntime.h"
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000018#include "TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Stmt.h"
20#include "clang/AST/StmtOpenMP.h"
Alexey Bataev2bbf7212016-03-03 03:52:24 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000022#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023using namespace clang;
24using namespace CodeGen;
25
Alexey Bataev3392d762016-02-16 11:18:12 +000026namespace {
27/// Lexical scope for OpenMP executable constructs, that handles correct codegen
28/// for captured expressions.
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000029class OMPLexicalScope : public CodeGenFunction::LexicalScope {
Alexey Bataev3392d762016-02-16 11:18:12 +000030 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
31 for (const auto *C : S.clauses()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +000032 if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
33 if (const auto *PreInit =
34 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000035 for (const auto *I : PreInit->decls()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +000036 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000037 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataevddf3db92018-04-13 17:31:06 +000038 } else {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000039 CodeGenFunction::AutoVarEmission Emission =
40 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
41 CGF.EmitAutoVarCleanups(Emission);
42 }
43 }
Alexey Bataev3392d762016-02-16 11:18:12 +000044 }
45 }
46 }
47 }
Alexey Bataev4ba78a42016-04-27 07:56:03 +000048 CodeGenFunction::OMPPrivateScope InlinedShareds;
49
50 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
51 return CGF.LambdaCaptureFields.lookup(VD) ||
52 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
53 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
54 }
Alexey Bataev3392d762016-02-16 11:18:12 +000055
Alexey Bataev3392d762016-02-16 11:18:12 +000056public:
Alexey Bataev475a7442018-01-12 19:39:11 +000057 OMPLexicalScope(
58 CodeGenFunction &CGF, const OMPExecutableDirective &S,
59 const llvm::Optional<OpenMPDirectiveKind> CapturedRegion = llvm::None,
60 const bool EmitPreInitStmt = true)
Alexey Bataev4ba78a42016-04-27 07:56:03 +000061 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
62 InlinedShareds(CGF) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000063 if (EmitPreInitStmt)
64 emitPreInitStmt(CGF, S);
Alexey Bataev475a7442018-01-12 19:39:11 +000065 if (!CapturedRegion.hasValue())
66 return;
67 assert(S.hasAssociatedStmt() &&
68 "Expected associated statement for inlined directive.");
69 const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion);
Alexey Bataevddf3db92018-04-13 17:31:06 +000070 for (const auto &C : CS->captures()) {
Alexey Bataev475a7442018-01-12 19:39:11 +000071 if (C.capturesVariable() || C.capturesVariableByCopy()) {
72 auto *VD = C.getCapturedVar();
73 assert(VD == VD->getCanonicalDecl() &&
74 "Canonical decl must be captured.");
75 DeclRefExpr DRE(
76 const_cast<VarDecl *>(VD),
77 isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo &&
78 InlinedShareds.isGlobalVarCaptured(VD)),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +000079 VD->getType().getNonReferenceType(), VK_LValue, C.getLocation());
Alexey Bataev475a7442018-01-12 19:39:11 +000080 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
81 return CGF.EmitLValue(&DRE).getAddress();
82 });
Alexey Bataev4ba78a42016-04-27 07:56:03 +000083 }
84 }
Alexey Bataev475a7442018-01-12 19:39:11 +000085 (void)InlinedShareds.Privatize();
Alexey Bataev3392d762016-02-16 11:18:12 +000086 }
87};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000088
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000089/// Lexical scope for OpenMP parallel construct, that handles correct codegen
90/// for captured expressions.
91class OMPParallelScope final : public OMPLexicalScope {
92 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
93 OpenMPDirectiveKind Kind = S.getDirectiveKind();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +000094 return !(isOpenMPTargetExecutionDirective(Kind) ||
95 isOpenMPLoopBoundSharingDirective(Kind)) &&
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000096 isOpenMPParallelDirective(Kind);
97 }
98
99public:
100 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +0000101 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
102 EmitPreInitStmt(S)) {}
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +0000103};
104
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000105/// Lexical scope for OpenMP teams construct, that handles correct codegen
106/// for captured expressions.
107class OMPTeamsScope final : public OMPLexicalScope {
108 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
109 OpenMPDirectiveKind Kind = S.getDirectiveKind();
110 return !isOpenMPTargetExecutionDirective(Kind) &&
111 isOpenMPTeamsDirective(Kind);
112 }
113
114public:
115 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +0000116 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
117 EmitPreInitStmt(S)) {}
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000118};
119
Alexey Bataev5a3af132016-03-29 08:58:54 +0000120/// Private scope for OpenMP loop-based directives, that supports capturing
121/// of used expression from loop statement.
122class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
123 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
Alexey Bataevab4ea222018-03-07 18:17:06 +0000124 CodeGenFunction::OMPMapVars PreCondVars;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000125 for (const auto *E : S.counters()) {
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000126 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey 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 Bataevab4ea222018-03-07 18:17:06 +0000130 (void)PreCondVars.apply(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000131 if (const auto *PreInits = cast_or_null<DeclStmt>(S.getPreInits())) {
George Burgess IV00f70bd2018-03-01 05:43:23 +0000132 for (const auto *I : PreInits->decls())
133 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataev5a3af132016-03-29 08:58:54 +0000134 }
Alexey Bataevab4ea222018-03-07 18:17:06 +0000135 PreCondVars.restore(CGF);
Alexey Bataev5a3af132016-03-29 08:58:54 +0000136 }
137
138public:
139 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
140 : CodeGenFunction::RunCleanupsScope(CGF) {
141 emitPreInitStmt(CGF, S);
142 }
143};
144
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000145class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
146 CodeGenFunction::OMPPrivateScope InlinedShareds;
147
148 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
149 return CGF.LambdaCaptureFields.lookup(VD) ||
150 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
151 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
152 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
153 }
154
155public:
156 OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
157 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
158 InlinedShareds(CGF) {
159 for (const auto *C : S.clauses()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000160 if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
161 if (const auto *PreInit =
162 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000163 for (const auto *I : PreInit->decls()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000164 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000165 CGF.EmitVarDecl(cast<VarDecl>(*I));
Alexey Bataevddf3db92018-04-13 17:31:06 +0000166 } else {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000167 CodeGenFunction::AutoVarEmission Emission =
168 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
169 CGF.EmitAutoVarCleanups(Emission);
170 }
171 }
172 }
173 } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
174 for (const Expr *E : UDP->varlists()) {
175 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
176 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
177 CGF.EmitVarDecl(*OED);
178 }
179 }
180 }
181 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
182 CGF.EmitOMPPrivateClause(S, InlinedShareds);
183 if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
184 if (const Expr *E = TG->getReductionRef())
185 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
186 }
187 const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
188 while (CS) {
189 for (auto &C : CS->captures()) {
190 if (C.capturesVariable() || C.capturesVariableByCopy()) {
191 auto *VD = C.getCapturedVar();
192 assert(VD == VD->getCanonicalDecl() &&
193 "Canonical decl must be captured.");
194 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
195 isCapturedVar(CGF, VD) ||
196 (CGF.CapturedStmtInfo &&
197 InlinedShareds.isGlobalVarCaptured(VD)),
198 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000199 C.getLocation());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000200 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
201 return CGF.EmitLValue(&DRE).getAddress();
202 });
203 }
204 }
205 CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
206 }
207 (void)InlinedShareds.Privatize();
208 }
209};
210
Alexey Bataev3392d762016-02-16 11:18:12 +0000211} // namespace
212
Alexey Bataevf8365372017-11-17 17:57:25 +0000213static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
214 const OMPExecutableDirective &S,
215 const RegionCodeGenTy &CodeGen);
216
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000217LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000218 if (const auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
219 if (const auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000220 OrigVD = OrigVD->getCanonicalDecl();
221 bool IsCaptured =
222 LambdaCaptureFields.lookup(OrigVD) ||
223 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
224 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
225 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), IsCaptured,
226 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
227 return EmitLValue(&DRE);
228 }
229 }
230 return EmitLValue(E);
231}
232
Alexey Bataev1189bd02016-01-26 12:20:39 +0000233llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000234 ASTContext &C = getContext();
Alexey Bataev1189bd02016-01-26 12:20:39 +0000235 llvm::Value *Size = nullptr;
236 auto SizeInChars = C.getTypeSizeInChars(Ty);
237 if (SizeInChars.isZero()) {
238 // getTypeSizeInChars() returns 0 for a VLA.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000239 while (const VariableArrayType *VAT = C.getAsVariableArrayType(Ty)) {
240 VlaSizePair VlaSize = getVLASize(VAT);
Sander de Smalen891af03a2018-02-03 13:55:59 +0000241 Ty = VlaSize.Type;
242 Size = Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts)
243 : VlaSize.NumElts;
Alexey Bataev1189bd02016-01-26 12:20:39 +0000244 }
245 SizeInChars = C.getTypeSizeInChars(Ty);
246 if (SizeInChars.isZero())
247 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000248 return Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
249 }
250 return CGM.getSize(SizeInChars);
Alexey Bataev1189bd02016-01-26 12:20:39 +0000251}
252
Alexey Bataev2377fe92015-09-10 08:12:02 +0000253void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000254 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000255 const RecordDecl *RD = S.getCapturedRecordDecl();
256 auto CurField = RD->field_begin();
257 auto CurCap = S.captures().begin();
258 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
259 E = S.capture_init_end();
260 I != E; ++I, ++CurField, ++CurCap) {
261 if (CurField->hasCapturedVLAType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000262 const VariableArrayType *VAT = CurField->getCapturedVLAType();
263 llvm::Value *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000264 CapturedVars.push_back(Val);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000265 } else if (CurCap->capturesThis()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000266 CapturedVars.push_back(CXXThisValue);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000267 } else if (CurCap->capturesVariableByCopy()) {
Alexey Bataev1e491372018-01-23 18:44:14 +0000268 llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000269
270 // If the field is not a pointer, we need to save the actual value
271 // and load it as a void pointer.
272 if (!CurField->getType()->isAnyPointerType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000273 ASTContext &Ctx = getContext();
274 Address DstAddr = CreateMemTemp(
Samuel Antao6d004262016-06-16 18:39:34 +0000275 Ctx.getUIntPtrType(),
Alexey Bataevddf3db92018-04-13 17:31:06 +0000276 Twine(CurCap->getCapturedVar()->getName(), ".casted"));
Samuel Antao6d004262016-06-16 18:39:34 +0000277 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
278
Alexey Bataevddf3db92018-04-13 17:31:06 +0000279 llvm::Value *SrcAddrVal = EmitScalarConversion(
Samuel Antao6d004262016-06-16 18:39:34 +0000280 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000281 Ctx.getPointerType(CurField->getType()), CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000282 LValue SrcLV =
283 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
284
285 // Store the value using the source type pointer.
286 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
287
288 // Load the value using the destination type pointer.
Alexey Bataev1e491372018-01-23 18:44:14 +0000289 CV = EmitLoadOfScalar(DstLV, CurCap->getLocation());
Samuel Antao6d004262016-06-16 18:39:34 +0000290 }
291 CapturedVars.push_back(CV);
292 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000293 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000294 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000295 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000296 }
297}
298
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000299static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc,
300 QualType DstType, StringRef Name,
301 LValue AddrLV,
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000302 bool isReferenceType = false) {
303 ASTContext &Ctx = CGF.getContext();
304
Alexey Bataevddf3db92018-04-13 17:31:06 +0000305 llvm::Value *CastedPtr = CGF.EmitScalarConversion(
306 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
307 Ctx.getPointerType(DstType), Loc);
308 Address TmpAddr =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000309 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
310 .getAddress();
311
312 // If we are dealing with references we need to return the address of the
313 // reference instead of the reference of the value.
314 if (isReferenceType) {
315 QualType RefType = Ctx.getLValueReferenceType(DstType);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000316 llvm::Value *RefVal = TmpAddr.getPointer();
317 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name, ".ref"));
318 LValue TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
319 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit=*/true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000320 }
321
322 return TmpAddr;
323}
324
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000325static QualType getCanonicalParamType(ASTContext &C, QualType T) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000326 if (T->isLValueReferenceType())
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000327 return C.getLValueReferenceType(
328 getCanonicalParamType(C, T.getNonReferenceType()),
329 /*SpelledAsLValue=*/false);
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000330 if (T->isPointerType())
331 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
Alexey Bataevddf3db92018-04-13 17:31:06 +0000332 if (const ArrayType *A = T->getAsArrayTypeUnsafe()) {
333 if (const auto *VLA = dyn_cast<VariableArrayType>(A))
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000334 return getCanonicalParamType(C, VLA->getElementType());
Alexey Bataevddf3db92018-04-13 17:31:06 +0000335 if (!A->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000336 return C.getCanonicalType(T);
337 }
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000338 return C.getCanonicalParamType(T);
339}
340
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000341namespace {
342 /// Contains required data for proper outlined function codegen.
343 struct FunctionOptions {
344 /// Captured statement for which the function is generated.
345 const CapturedStmt *S = nullptr;
346 /// true if cast to/from UIntPtr is required for variables captured by
347 /// value.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000348 const bool UIntPtrCastRequired = true;
Alexey Bataeve754b182017-08-09 19:38:53 +0000349 /// true if only casted arguments must be registered as local args or VLA
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000350 /// sizes.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000351 const bool RegisterCastedArgsOnly = false;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000352 /// Name of the generated function.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000353 const StringRef FunctionName;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000354 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
355 bool RegisterCastedArgsOnly,
Alexey Bataev4aa19052017-08-08 16:45:36 +0000356 StringRef FunctionName)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000357 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
358 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
Alexey Bataev4aa19052017-08-08 16:45:36 +0000359 FunctionName(FunctionName) {}
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000360 };
361}
362
Alexey Bataeve754b182017-08-09 19:38:53 +0000363static llvm::Function *emitOutlinedFunctionPrologue(
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000364 CodeGenFunction &CGF, FunctionArgList &Args,
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000365 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000366 &LocalAddrs,
367 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
368 &VLASizes,
369 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
370 const CapturedDecl *CD = FO.S->getCapturedDecl();
371 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000372 assert(CD->hasBody() && "missing CapturedDecl body");
373
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000374 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000375 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000376 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000377 ASTContext &Ctx = CGM.getContext();
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000378 FunctionArgList TargetArgs;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000379 Args.append(CD->param_begin(),
380 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000381 TargetArgs.append(
382 CD->param_begin(),
383 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000384 auto I = FO.S->captures().begin();
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000385 FunctionDecl *DebugFunctionDecl = nullptr;
386 if (!FO.UIntPtrCastRequired) {
387 FunctionProtoType::ExtProtoInfo EPI;
388 DebugFunctionDecl = FunctionDecl::Create(
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000389 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getBeginLoc(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000390 SourceLocation(), DeclarationName(), Ctx.VoidTy,
391 Ctx.getTrivialTypeSourceInfo(
392 Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI)),
393 SC_Static, /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
394 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000395 for (const FieldDecl *FD : RD->fields()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000396 QualType ArgType = FD->getType();
397 IdentifierInfo *II = nullptr;
398 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000399
400 // If this is a capture by copy and the type is not a pointer, the outlined
401 // function argument type should be uintptr and the value properly casted to
402 // uintptr. This is necessary given that the runtime library is only able to
403 // deal with pointers. We can pass in the same way the VLA type sizes to the
404 // outlined function.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000405 if (FO.UIntPtrCastRequired &&
406 ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
407 I->capturesVariableArrayType()))
408 ArgType = Ctx.getUIntPtrType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000409
410 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000411 CapVar = I->getCapturedVar();
412 II = CapVar->getIdentifier();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000413 } else if (I->capturesThis()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000414 II = &Ctx.Idents.get("this");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000415 } else {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000416 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000417 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000418 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000419 if (ArgType->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000420 ArgType = getCanonicalParamType(Ctx, ArgType);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000421 VarDecl *Arg;
422 if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
423 Arg = ParmVarDecl::Create(
424 Ctx, DebugFunctionDecl,
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000425 CapVar ? CapVar->getBeginLoc() : FD->getBeginLoc(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000426 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
427 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
428 } else {
429 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
430 II, ArgType, ImplicitParamDecl::Other);
431 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000432 Args.emplace_back(Arg);
433 // Do not cast arguments if we emit function with non-original types.
434 TargetArgs.emplace_back(
435 FO.UIntPtrCastRequired
436 ? Arg
437 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000438 ++I;
439 }
440 Args.append(
441 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
442 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000443 TargetArgs.append(
444 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
445 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000446
447 // Create the function declaration.
Alexey Bataev2377fe92015-09-10 08:12:02 +0000448 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000449 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000450 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
451
Alexey Bataevddf3db92018-04-13 17:31:06 +0000452 auto *F =
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000453 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
454 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000455 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
456 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000457 F->setDoesNotThrow();
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000458 F->setDoesNotRecurse();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000459
460 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000461 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000462 FO.S->getBeginLoc(), CD->getBody()->getBeginLoc());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000463 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000464 I = FO.S->captures().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000465 for (const FieldDecl *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000466 // Do not map arguments if we emit function with non-original types.
467 Address LocalAddr(Address::invalid());
468 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
469 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
470 TargetArgs[Cnt]);
471 } else {
472 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
473 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000474 // If we are capturing a pointer by copy we don't need to do anything, just
475 // use the value that we get from the arguments.
476 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000477 const VarDecl *CurVD = I->getCapturedVar();
Samuel Antao403ffd42016-07-27 22:49:49 +0000478 // If the variable is a reference we need to materialize it here.
479 if (CurVD->getType()->isReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000480 Address RefAddr = CGF.CreateMemTemp(
481 CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
482 CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
483 /*Volatile=*/false, CurVD->getType());
Samuel Antao403ffd42016-07-27 22:49:49 +0000484 LocalAddr = RefAddr;
485 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000486 if (!FO.RegisterCastedArgsOnly)
487 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000488 ++Cnt;
489 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000490 continue;
491 }
492
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000493 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
494 AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000495 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000496 if (FO.UIntPtrCastRequired) {
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000497 ArgLVal = CGF.MakeAddrLValue(
498 castValueFromUintptr(CGF, I->getLocation(), FD->getType(),
499 Args[Cnt]->getName(), ArgLVal),
500 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000501 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000502 llvm::Value *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
503 const VariableArrayType *VAT = FD->getCapturedVLAType();
504 VLASizes.try_emplace(Args[Cnt], VAT->getSizeExpr(), ExprArg);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000505 } else if (I->capturesVariable()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000506 const VarDecl *Var = I->getCapturedVar();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000507 QualType VarTy = Var->getType();
508 Address ArgAddr = ArgLVal.getAddress();
509 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000510 if (ArgLVal.getType()->isLValueReferenceType()) {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +0000511 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000512 } else if (!VarTy->isVariablyModifiedType() ||
513 !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000514 assert(ArgLVal.getType()->isPointerType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000515 ArgAddr = CGF.EmitLoadOfPointer(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000516 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
517 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000518 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000519 if (!FO.RegisterCastedArgsOnly) {
520 LocalAddrs.insert(
521 {Args[Cnt],
522 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
523 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000524 } else if (I->capturesVariableByCopy()) {
525 assert(!FD->getType()->isAnyPointerType() &&
526 "Not expecting a captured pointer.");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000527 const VarDecl *Var = I->getCapturedVar();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000528 QualType VarTy = Var->getType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000529 LocalAddrs.insert(
530 {Args[Cnt],
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000531 {Var, FO.UIntPtrCastRequired
532 ? castValueFromUintptr(CGF, I->getLocation(),
533 FD->getType(), Args[Cnt]->getName(),
534 ArgLVal, VarTy->isReferenceType())
535 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000536 } else {
537 // If 'this' is captured, load it into CXXThisValue.
538 assert(I->capturesThis());
Alexey Bataev1e491372018-01-23 18:44:14 +0000539 CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000540 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000541 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000542 ++Cnt;
543 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000544 }
545
Alexey Bataeve754b182017-08-09 19:38:53 +0000546 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000547}
548
549llvm::Function *
550CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
551 assert(
552 CapturedStmtInfo &&
553 "CapturedStmtInfo should be set when generating the captured function");
554 const CapturedDecl *CD = S.getCapturedDecl();
555 // Build the argument list.
556 bool NeedWrapperFunction =
557 getDebugInfo() &&
558 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
559 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000560 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000561 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000562 SmallString<256> Buffer;
563 llvm::raw_svector_ostream Out(Buffer);
564 Out << CapturedStmtInfo->getHelperName();
565 if (NeedWrapperFunction)
566 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000567 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataeve754b182017-08-09 19:38:53 +0000568 Out.str());
569 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
570 VLASizes, CXXThisValue, FO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000571 for (const auto &LocalAddrPair : LocalAddrs) {
572 if (LocalAddrPair.second.first) {
573 setAddrOfLocalVar(LocalAddrPair.second.first,
574 LocalAddrPair.second.second);
575 }
576 }
577 for (const auto &VLASizePair : VLASizes)
578 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000579 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000580 CapturedStmtInfo->EmitBody(*this, CD->getBody());
581 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000582 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000583 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000584
Alexey Bataevefd884d2017-08-04 21:26:25 +0000585 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000586 /*RegisterCastedArgsOnly=*/true,
587 CapturedStmtInfo->getHelperName());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000588 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000589 WrapperCGF.CapturedStmtInfo = CapturedStmtInfo;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000590 Args.clear();
591 LocalAddrs.clear();
592 VLASizes.clear();
593 llvm::Function *WrapperF =
594 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000595 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000596 llvm::SmallVector<llvm::Value *, 4> CallArgs;
597 for (const auto *Arg : Args) {
598 llvm::Value *CallArg;
599 auto I = LocalAddrs.find(Arg);
600 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000601 LValue LV = WrapperCGF.MakeAddrLValue(
602 I->second.second,
603 I->second.first ? I->second.first->getType() : Arg->getType(),
604 AlignmentSource::Decl);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000605 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000606 } else {
607 auto EI = VLASizes.find(Arg);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000608 if (EI != VLASizes.end()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000609 CallArg = EI->second.second;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000610 } else {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000611 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000612 Arg->getType(),
613 AlignmentSource::Decl);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000614 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000615 }
616 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000617 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000618 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000619 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getBeginLoc(),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000620 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000621 WrapperCGF.FinishFunction();
622 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000623}
624
Alexey Bataev9959db52014-05-06 10:08:46 +0000625//===----------------------------------------------------------------------===//
626// OpenMP Directive Emission
627//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000628void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000629 Address DestAddr, Address SrcAddr, QualType OriginalType,
Alexey Bataevddf3db92018-04-13 17:31:06 +0000630 const llvm::function_ref<void(Address, Address)> CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000631 // Perform element-by-element initialization.
632 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000633
634 // Drill down to the base element type on both arrays.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000635 const ArrayType *ArrayTy = OriginalType->getAsArrayTypeUnsafe();
636 llvm::Value *NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
John McCall7f416cc2015-09-08 08:05:57 +0000637 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
638
Alexey Bataevddf3db92018-04-13 17:31:06 +0000639 llvm::Value *SrcBegin = SrcAddr.getPointer();
640 llvm::Value *DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000641 // Cast from pointer to array type to pointer to single element.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000642 llvm::Value *DestEnd = Builder.CreateGEP(DestBegin, NumElements);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000643 // The basic structure here is a while-do loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000644 llvm::BasicBlock *BodyBB = createBasicBlock("omp.arraycpy.body");
645 llvm::BasicBlock *DoneBB = createBasicBlock("omp.arraycpy.done");
646 llvm::Value *IsEmpty =
Alexey Bataev420d45b2015-04-14 05:11:24 +0000647 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
648 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000649
Alexey Bataev420d45b2015-04-14 05:11:24 +0000650 // Enter the loop body, making that address the current address.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000651 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000652 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000653
654 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
655
656 llvm::PHINode *SrcElementPHI =
657 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
658 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
659 Address SrcElementCurrent =
660 Address(SrcElementPHI,
661 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
662
663 llvm::PHINode *DestElementPHI =
664 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
665 DestElementPHI->addIncoming(DestBegin, EntryBB);
666 Address DestElementCurrent =
667 Address(DestElementPHI,
668 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000669
Alexey Bataev420d45b2015-04-14 05:11:24 +0000670 // Emit copy.
671 CopyGen(DestElementCurrent, SrcElementCurrent);
672
673 // Shift the address forward by one element.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000674 llvm::Value *DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000675 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataevddf3db92018-04-13 17:31:06 +0000676 llvm::Value *SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000677 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000678 // Check whether we've reached the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000679 llvm::Value *Done =
Alexey Bataev420d45b2015-04-14 05:11:24 +0000680 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
681 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000682 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
683 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000684
685 // Done.
686 EmitBlock(DoneBB, /*IsFinished=*/true);
687}
688
John McCall7f416cc2015-09-08 08:05:57 +0000689void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
690 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000691 const VarDecl *SrcVD, const Expr *Copy) {
692 if (OriginalType->isArrayType()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000693 const auto *BO = dyn_cast<BinaryOperator>(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000694 if (BO && BO->getOpcode() == BO_Assign) {
695 // Perform simple memcpy for simple copying.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000696 LValue Dest = MakeAddrLValue(DestAddr, OriginalType);
697 LValue Src = MakeAddrLValue(SrcAddr, OriginalType);
698 EmitAggregateAssign(Dest, Src, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000699 } else {
700 // For arrays with complex element types perform element by element
701 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000702 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000703 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000704 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000705 // Working with the single array element, so have to remap
706 // destination and source variables to corresponding array
707 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000708 CodeGenFunction::OMPPrivateScope Remap(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000709 Remap.addPrivate(DestVD, [DestElement]() { return DestElement; });
710 Remap.addPrivate(SrcVD, [SrcElement]() { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000711 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000712 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000713 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000714 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000715 } else {
716 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000717 CodeGenFunction::OMPPrivateScope Remap(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +0000718 Remap.addPrivate(SrcVD, [SrcAddr]() { return SrcAddr; });
719 Remap.addPrivate(DestVD, [DestAddr]() { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000720 (void)Remap.Privatize();
721 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000722 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000723 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000724}
725
Alexey Bataev69c62a92015-04-15 04:52:20 +0000726bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
727 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000728 if (!HaveInsertPoint())
729 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000730 bool FirstprivateIsLastprivate = false;
731 llvm::DenseSet<const VarDecl *> Lastprivates;
732 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
733 for (const auto *D : C->varlists())
734 Lastprivates.insert(
735 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
736 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000737 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev475a7442018-01-12 19:39:11 +0000738 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
739 getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind());
740 // Force emission of the firstprivate copy if the directive does not emit
741 // outlined function, like omp for, omp simd, omp distribute etc.
742 bool MustEmitFirstprivateCopy =
743 CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000744 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000745 auto IRef = C->varlist_begin();
746 auto InitsRef = C->inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000747 for (const Expr *IInit : C->private_copies()) {
748 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000749 bool ThisFirstprivateIsLastprivate =
750 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataevddf3db92018-04-13 17:31:06 +0000751 const FieldDecl *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev475a7442018-01-12 19:39:11 +0000752 if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000753 !FD->getType()->isReferenceType()) {
754 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
755 ++IRef;
756 ++InitsRef;
757 continue;
758 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000759 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000760 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000761 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000762 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
763 const auto *VDInit =
764 cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000765 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000766 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
767 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
768 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000769 LValue OriginalLVal = EmitLValue(&DRE);
Alexey Bataevfeddd642016-04-22 09:05:03 +0000770 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000771 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000772 // Emit VarDecl with copy init for arrays.
773 // Get the address of the original variable captured in current
774 // captured region.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000775 IsRegistered = PrivateScope.addPrivate(
776 OrigVD, [this, VD, Type, OriginalLVal, VDInit]() {
777 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
778 const Expr *Init = VD->getInit();
779 if (!isa<CXXConstructExpr>(Init) ||
780 isTrivialInitializer(Init)) {
781 // Perform simple memcpy.
782 LValue Dest =
783 MakeAddrLValue(Emission.getAllocatedAddress(), Type);
784 EmitAggregateAssign(Dest, OriginalLVal, Type);
785 } else {
786 EmitOMPAggregateAssign(
787 Emission.getAllocatedAddress(), OriginalLVal.getAddress(),
788 Type,
789 [this, VDInit, Init](Address DestElement,
790 Address SrcElement) {
791 // Clean up any temporaries needed by the
792 // initialization.
793 RunCleanupsScope InitScope(*this);
794 // Emit initialization for single element.
795 setAddrOfLocalVar(VDInit, SrcElement);
796 EmitAnyExprToMem(Init, DestElement,
797 Init->getType().getQualifiers(),
798 /*IsInitializer*/ false);
799 LocalDeclMap.erase(VDInit);
800 });
801 }
802 EmitAutoVarCleanups(Emission);
803 return Emission.getAllocatedAddress();
804 });
Alexey Bataev69c62a92015-04-15 04:52:20 +0000805 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000806 Address OriginalAddr = OriginalLVal.getAddress();
807 IsRegistered = PrivateScope.addPrivate(
808 OrigVD, [this, VDInit, OriginalAddr, VD]() {
809 // Emit private VarDecl with copy init.
810 // Remap temp VDInit variable to the address of the original
811 // variable (for proper handling of captured global variables).
812 setAddrOfLocalVar(VDInit, OriginalAddr);
813 EmitDecl(*VD);
814 LocalDeclMap.erase(VDInit);
815 return GetAddrOfLocalVar(VD);
816 });
Alexey Bataev69c62a92015-04-15 04:52:20 +0000817 }
818 assert(IsRegistered &&
819 "firstprivate var already registered as private");
820 // Silence the warning about unused variable.
821 (void)IsRegistered;
822 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000823 ++IRef;
824 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000825 }
826 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000827 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000828}
829
Alexey Bataev03b340a2014-10-21 03:16:40 +0000830void CodeGenFunction::EmitOMPPrivateClause(
831 const OMPExecutableDirective &D,
832 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000833 if (!HaveInsertPoint())
834 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000835 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000836 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000837 auto IRef = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000838 for (const Expr *IInit : C->private_copies()) {
839 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000840 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000841 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
842 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() {
843 // Emit private VarDecl with copy init.
844 EmitDecl(*VD);
845 return GetAddrOfLocalVar(VD);
846 });
Alexey Bataev50a64582015-04-22 12:24:45 +0000847 assert(IsRegistered && "private var already registered as private");
848 // Silence the warning about unused variable.
849 (void)IsRegistered;
850 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000851 ++IRef;
852 }
853 }
854}
855
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000856bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000857 if (!HaveInsertPoint())
858 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000859 // threadprivate_var1 = master_threadprivate_var1;
860 // operator=(threadprivate_var2, master_threadprivate_var2);
861 // ...
862 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000863 llvm::DenseSet<const VarDecl *> CopiedVars;
864 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000865 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000866 auto IRef = C->varlist_begin();
867 auto ISrcRef = C->source_exprs().begin();
868 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000869 for (const Expr *AssignOp : C->assignment_ops()) {
870 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000871 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000872 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000873 // Get the address of the master variable. If we are emitting code with
874 // TLS support, the address is passed from the master as field in the
875 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000876 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000877 if (getLangOpts().OpenMPUseTLS &&
878 getContext().getTargetInfo().isTLSSupported()) {
879 assert(CapturedStmtInfo->lookup(VD) &&
880 "Copyin threadprivates should have been captured!");
881 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
882 VK_LValue, (*IRef)->getExprLoc());
883 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000884 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000885 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000886 MasterAddr =
887 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
888 : CGM.GetAddrOfGlobal(VD),
889 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000890 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000891 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000892 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000893 if (CopiedVars.size() == 1) {
894 // At first check if current thread is a master thread. If it is, no
895 // need to copy data.
896 CopyBegin = createBasicBlock("copyin.not.master");
897 CopyEnd = createBasicBlock("copyin.not.master.end");
898 Builder.CreateCondBr(
899 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000900 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
Alexey Bataevddf3db92018-04-13 17:31:06 +0000901 Builder.CreatePtrToInt(PrivateAddr.getPointer(),
902 CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000903 CopyBegin, CopyEnd);
904 EmitBlock(CopyBegin);
905 }
Alexey Bataevddf3db92018-04-13 17:31:06 +0000906 const auto *SrcVD =
907 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
908 const auto *DestVD =
909 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000910 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000911 }
912 ++IRef;
913 ++ISrcRef;
914 ++IDestRef;
915 }
916 }
917 if (CopyEnd) {
918 // Exit out of copying procedure for non-master thread.
919 EmitBlock(CopyEnd, /*IsFinished=*/true);
920 return true;
921 }
922 return false;
923}
924
Alexey Bataev38e89532015-04-16 04:54:05 +0000925bool CodeGenFunction::EmitOMPLastprivateClauseInit(
926 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000927 if (!HaveInsertPoint())
928 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000929 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000930 llvm::DenseSet<const VarDecl *> SIMDLCVs;
931 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000932 const auto *LoopDirective = cast<OMPLoopDirective>(&D);
933 for (const Expr *C : LoopDirective->counters()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000934 SIMDLCVs.insert(
935 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
936 }
937 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000938 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000939 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000940 HasAtLeastOneLastprivate = true;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000941 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
942 !getLangOpts().OpenMPSimd)
Alexey Bataevf93095a2016-05-05 08:46:22 +0000943 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000944 auto IRef = C->varlist_begin();
945 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +0000946 for (const Expr *IInit : C->private_copies()) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000947 // Keep the address of the original variable for future update at the end
948 // of the loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +0000949 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000950 // Taskloops do not require additional initialization, it is done in
951 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000952 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000953 const auto *DestVD =
954 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
955 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() {
Alexey Bataev38e89532015-04-16 04:54:05 +0000956 DeclRefExpr DRE(
957 const_cast<VarDecl *>(OrigVD),
958 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
959 OrigVD) != nullptr,
960 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
961 return EmitLValue(&DRE).getAddress();
962 });
963 // Check if the variable is also a firstprivate: in this case IInit is
964 // not generated. Initialization of this variable will happen in codegen
965 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000966 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +0000967 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
968 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() {
Alexey Bataevf93095a2016-05-05 08:46:22 +0000969 // Emit private VarDecl with copy init.
970 EmitDecl(*VD);
971 return GetAddrOfLocalVar(VD);
972 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000973 assert(IsRegistered &&
974 "lastprivate var already registered as private");
975 (void)IsRegistered;
976 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000977 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000978 ++IRef;
979 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000980 }
981 }
982 return HasAtLeastOneLastprivate;
983}
984
985void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000986 const OMPExecutableDirective &D, bool NoFinals,
987 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000988 if (!HaveInsertPoint())
989 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000990 // Emit following code:
991 // if (<IsLastIterCond>) {
992 // orig_var1 = private_orig_var1;
993 // ...
994 // orig_varn = private_orig_varn;
995 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000996 llvm::BasicBlock *ThenBB = nullptr;
997 llvm::BasicBlock *DoneBB = nullptr;
998 if (IsLastIterCond) {
999 ThenBB = createBasicBlock(".omp.lastprivate.then");
1000 DoneBB = createBasicBlock(".omp.lastprivate.done");
1001 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
1002 EmitBlock(ThenBB);
1003 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001004 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
1005 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001006 if (const auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001007 auto IC = LoopDirective->counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001008 for (const Expr *F : LoopDirective->finals()) {
1009 const auto *D =
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001010 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1011 if (NoFinals)
1012 AlreadyEmittedVars.insert(D);
1013 else
1014 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001015 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001016 }
1017 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001018 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1019 auto IRef = C->varlist_begin();
1020 auto ISrcRef = C->source_exprs().begin();
1021 auto IDestRef = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001022 for (const Expr *AssignOp : C->assignment_ops()) {
1023 const auto *PrivateVD =
1024 cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001025 QualType Type = PrivateVD->getType();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001026 const auto *CanonicalVD = PrivateVD->getCanonicalDecl();
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001027 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1028 // If lastprivate variable is a loop control variable for loop-based
1029 // directive, update its value before copyin back to original
1030 // variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001031 if (const Expr *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001032 EmitIgnoredExpr(FinalExpr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001033 const auto *SrcVD =
1034 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1035 const auto *DestVD =
1036 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001037 // Get the address of the original variable.
1038 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
1039 // Get the address of the private variable.
1040 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001041 if (const auto *RefTy = PrivateVD->getType()->getAs<ReferenceType>())
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001042 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +00001043 Address(Builder.CreateLoad(PrivateAddr),
1044 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001045 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +00001046 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001047 ++IRef;
1048 ++ISrcRef;
1049 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +00001050 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001051 if (const Expr *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00001052 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001053 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001054 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001055 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +00001056}
1057
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001058void CodeGenFunction::EmitOMPReductionClauseInit(
1059 const OMPExecutableDirective &D,
1060 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001061 if (!HaveInsertPoint())
1062 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001063 SmallVector<const Expr *, 4> Shareds;
1064 SmallVector<const Expr *, 4> Privates;
1065 SmallVector<const Expr *, 4> ReductionOps;
1066 SmallVector<const Expr *, 4> LHSs;
1067 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001068 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001069 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001070 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001071 auto ILHS = C->lhs_exprs().begin();
1072 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001073 for (const Expr *Ref : C->varlists()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001074 Shareds.emplace_back(Ref);
1075 Privates.emplace_back(*IPriv);
1076 ReductionOps.emplace_back(*IRed);
1077 LHSs.emplace_back(*ILHS);
1078 RHSs.emplace_back(*IRHS);
1079 std::advance(IPriv, 1);
1080 std::advance(IRed, 1);
1081 std::advance(ILHS, 1);
1082 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001083 }
1084 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001085 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1086 unsigned Count = 0;
1087 auto ILHS = LHSs.begin();
1088 auto IRHS = RHSs.begin();
1089 auto IPriv = Privates.begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001090 for (const Expr *IRef : Shareds) {
1091 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001092 // Emit private VarDecl with reduction init.
1093 RedCG.emitSharedLValue(*this, Count);
1094 RedCG.emitAggregateType(*this, Count);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001095 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001096 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1097 RedCG.getSharedLValue(Count),
1098 [&Emission](CodeGenFunction &CGF) {
1099 CGF.EmitAutoVarInit(Emission);
1100 return true;
1101 });
1102 EmitAutoVarCleanups(Emission);
1103 Address BaseAddr = RedCG.adjustPrivateAddress(
1104 *this, Count, Emission.getAllocatedAddress());
1105 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataevddf3db92018-04-13 17:31:06 +00001106 RedCG.getBaseDecl(Count), [BaseAddr]() { return BaseAddr; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001107 assert(IsRegistered && "private var already registered as private");
1108 // Silence the warning about unused variable.
1109 (void)IsRegistered;
1110
Alexey Bataevddf3db92018-04-13 17:31:06 +00001111 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1112 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001113 QualType Type = PrivateVD->getType();
1114 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1115 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001116 // Store the address of the original variable associated with the LHS
1117 // implicit variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001118 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001119 return RedCG.getSharedLValue(Count).getAddress();
1120 });
Alexey Bataevddf3db92018-04-13 17:31:06 +00001121 PrivateScope.addPrivate(
1122 RHSVD, [this, PrivateVD]() { return GetAddrOfLocalVar(PrivateVD); });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001123 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1124 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001125 // Store the address of the original variable associated with the LHS
1126 // implicit variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001127 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001128 return RedCG.getSharedLValue(Count).getAddress();
1129 });
Alexey Bataevddf3db92018-04-13 17:31:06 +00001130 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001131 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1132 ConvertTypeForMem(RHSVD->getType()),
1133 "rhs.begin");
1134 });
1135 } else {
1136 QualType Type = PrivateVD->getType();
1137 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1138 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1139 // Store the address of the original variable associated with the LHS
1140 // implicit variable.
1141 if (IsArray) {
1142 OriginalAddr = Builder.CreateElementBitCast(
1143 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1144 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001145 PrivateScope.addPrivate(LHSVD, [OriginalAddr]() { return OriginalAddr; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001146 PrivateScope.addPrivate(
Alexey Bataevddf3db92018-04-13 17:31:06 +00001147 RHSVD, [this, PrivateVD, RHSVD, IsArray]() {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001148 return IsArray
1149 ? Builder.CreateElementBitCast(
1150 GetAddrOfLocalVar(PrivateVD),
1151 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1152 : GetAddrOfLocalVar(PrivateVD);
1153 });
1154 }
1155 ++ILHS;
1156 ++IRHS;
1157 ++IPriv;
1158 ++Count;
1159 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001160}
1161
1162void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001163 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001164 if (!HaveInsertPoint())
1165 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001166 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001167 llvm::SmallVector<const Expr *, 8> LHSExprs;
1168 llvm::SmallVector<const Expr *, 8> RHSExprs;
1169 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001170 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001171 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001172 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001173 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001174 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1175 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1176 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1177 }
1178 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001179 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1180 isOpenMPParallelDirective(D.getDirectiveKind()) ||
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001181 ReductionKind == OMPD_simd;
1182 bool SimpleReduction = ReductionKind == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001183 // Emit nowait reduction if nowait clause is present or directive is a
1184 // parallel directive (it always has implicit barrier).
1185 CGM.getOpenMPRuntime().emitReduction(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001186 *this, D.getEndLoc(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001187 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001188 }
1189}
1190
Alexey Bataev61205072016-03-02 04:57:40 +00001191static void emitPostUpdateForReductionClause(
1192 CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001193 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev61205072016-03-02 04:57:40 +00001194 if (!CGF.HaveInsertPoint())
1195 return;
1196 llvm::BasicBlock *DoneBB = nullptr;
1197 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001198 if (const Expr *PostUpdate = C->getPostUpdateExpr()) {
Alexey Bataev61205072016-03-02 04:57:40 +00001199 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001200 if (llvm::Value *Cond = CondGen(CGF)) {
Alexey Bataev61205072016-03-02 04:57:40 +00001201 // If the first post-update expression is found, emit conditional
1202 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001203 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
Alexey Bataev61205072016-03-02 04:57:40 +00001204 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1205 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1206 CGF.EmitBlock(ThenBB);
1207 }
1208 }
1209 CGF.EmitIgnoredExpr(PostUpdate);
1210 }
1211 }
1212 if (DoneBB)
1213 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1214}
1215
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001216namespace {
1217/// Codegen lambda for appending distribute lower and upper bounds to outlined
1218/// parallel function. This is necessary for combined constructs such as
1219/// 'distribute parallel for'
1220typedef llvm::function_ref<void(CodeGenFunction &,
1221 const OMPExecutableDirective &,
1222 llvm::SmallVectorImpl<llvm::Value *> &)>
1223 CodeGenBoundParametersTy;
1224} // anonymous namespace
1225
1226static void emitCommonOMPParallelDirective(
1227 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1228 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1229 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001230 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001231 llvm::Value *OutlinedFn =
1232 CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1233 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001234 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001235 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001236 llvm::Value *NumThreads =
1237 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1238 /*IgnoreResultAssign=*/true);
Alexey Bataev1d677132015-04-22 13:57:31 +00001239 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001240 CGF, NumThreads, NumThreadsClause->getBeginLoc());
Alexey Bataev1d677132015-04-22 13:57:31 +00001241 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001242 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001243 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001244 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001245 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getBeginLoc());
Alexey Bataev7f210c62015-06-18 13:40:03 +00001246 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001247 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001248 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1249 if (C->getNameModifier() == OMPD_unknown ||
1250 C->getNameModifier() == OMPD_parallel) {
1251 IfCond = C->getCondition();
1252 break;
1253 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001254 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001255
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001256 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001257 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001258 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1259 // lower and upper bounds with the pragma 'for' chunking mechanism.
1260 // The following lambda takes care of appending the lower and upper bound
1261 // parameters when necessary
1262 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001263 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001264 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getBeginLoc(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001265 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001266}
1267
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001268static void emitEmptyBoundParameters(CodeGenFunction &,
1269 const OMPExecutableDirective &,
1270 llvm::SmallVectorImpl<llvm::Value *> &) {}
1271
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001272void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001273 // Emit parallel region as a standalone region.
Alexey Bataevc99042b2018-03-15 18:10:54 +00001274 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001275 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001276 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001277 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001278 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1279 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001280 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001281 // propagation master's thread values of threadprivate variables to local
1282 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001283 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001284 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev25e5b442015-09-15 12:52:43 +00001285 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001286 }
1287 CGF.EmitOMPPrivateClause(S, PrivateScope);
1288 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1289 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00001290 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001291 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001292 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001293 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1294 emitEmptyBoundParameters);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001295 emitPostUpdateForReductionClause(*this, S,
1296 [](CodeGenFunction &) { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001297}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001298
Alexey Bataev0f34da12015-07-02 04:17:07 +00001299void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1300 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001301 RunCleanupsScope BodyScope(*this);
1302 // Update counters values on current iteration.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001303 for (const Expr *UE : D.updates())
1304 EmitIgnoredExpr(UE);
Alexander Musman3276a272015-03-21 10:12:56 +00001305 // Update the linear variables.
Alexey Bataev617db5f2017-12-04 15:38:33 +00001306 // In distribute directives only loop counters may be marked as linear, no
1307 // need to generate the code for them.
1308 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1309 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001310 for (const Expr *UE : C->updates())
1311 EmitIgnoredExpr(UE);
Alexey Bataev617db5f2017-12-04 15:38:33 +00001312 }
Alexander Musman3276a272015-03-21 10:12:56 +00001313 }
1314
Alexander Musmana5f070a2014-10-01 06:03:56 +00001315 // On a continue in the body, jump to the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001316 JumpDest Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001317 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001318 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001319 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001320 // The end (updates/cleanups).
1321 EmitBlock(Continue.getBlock());
1322 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001323}
1324
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001325void CodeGenFunction::EmitOMPInnerLoop(
1326 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1327 const Expr *IncExpr,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001328 const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
1329 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001330 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001331
1332 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001333 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001334 EmitBlock(CondBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001335 const SourceRange R = S.getSourceRange();
Amara Emerson652795d2016-11-10 14:44:30 +00001336 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1337 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001338
1339 // If there are any cleanups between here and the loop-exit scope,
1340 // create a block to stage a loop exit along.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001341 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001342 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001343 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001344
Alexey Bataevddf3db92018-04-13 17:31:06 +00001345 llvm::BasicBlock *LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001346
Alexey Bataev2df54a02015-03-12 08:53:29 +00001347 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001348 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001349 if (ExitBlock != LoopExit.getBlock()) {
1350 EmitBlock(ExitBlock);
1351 EmitBranchThroughCleanup(LoopExit);
1352 }
1353
1354 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001355 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001356
1357 // Create a block for the increment.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001358 JumpDest Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001359 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1360
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001361 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001362
1363 // Emit "IV = IV + 1" and a back-edge to the condition block.
1364 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001365 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001366 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001367 BreakContinueStack.pop_back();
1368 EmitBranch(CondBlock);
1369 LoopStack.pop();
1370 // Emit the fall-through block.
1371 EmitBlock(LoopExit.getBlock());
1372}
1373
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001374bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001375 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001376 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001377 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001378 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001379 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001380 for (const Expr *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001381 HasLinears = true;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001382 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
1383 if (const auto *Ref =
1384 dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001385 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001386 const auto *OrigVD = cast<VarDecl>(Ref->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001387 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1388 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1389 VD->getInit()->getType(), VK_LValue,
1390 VD->getInit()->getExprLoc());
1391 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1392 VD->getType()),
1393 /*capturedByInit=*/false);
1394 EmitAutoVarCleanups(Emission);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001395 } else {
Alexey Bataevef549a82016-03-09 09:49:09 +00001396 EmitVarDecl(*VD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001397 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001398 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001399 // Emit the linear steps for the linear clauses.
1400 // If a step is not constant, it is pre-calculated before the loop.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001401 if (const auto *CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1402 if (const auto *SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001403 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001404 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001405 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001406 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001407 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001408 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001409}
1410
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001411void CodeGenFunction::EmitOMPLinearClauseFinal(
1412 const OMPLoopDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001413 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001414 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001415 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001416 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001417 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001418 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001419 auto IC = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001420 for (const Expr *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001421 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001422 if (llvm::Value *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001423 // If the first post-update expression is found, emit conditional
1424 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001425 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.linear.pu");
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001426 DoneBB = createBasicBlock(".omp.linear.pu.done");
1427 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1428 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001429 }
1430 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001431 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
Alexey Bataev39f915b82015-05-08 10:41:21 +00001432 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001433 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001434 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001435 Address OrigAddr = EmitLValue(&DRE).getAddress();
1436 CodeGenFunction::OMPPrivateScope VarScope(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001437 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001438 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001439 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001440 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001441 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001442 if (const Expr *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001443 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001444 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001445 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001446 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001447}
1448
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001449static void emitAlignedClause(CodeGenFunction &CGF,
1450 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001451 if (!CGF.HaveInsertPoint())
1452 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001453 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001454 unsigned ClauseAlignment = 0;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001455 if (const Expr *AlignmentExpr = Clause->getAlignment()) {
1456 auto *AlignmentCI =
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001457 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1458 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001459 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001460 for (const Expr *E : Clause->varlists()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001461 unsigned Alignment = ClauseAlignment;
1462 if (Alignment == 0) {
1463 // OpenMP [2.8.1, Description]
1464 // If no optional parameter is specified, implementation-defined default
1465 // alignments for SIMD instructions on the target platforms are assumed.
1466 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001467 CGF.getContext()
1468 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1469 E->getType()->getPointeeType()))
1470 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001471 }
1472 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1473 "alignment is not power of 2");
1474 if (Alignment != 0) {
1475 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1476 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1477 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001478 }
1479 }
1480}
1481
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001482void CodeGenFunction::EmitOMPPrivateLoopCounters(
1483 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1484 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001485 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001486 auto I = S.private_counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001487 for (const Expr *E : S.counters()) {
1488 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1489 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataevab4ea222018-03-07 18:17:06 +00001490 // Emit var without initialization.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001491 AutoVarEmission VarEmission = EmitAutoVarAlloca(*PrivateVD);
Alexey Bataevab4ea222018-03-07 18:17:06 +00001492 EmitAutoVarCleanups(VarEmission);
1493 LocalDeclMap.erase(PrivateVD);
1494 (void)LoopScope.addPrivate(VD, [&VarEmission]() {
1495 return VarEmission.getAllocatedAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001496 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001497 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1498 VD->hasGlobalStorage()) {
Alexey Bataevab4ea222018-03-07 18:17:06 +00001499 (void)LoopScope.addPrivate(PrivateVD, [this, VD, E]() {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001500 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1501 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1502 E->getType(), VK_LValue, E->getExprLoc());
1503 return EmitLValue(&DRE).getAddress();
1504 });
Alexey Bataevab4ea222018-03-07 18:17:06 +00001505 } else {
1506 (void)LoopScope.addPrivate(PrivateVD, [&VarEmission]() {
1507 return VarEmission.getAllocatedAddress();
1508 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001509 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001510 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001511 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00001512 // Privatize extra loop counters used in loops for ordered(n) clauses.
1513 for (const auto *C : S.getClausesOfKind<OMPOrderedClause>()) {
1514 if (!C->getNumForLoops())
1515 continue;
1516 for (unsigned I = S.getCollapsedNumber(),
1517 E = C->getLoopNumIterations().size();
1518 I < E; ++I) {
Mike Rice0ed46662018-09-20 17:19:41 +00001519 const auto *DRE = cast<DeclRefExpr>(C->getLoopCounter(I));
Alexey Bataevf138fda2018-08-13 19:04:24 +00001520 const auto *VD = cast<VarDecl>(DRE->getDecl());
1521 // Override only those variables that are really emitted already.
1522 if (LocalDeclMap.count(VD)) {
1523 (void)LoopScope.addPrivate(VD, [this, DRE, VD]() {
1524 return CreateMemTemp(DRE->getType(), VD->getName());
1525 });
1526 }
1527 }
1528 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001529}
1530
Alexey Bataev62dbb972015-04-22 11:59:37 +00001531static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1532 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1533 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001534 if (!CGF.HaveInsertPoint())
1535 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001536 {
1537 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001538 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001539 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001540 // Get initial values of real counters.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001541 for (const Expr *I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001542 CGF.EmitIgnoredExpr(I);
1543 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001544 }
1545 // Check that loop is executed at least one time.
1546 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1547}
1548
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001549void CodeGenFunction::EmitOMPLinearClause(
1550 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1551 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001552 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001553 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1554 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001555 const auto *LoopDirective = cast<OMPLoopDirective>(&D);
1556 for (const Expr *C : LoopDirective->counters()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001557 SIMDLCVs.insert(
1558 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1559 }
1560 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001561 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001562 auto CurPrivate = C->privates().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001563 for (const Expr *E : C->varlists()) {
1564 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1565 const auto *PrivateVD =
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001566 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001567 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001568 bool IsRegistered = PrivateScope.addPrivate(VD, [this, PrivateVD]() {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001569 // Emit private VarDecl with copy init.
1570 EmitVarDecl(*PrivateVD);
1571 return GetAddrOfLocalVar(PrivateVD);
1572 });
1573 assert(IsRegistered && "linear var already registered as private");
1574 // Silence the warning about unused variable.
1575 (void)IsRegistered;
Alexey Bataevddf3db92018-04-13 17:31:06 +00001576 } else {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001577 EmitVarDecl(*PrivateVD);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001578 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001579 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001580 }
1581 }
1582}
1583
Alexey Bataev45bfad52015-08-21 12:19:04 +00001584static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001585 const OMPExecutableDirective &D,
1586 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001587 if (!CGF.HaveInsertPoint())
1588 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001589 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001590 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1591 /*ignoreResult=*/true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001592 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Alexey Bataev45bfad52015-08-21 12:19:04 +00001593 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1594 // In presence of finite 'safelen', it may be unsafe to mark all
1595 // the memory instructions parallel, because loop-carried
1596 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001597 if (!IsMonotonic)
1598 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001599 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001600 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1601 /*ignoreResult=*/true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001602 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001603 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001604 // In presence of finite 'safelen', it may be unsafe to mark all
1605 // the memory instructions parallel, because loop-carried
1606 // dependences of 'safelen' iterations are possible.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001607 CGF.LoopStack.setParallel(/*Enable=*/false);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001608 }
1609}
1610
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001611void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1612 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001613 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001614 LoopStack.setParallel(!IsMonotonic);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001615 LoopStack.setVectorizeEnable();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001616 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001617}
1618
Alexey Bataevef549a82016-03-09 09:49:09 +00001619void CodeGenFunction::EmitOMPSimdFinal(
1620 const OMPLoopDirective &D,
Alexey Bataevddf3db92018-04-13 17:31:06 +00001621 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001622 if (!HaveInsertPoint())
1623 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001624 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001625 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001626 auto IPC = D.private_counters().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001627 for (const Expr *F : D.finals()) {
1628 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
1629 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1630 const auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001631 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1632 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001633 if (!DoneBB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001634 if (llvm::Value *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001635 // If the first post-update expression is found, emit conditional
1636 // block if it was requested.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001637 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.final.then");
Alexey Bataevef549a82016-03-09 09:49:09 +00001638 DoneBB = createBasicBlock(".omp.final.done");
1639 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1640 EmitBlock(ThenBB);
1641 }
1642 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001643 Address OrigAddr = Address::invalid();
Alexey Bataevab4ea222018-03-07 18:17:06 +00001644 if (CED) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001645 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
Alexey Bataevab4ea222018-03-07 18:17:06 +00001646 } else {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001647 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1648 /*RefersToEnclosingVariableOrCapture=*/false,
1649 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1650 OrigAddr = EmitLValue(&DRE).getAddress();
1651 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001652 OMPPrivateScope VarScope(*this);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001653 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001654 (void)VarScope.Privatize();
1655 EmitIgnoredExpr(F);
1656 }
1657 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001658 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001659 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001660 if (DoneBB)
1661 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001662}
1663
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001664static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1665 const OMPLoopDirective &S,
1666 CodeGenFunction::JumpDest LoopExit) {
1667 CGF.EmitOMPLoopBody(S, LoopExit);
1668 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001669}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001670
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001671/// Emit a helper variable and return corresponding lvalue.
1672static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1673 const DeclRefExpr *Helper) {
1674 auto VDecl = cast<VarDecl>(Helper->getDecl());
1675 CGF.EmitVarDecl(*VDecl);
1676 return CGF.EmitLValue(Helper);
1677}
1678
Alexey Bataevf8365372017-11-17 17:57:25 +00001679static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1680 PrePostActionTy &Action) {
1681 Action.Enter(CGF);
1682 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1683 "Expected simd directive");
1684 OMPLoopScope PreInitScope(CGF, S);
1685 // if (PreCond) {
1686 // for (IV in 0..LastIteration) BODY;
1687 // <Final counter/linear vars updates>;
1688 // }
1689 //
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001690 if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
1691 isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
1692 isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
1693 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1694 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1695 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001696
Alexey Bataevf8365372017-11-17 17:57:25 +00001697 // Emit: if (PreCond) - begin.
1698 // If the condition constant folds and can be elided, avoid emitting the
1699 // whole loop.
1700 bool CondConstant;
1701 llvm::BasicBlock *ContBlock = nullptr;
1702 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1703 if (!CondConstant)
1704 return;
1705 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001706 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("simd.if.then");
Alexey Bataevf8365372017-11-17 17:57:25 +00001707 ContBlock = CGF.createBasicBlock("simd.if.end");
1708 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1709 CGF.getProfileCount(&S));
1710 CGF.EmitBlock(ThenBlock);
1711 CGF.incrementProfileCounter(&S);
1712 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001713
Alexey Bataevf8365372017-11-17 17:57:25 +00001714 // Emit the loop iteration variable.
1715 const Expr *IVExpr = S.getIterationVariable();
Alexey Bataevddf3db92018-04-13 17:31:06 +00001716 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
Alexey Bataevf8365372017-11-17 17:57:25 +00001717 CGF.EmitVarDecl(*IVDecl);
1718 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001719
Alexey Bataevf8365372017-11-17 17:57:25 +00001720 // Emit the iterations count variable.
1721 // If it is not a variable, Sema decided to calculate iterations count on
1722 // each iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00001723 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexey Bataevf8365372017-11-17 17:57:25 +00001724 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1725 // Emit calculation of the iterations count.
1726 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1727 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001728
Alexey Bataevf8365372017-11-17 17:57:25 +00001729 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001730
Alexey Bataevf8365372017-11-17 17:57:25 +00001731 emitAlignedClause(CGF, S);
1732 (void)CGF.EmitOMPLinearClauseInit(S);
1733 {
1734 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1735 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1736 CGF.EmitOMPLinearClause(S, LoopScope);
1737 CGF.EmitOMPPrivateClause(S, LoopScope);
1738 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1739 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1740 (void)LoopScope.Privatize();
1741 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1742 S.getInc(),
1743 [&S](CodeGenFunction &CGF) {
1744 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1745 CGF.EmitStopPoint(&S);
1746 },
1747 [](CodeGenFunction &) {});
Alexey Bataevddf3db92018-04-13 17:31:06 +00001748 CGF.EmitOMPSimdFinal(S, [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001749 // Emit final copy of the lastprivate variables at the end of loops.
1750 if (HasLastprivateClause)
1751 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1752 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001753 emitPostUpdateForReductionClause(CGF, S,
1754 [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001755 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00001756 CGF.EmitOMPLinearClauseFinal(S, [](CodeGenFunction &) { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001757 // Emit: if (PreCond) - end.
1758 if (ContBlock) {
1759 CGF.EmitBranch(ContBlock);
1760 CGF.EmitBlock(ContBlock, true);
1761 }
1762}
1763
1764void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1765 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1766 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001767 };
Alexey Bataev475a7442018-01-12 19:39:11 +00001768 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001769 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001770}
1771
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001772void CodeGenFunction::EmitOMPOuterLoop(
1773 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1774 CodeGenFunction::OMPPrivateScope &LoopScope,
1775 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1776 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1777 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001778 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001779
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001780 const Expr *IVExpr = S.getIterationVariable();
1781 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1782 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1783
Alexey Bataevddf3db92018-04-13 17:31:06 +00001784 JumpDest LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001785
1786 // Start the loop with a block that tests the condition.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001787 llvm::BasicBlock *CondBlock = createBasicBlock("omp.dispatch.cond");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001788 EmitBlock(CondBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00001789 const SourceRange R = S.getSourceRange();
Amara Emerson652795d2016-11-10 14:44:30 +00001790 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1791 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001792
1793 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001794 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001795 // UB = min(UB, GlobalUB) or
1796 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1797 // 'distribute parallel for')
1798 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001799 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001800 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001801 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001802 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001803 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001804 BoolCondVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001805 RT.emitForNext(*this, S.getBeginLoc(), IVSize, IVSigned, LoopArgs.IL,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001806 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001807 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001808
1809 // If there are any cleanups between here and the loop-exit scope,
1810 // create a block to stage a loop exit along.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001811 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001812 if (LoopScope.requiresCleanups())
1813 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1814
Alexey Bataevddf3db92018-04-13 17:31:06 +00001815 llvm::BasicBlock *LoopBody = createBasicBlock("omp.dispatch.body");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001816 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1817 if (ExitBlock != LoopExit.getBlock()) {
1818 EmitBlock(ExitBlock);
1819 EmitBranchThroughCleanup(LoopExit);
1820 }
1821 EmitBlock(LoopBody);
1822
Alexander Musman92bdaab2015-03-12 13:37:50 +00001823 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1824 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001825 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001826 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001827
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001828 // Create a block for the increment.
Alexey Bataevddf3db92018-04-13 17:31:06 +00001829 JumpDest Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001830 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1831
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001832 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1833 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001834 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1835 LoopStack.setParallel(!IsMonotonic);
1836 else
1837 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001838
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001839 SourceLocation Loc = S.getBeginLoc();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001840
1841 // when 'distribute' is not combined with a 'for':
1842 // while (idx <= UB) { BODY; ++idx; }
1843 // when 'distribute' is combined with a 'for'
1844 // (e.g. 'distribute parallel for')
1845 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1846 EmitOMPInnerLoop(
1847 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1848 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1849 CodeGenLoop(CGF, S, LoopExit);
1850 },
1851 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1852 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1853 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001854
1855 EmitBlock(Continue.getBlock());
1856 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001857 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001858 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001859 EmitIgnoredExpr(LoopArgs.NextLB);
1860 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001861 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001862
1863 EmitBranch(CondBlock);
1864 LoopStack.pop();
1865 // Emit the fall-through block.
1866 EmitBlock(LoopExit.getBlock());
1867
1868 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001869 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1870 if (!DynamicOrOrdered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001871 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00001872 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00001873 };
1874 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001875}
1876
1877void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001878 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001879 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001880 const OMPLoopArguments &LoopArgs,
1881 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001882 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001883
1884 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001885 const bool DynamicOrOrdered =
1886 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001887
1888 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001889 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001890 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001891 "static non-chunked schedule does not need outer loop");
1892
1893 // Emit outer loop.
1894 //
1895 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1896 // When schedule(dynamic,chunk_size) is specified, the iterations are
1897 // distributed to threads in the team in chunks as the threads request them.
1898 // Each thread executes a chunk of iterations, then requests another chunk,
1899 // until no chunks remain to be distributed. Each chunk contains chunk_size
1900 // iterations, except for the last chunk to be distributed, which may have
1901 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1902 //
1903 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1904 // to threads in the team in chunks as the executing threads request them.
1905 // Each thread executes a chunk of iterations, then requests another chunk,
1906 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1907 // each chunk is proportional to the number of unassigned iterations divided
1908 // by the number of threads in the team, decreasing to 1. For a chunk_size
1909 // with value k (greater than 1), the size of each chunk is determined in the
1910 // same way, with the restriction that the chunks do not contain fewer than k
1911 // iterations (except for the last chunk to be assigned, which may have fewer
1912 // than k iterations).
1913 //
1914 // When schedule(auto) is specified, the decision regarding scheduling is
1915 // delegated to the compiler and/or runtime system. The programmer gives the
1916 // implementation the freedom to choose any possible mapping of iterations to
1917 // threads in the team.
1918 //
1919 // When schedule(runtime) is specified, the decision regarding scheduling is
1920 // deferred until run time, and the schedule and chunk size are taken from the
1921 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1922 // implementation defined
1923 //
1924 // while(__kmpc_dispatch_next(&LB, &UB)) {
1925 // idx = LB;
1926 // while (idx <= UB) { BODY; ++idx;
1927 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1928 // } // inner loop
1929 // }
1930 //
1931 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1932 // When schedule(static, chunk_size) is specified, iterations are divided into
1933 // chunks of size chunk_size, and the chunks are assigned to the threads in
1934 // the team in a round-robin fashion in the order of the thread number.
1935 //
1936 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1937 // while (idx <= UB) { BODY; ++idx; } // inner loop
1938 // LB = LB + ST;
1939 // UB = UB + ST;
1940 // }
1941 //
1942
1943 const Expr *IVExpr = S.getIterationVariable();
1944 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1945 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1946
1947 if (DynamicOrOrdered) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00001948 const std::pair<llvm::Value *, llvm::Value *> DispatchBounds =
1949 CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001950 llvm::Value *LBVal = DispatchBounds.first;
1951 llvm::Value *UBVal = DispatchBounds.second;
1952 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1953 LoopArgs.Chunk};
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001954 RT.emitForDispatchInit(*this, S.getBeginLoc(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001955 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001956 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001957 CGOpenMPRuntime::StaticRTInput StaticInit(
1958 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1959 LoopArgs.ST, LoopArgs.Chunk);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001960 RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(),
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001961 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001962 }
1963
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001964 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1965 const unsigned IVSize,
1966 const bool IVSigned) {
1967 if (Ordered) {
1968 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1969 IVSigned);
1970 }
1971 };
1972
1973 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1974 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1975 OuterLoopArgs.IncExpr = S.getInc();
1976 OuterLoopArgs.Init = S.getInit();
1977 OuterLoopArgs.Cond = S.getCond();
1978 OuterLoopArgs.NextLB = S.getNextLowerBound();
1979 OuterLoopArgs.NextUB = S.getNextUpperBound();
1980 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1981 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001982}
1983
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001984static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1985 const unsigned IVSize, const bool IVSigned) {}
1986
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001987void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001988 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1989 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1990 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001991
Alexey Bataevddf3db92018-04-13 17:31:06 +00001992 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001993
1994 // Emit outer loop.
1995 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1996 // dynamic
1997 //
1998
1999 const Expr *IVExpr = S.getIterationVariable();
2000 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2001 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2002
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002003 CGOpenMPRuntime::StaticRTInput StaticInit(
2004 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
2005 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002006 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002007
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002008 // for combined 'distribute' and 'for' the increment expression of distribute
2009 // is store in DistInc. For 'distribute' alone, it is in Inc.
2010 Expr *IncExpr;
2011 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
2012 IncExpr = S.getDistInc();
2013 else
2014 IncExpr = S.getInc();
2015
2016 // this routine is shared by 'omp distribute parallel for' and
2017 // 'omp distribute': select the right EUB expression depending on the
2018 // directive
2019 OMPLoopArguments OuterLoopArgs;
2020 OuterLoopArgs.LB = LoopArgs.LB;
2021 OuterLoopArgs.UB = LoopArgs.UB;
2022 OuterLoopArgs.ST = LoopArgs.ST;
2023 OuterLoopArgs.IL = LoopArgs.IL;
2024 OuterLoopArgs.Chunk = LoopArgs.Chunk;
2025 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2026 ? S.getCombinedEnsureUpperBound()
2027 : S.getEnsureUpperBound();
2028 OuterLoopArgs.IncExpr = IncExpr;
2029 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2030 ? S.getCombinedInit()
2031 : S.getInit();
2032 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2033 ? S.getCombinedCond()
2034 : S.getCond();
2035 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2036 ? S.getCombinedNextLowerBound()
2037 : S.getNextLowerBound();
2038 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2039 ? S.getCombinedNextUpperBound()
2040 : S.getNextUpperBound();
2041
2042 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
2043 LoopScope, OuterLoopArgs, CodeGenLoopContent,
2044 emitEmptyOrdered);
2045}
2046
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002047static std::pair<LValue, LValue>
2048emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
2049 const OMPExecutableDirective &S) {
2050 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2051 LValue LB =
2052 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2053 LValue UB =
2054 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2055
2056 // When composing 'distribute' with 'for' (e.g. as in 'distribute
2057 // parallel for') we need to use the 'distribute'
2058 // chunk lower and upper bounds rather than the whole loop iteration
2059 // space. These are parameters to the outlined function for 'parallel'
2060 // and we copy the bounds of the previous schedule into the
2061 // the current ones.
2062 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
2063 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002064 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
2065 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002066 PrevLBVal = CGF.EmitScalarConversion(
2067 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002068 LS.getIterationVariable()->getType(),
2069 LS.getPrevLowerBoundVariable()->getExprLoc());
2070 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
2071 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002072 PrevUBVal = CGF.EmitScalarConversion(
2073 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002074 LS.getIterationVariable()->getType(),
2075 LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002076
2077 CGF.EmitStoreOfScalar(PrevLBVal, LB);
2078 CGF.EmitStoreOfScalar(PrevUBVal, UB);
2079
2080 return {LB, UB};
2081}
2082
2083/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
2084/// we need to use the LB and UB expressions generated by the worksharing
2085/// code generation support, whereas in non combined situations we would
2086/// just emit 0 and the LastIteration expression
2087/// This function is necessary due to the difference of the LB and UB
2088/// types for the RT emission routines for 'for_static_init' and
2089/// 'for_dispatch_init'
2090static std::pair<llvm::Value *, llvm::Value *>
2091emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
2092 const OMPExecutableDirective &S,
2093 Address LB, Address UB) {
2094 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2095 const Expr *IVExpr = LS.getIterationVariable();
2096 // when implementing a dynamic schedule for a 'for' combined with a
2097 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
2098 // is not normalized as each team only executes its own assigned
2099 // distribute chunk
2100 QualType IteratorTy = IVExpr->getType();
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002101 llvm::Value *LBVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002102 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002103 llvm::Value *UBVal =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002104 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002105 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00002106}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002107
2108static void emitDistributeParallelForDistributeInnerBoundParams(
2109 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2110 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2111 const auto &Dir = cast<OMPLoopDirective>(S);
2112 LValue LB =
2113 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
Alexey Bataevddf3db92018-04-13 17:31:06 +00002114 llvm::Value *LBCast = CGF.Builder.CreateIntCast(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002115 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2116 CapturedVars.push_back(LBCast);
2117 LValue UB =
2118 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2119
Alexey Bataevddf3db92018-04-13 17:31:06 +00002120 llvm::Value *UBCast = CGF.Builder.CreateIntCast(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002121 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2122 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00002123}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002124
2125static void
2126emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2127 const OMPLoopDirective &S,
2128 CodeGenFunction::JumpDest LoopExit) {
2129 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00002130 PrePostActionTy &Action) {
2131 Action.Enter(CGF);
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002132 bool HasCancel = false;
2133 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2134 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2135 HasCancel = D->hasCancel();
2136 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2137 HasCancel = D->hasCancel();
Alexey Bataev16e79882017-11-22 21:12:03 +00002138 else if (const auto *D =
2139 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2140 HasCancel = D->hasCancel();
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002141 }
2142 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2143 HasCancel);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002144 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2145 emitDistributeParallelForInnerBounds,
2146 emitDistributeParallelForDispatchBounds);
2147 };
2148
2149 emitCommonOMPParallelDirective(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002150 CGF, S,
2151 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2152 CGInlinedWorksharingLoop,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002153 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002154}
2155
Carlo Bertolli9925f152016-06-27 14:55:37 +00002156void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2157 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002158 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2159 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2160 S.getDistInc());
2161 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002162 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev10a54312017-11-27 16:54:08 +00002163 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002164}
2165
Kelvin Li4a39add2016-07-05 05:00:15 +00002166void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2167 const OMPDistributeParallelForSimdDirective &S) {
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002168 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2169 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2170 S.getDistInc());
2171 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002172 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002173 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Kelvin Li4a39add2016-07-05 05:00:15 +00002174}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002175
2176void CodeGenFunction::EmitOMPDistributeSimdDirective(
2177 const OMPDistributeSimdDirective &S) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00002178 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2179 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2180 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002181 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev617db5f2017-12-04 15:38:33 +00002182 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002183}
2184
Alexey Bataevf8365372017-11-17 17:57:25 +00002185void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2186 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2187 // Emit SPMD target parallel for region as a standalone region.
2188 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2189 emitOMPSimdRegion(CGF, S, Action);
2190 };
2191 llvm::Function *Fn;
2192 llvm::Constant *Addr;
2193 // Emit target region as a standalone region.
2194 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2195 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2196 assert(Fn && Addr && "Target device function emission failed.");
2197}
2198
Kelvin Li986330c2016-07-20 22:57:10 +00002199void CodeGenFunction::EmitOMPTargetSimdDirective(
2200 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002201 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2202 emitOMPSimdRegion(CGF, S, Action);
2203 };
2204 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002205}
2206
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002207namespace {
2208 struct ScheduleKindModifiersTy {
2209 OpenMPScheduleClauseKind Kind;
2210 OpenMPScheduleClauseModifier M1;
2211 OpenMPScheduleClauseModifier M2;
2212 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2213 OpenMPScheduleClauseModifier M1,
2214 OpenMPScheduleClauseModifier M2)
2215 : Kind(Kind), M1(M1), M2(M2) {}
2216 };
2217} // namespace
2218
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002219bool CodeGenFunction::EmitOMPWorksharingLoop(
2220 const OMPLoopDirective &S, Expr *EUB,
2221 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2222 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002223 // Emit the loop iteration variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002224 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2225 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
Alexander Musmanc6388682014-12-15 07:07:06 +00002226 EmitVarDecl(*IVDecl);
2227
2228 // Emit the iterations count variable.
2229 // If it is not a variable, Sema decided to calculate iterations count on each
2230 // iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00002231 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002232 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2233 // Emit calculation of the iterations count.
2234 EmitIgnoredExpr(S.getCalcLastIteration());
2235 }
2236
Alexey Bataevddf3db92018-04-13 17:31:06 +00002237 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Alexander Musmanc6388682014-12-15 07:07:06 +00002238
Alexey Bataev38e89532015-04-16 04:54:05 +00002239 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002240 // Check pre-condition.
2241 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002242 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002243 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002244 // If the condition constant folds and can be elided, avoid emitting the
2245 // whole loop.
2246 bool CondConstant;
2247 llvm::BasicBlock *ContBlock = nullptr;
2248 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2249 if (!CondConstant)
2250 return false;
2251 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002252 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
Alexey Bataev62dbb972015-04-22 11:59:37 +00002253 ContBlock = createBasicBlock("omp.precond.end");
2254 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002255 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002256 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002257 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002258 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002259
Alexey Bataevea33dee2018-02-15 23:39:43 +00002260 RunCleanupsScope DoacrossCleanupScope(*this);
Alexey Bataev8b427062016-05-25 12:36:08 +00002261 bool Ordered = false;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002262 if (const auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
Alexey Bataev8b427062016-05-25 12:36:08 +00002263 if (OrderedClause->getNumForLoops())
Alexey Bataevf138fda2018-08-13 19:04:24 +00002264 RT.emitDoacrossInit(*this, S, OrderedClause->getLoopNumIterations());
Alexey Bataev8b427062016-05-25 12:36:08 +00002265 else
2266 Ordered = true;
2267 }
2268
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002269 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002270 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002271 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002272 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002273
2274 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2275 LValue LB = Bounds.first;
2276 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002277 LValue ST =
2278 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2279 LValue IL =
2280 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2281
Alexander Musmanc6388682014-12-15 07:07:06 +00002282 // Emit 'then' code.
2283 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002284 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002285 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002286 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002287 // initialization of firstprivate variables and post-update of
2288 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002289 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002290 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002291 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002292 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002293 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002294 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002295 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002296 EmitOMPPrivateLoopCounters(S, LoopScope);
2297 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002298 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002299
2300 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002301 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002302 OpenMPScheduleTy ScheduleKind;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002303 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002304 ScheduleKind.Schedule = C->getScheduleKind();
2305 ScheduleKind.M1 = C->getFirstScheduleModifier();
2306 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002307 if (const Expr *Ch = C->getChunkSize()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002308 Chunk = EmitScalarExpr(Ch);
2309 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2310 S.getIterationVariable()->getType(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002311 S.getBeginLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002312 }
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00002313 } else {
2314 // Default behaviour for schedule clause.
2315 CGM.getOpenMPRuntime().getDefaultScheduleAndChunk(
2316 *this, S, ScheduleKind.Schedule, Chunk);
Alexey Bataev3392d762016-02-16 11:18:12 +00002317 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002318 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2319 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002320 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2321 // If the static schedule kind is specified or if the ordered clause is
2322 // specified, and if no monotonic modifier is specified, the effect will
2323 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002324 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002325 /* Chunked */ Chunk != nullptr) &&
2326 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002327 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2328 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002329 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2330 // When no chunk_size is specified, the iteration space is divided into
2331 // chunks that are approximately equal in size, and at most one chunk is
2332 // distributed to each thread. Note that the size of the chunks is
2333 // unspecified in this case.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002334 CGOpenMPRuntime::StaticRTInput StaticInit(
2335 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
2336 UB.getAddress(), ST.getAddress());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002337 RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(),
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002338 ScheduleKind, StaticInit);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002339 JumpDest LoopExit =
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002340 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002341 // UB = min(UB, GlobalUB);
2342 EmitIgnoredExpr(S.getEnsureUpperBound());
2343 // IV = LB;
2344 EmitIgnoredExpr(S.getInit());
2345 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002346 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2347 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002348 [&S, LoopExit](CodeGenFunction &CGF) {
2349 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002350 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002351 },
2352 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002353 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002354 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002355 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002356 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00002357 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002358 };
2359 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002360 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002361 const bool IsMonotonic =
2362 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2363 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2364 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2365 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002366 // Emit the outer loop, which requests its work chunk [LB..UB] from
2367 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002368 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2369 ST.getAddress(), IL.getAddress(),
2370 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002371 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002372 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002373 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002374 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002375 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
2376 return CGF.Builder.CreateIsNotNull(
2377 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
2378 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002379 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002380 EmitOMPReductionClauseFinal(
2381 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2382 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2383 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002384 // Emit post-update of the reduction variables if IsLastIter != 0.
2385 emitPostUpdateForReductionClause(
Alexey Bataevddf3db92018-04-13 17:31:06 +00002386 *this, S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataev61205072016-03-02 04:57:40 +00002387 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002388 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataev61205072016-03-02 04:57:40 +00002389 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002390 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2391 if (HasLastprivateClause)
2392 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002393 S, isOpenMPSimdDirective(S.getDirectiveKind()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002394 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002395 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00002396 EmitOMPLinearClauseFinal(S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataevef549a82016-03-09 09:49:09 +00002397 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002398 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataevef549a82016-03-09 09:49:09 +00002399 });
Alexey Bataevea33dee2018-02-15 23:39:43 +00002400 DoacrossCleanupScope.ForceCleanup();
Alexander Musmanc6388682014-12-15 07:07:06 +00002401 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002402 if (ContBlock) {
2403 EmitBranch(ContBlock);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002404 EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002405 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002406 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002407 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002408}
2409
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002410/// The following two functions generate expressions for the loop lower
2411/// and upper bounds in case of static and dynamic (dispatch) schedule
2412/// of the associated 'for' or 'distribute' loop.
2413static std::pair<LValue, LValue>
2414emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002415 const auto &LS = cast<OMPLoopDirective>(S);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002416 LValue LB =
2417 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2418 LValue UB =
2419 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2420 return {LB, UB};
2421}
2422
2423/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2424/// consider the lower and upper bound expressions generated by the
2425/// worksharing loop support, but we use 0 and the iteration space size as
2426/// constants
2427static std::pair<llvm::Value *, llvm::Value *>
2428emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2429 Address LB, Address UB) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002430 const auto &LS = cast<OMPLoopDirective>(S);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002431 const Expr *IVExpr = LS.getIterationVariable();
2432 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2433 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2434 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2435 return {LBVal, UBVal};
2436}
2437
Alexander Musmanc6388682014-12-15 07:07:06 +00002438void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002439 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002440 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2441 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002442 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002443 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2444 emitForLoopBounds,
2445 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002446 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002447 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002448 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002449 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2450 S.hasCancel());
2451 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002452
2453 // Emit an implicit barrier at the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002454 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002455 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002456}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002457
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002458void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002459 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002460 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2461 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002462 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2463 emitForLoopBounds,
2464 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002465 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002466 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002467 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002468 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2469 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002470
2471 // Emit an implicit barrier at the end.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002472 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002473 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002474}
2475
Alexey Bataev2df54a02015-03-12 08:53:29 +00002476static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2477 const Twine &Name,
2478 llvm::Value *Init = nullptr) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002479 LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002480 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002481 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002482 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002483}
2484
Alexey Bataev3392d762016-02-16 11:18:12 +00002485void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002486 const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
2487 const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002488 bool HasLastprivates = false;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002489 auto &&CodeGen = [&S, CapturedStmt, CS,
2490 &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) {
2491 ASTContext &C = CGF.getContext();
2492 QualType KmpInt32Ty =
2493 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002494 // Emit helper vars inits.
2495 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2496 CGF.Builder.getInt32(0));
Alexey Bataevddf3db92018-04-13 17:31:06 +00002497 llvm::ConstantInt *GlobalUBVal = CS != nullptr
2498 ? CGF.Builder.getInt32(CS->size() - 1)
2499 : CGF.Builder.getInt32(0);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002500 LValue UB =
2501 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2502 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2503 CGF.Builder.getInt32(1));
2504 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2505 CGF.Builder.getInt32(0));
2506 // Loop counter.
2507 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002508 OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002509 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002510 OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002511 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2512 // Generate condition for loop.
2513 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002514 OK_Ordinary, S.getBeginLoc(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002515 // Increment for loop counter.
2516 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002517 S.getBeginLoc(), true);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002518 auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002519 // Iterate through all sections and emit a switch construct:
2520 // switch (IV) {
2521 // case 0:
2522 // <SectionStmt[0]>;
2523 // break;
2524 // ...
2525 // case <NumSection> - 1:
2526 // <SectionStmt[<NumSection> - 1]>;
2527 // break;
2528 // }
2529 // .omp.sections.exit:
Alexey Bataevddf3db92018-04-13 17:31:06 +00002530 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2531 llvm::SwitchInst *SwitchStmt =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002532 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002533 ExitBB, CS == nullptr ? 1 : CS->size());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002534 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002535 unsigned CaseNumber = 0;
Alexey Bataevddf3db92018-04-13 17:31:06 +00002536 for (const Stmt *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002537 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2538 CGF.EmitBlock(CaseBB);
2539 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002540 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002541 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002542 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002543 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002544 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002545 llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case");
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002546 CGF.EmitBlock(CaseBB);
2547 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002548 CGF.EmitStmt(CapturedStmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002549 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002550 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002551 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002552 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002553
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002554 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2555 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002556 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002557 // initialization of firstprivate variables and post-update of lastprivate
2558 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002559 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002560 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002561 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002562 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002563 CGF.EmitOMPPrivateClause(S, LoopScope);
2564 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2565 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2566 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002567
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002568 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002569 OpenMPScheduleTy ScheduleKind;
2570 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002571 CGOpenMPRuntime::StaticRTInput StaticInit(
2572 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2573 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002574 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002575 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002576 // UB = min(UB, GlobalUB);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002577 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc());
Alexey Bataevddf3db92018-04-13 17:31:06 +00002578 llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect(
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002579 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2580 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2581 // IV = LB;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002582 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002583 // while (idx <= UB) { BODY; ++idx; }
2584 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2585 [](CodeGenFunction &) {});
2586 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002587 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002588 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
Alexey Bataevf43f7142017-09-06 16:17:35 +00002589 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002590 };
2591 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002592 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002593 // Emit post-update of the reduction variables if IsLastIter != 0.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002594 emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) {
2595 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002596 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataevddf3db92018-04-13 17:31:06 +00002597 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002598
2599 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2600 if (HasLastprivates)
2601 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002602 S, /*NoFinals=*/false,
2603 CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002604 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002605 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002606
2607 bool HasCancel = false;
2608 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2609 HasCancel = OSD->hasCancel();
2610 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2611 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002612 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002613 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2614 HasCancel);
2615 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2616 // clause. Otherwise the barrier will be generated by the codegen for the
2617 // directive.
2618 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002619 // Emit implicit barrier to synchronize threads and avoid data races on
2620 // initialization of firstprivate variables.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002621 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002622 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002623 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002624}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002625
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002626void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002627 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002628 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002629 EmitSections(S);
2630 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002631 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002632 if (!S.getSingleClause<OMPNowaitClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002633 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
Alexey Bataev3392d762016-02-16 11:18:12 +00002634 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002635 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002636}
2637
2638void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002639 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002640 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002641 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002642 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002643 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2644 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002645}
2646
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002647void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002648 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002649 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002650 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002651 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002652 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002653 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002654 // Build a list of copyprivate variables along with helper expressions
2655 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002656 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002657 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002658 DestExprs.append(C->destination_exprs().begin(),
2659 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002660 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002661 AssignmentOps.append(C->assignment_ops().begin(),
2662 C->assignment_ops().end());
2663 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002664 // Emit code for 'single' region along with 'copyprivate' clauses
2665 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2666 Action.Enter(CGF);
2667 OMPPrivateScope SingleScope(CGF);
2668 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2669 CGF.EmitOMPPrivateClause(S, SingleScope);
2670 (void)SingleScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00002671 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002672 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002673 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002674 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002675 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(),
Alexey Bataev3392d762016-02-16 11:18:12 +00002676 CopyprivateVars, DestExprs,
2677 SrcExprs, AssignmentOps);
2678 }
2679 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2680 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002681 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002682 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002683 *this, S.getBeginLoc(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002684 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002685 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002686}
2687
Alexey Bataev8d690652014-12-04 07:23:53 +00002688void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002689 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2690 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002691 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002692 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002693 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002694 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
Alexander Musman80c22892014-07-17 08:54:58 +00002695}
2696
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002697void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002698 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2699 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002700 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002701 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00002702 const Expr *Hint = nullptr;
2703 if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
Alexey Bataevfc57d162015-12-15 10:55:09 +00002704 Hint = HintClause->getHint();
Alexey Bataev475a7442018-01-12 19:39:11 +00002705 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002706 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2707 S.getDirectiveName().getAsString(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002708 CodeGen, S.getBeginLoc(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002709}
2710
Alexey Bataev671605e2015-04-13 05:28:11 +00002711void CodeGenFunction::EmitOMPParallelForDirective(
2712 const OMPParallelForDirective &S) {
2713 // Emit directive as a combined directive that consists of two implicit
2714 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00002715 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2716 Action.Enter(CGF);
Alexey Bataev957d8562016-11-17 15:12:05 +00002717 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002718 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2719 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002720 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002721 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2722 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002723}
2724
Alexander Musmane4e893b2014-09-23 09:33:00 +00002725void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002726 const OMPParallelForSimdDirective &S) {
2727 // Emit directive as a combined directive that consists of two implicit
2728 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00002729 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2730 Action.Enter(CGF);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002731 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2732 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002733 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002734 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2735 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002736}
2737
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002738void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002739 const OMPParallelSectionsDirective &S) {
2740 // Emit directive as a combined directive that consists of two implicit
2741 // directives: 'parallel' with 'sections' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00002742 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2743 Action.Enter(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002744 CGF.EmitSections(S);
2745 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002746 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2747 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002748}
2749
Alexey Bataev475a7442018-01-12 19:39:11 +00002750void CodeGenFunction::EmitOMPTaskBasedDirective(
2751 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
2752 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
2753 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002754 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00002755 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002756 auto I = CS->getCapturedDecl()->param_begin();
2757 auto PartId = std::next(I);
2758 auto TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002759 // Check if the task is final
2760 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2761 // If the condition constant folds and can be elided, try to avoid emitting
2762 // the condition and the dead arm of the if/else.
Alexey Bataevddf3db92018-04-13 17:31:06 +00002763 const Expr *Cond = Clause->getCondition();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002764 bool CondConstant;
2765 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2766 Data.Final.setInt(CondConstant);
2767 else
2768 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2769 } else {
2770 // By default the task is not final.
2771 Data.Final.setInt(/*IntVal=*/false);
2772 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002773 // Check if the task has 'priority' clause.
2774 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00002775 const Expr *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002776 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002777 Data.Priority.setPointer(EmitScalarConversion(
2778 EmitScalarExpr(Prio), Prio->getType(),
2779 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2780 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002781 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002782 // The first function argument for tasks is a thread id, the second one is a
2783 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002784 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2785 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002786 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002787 auto IRef = C->varlist_begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002788 for (const Expr *IInit : C->private_copies()) {
2789 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002790 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002791 Data.PrivateVars.push_back(*IRef);
2792 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002793 }
2794 ++IRef;
2795 }
2796 }
2797 EmittedAsPrivate.clear();
2798 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002799 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002800 auto IRef = C->varlist_begin();
2801 auto IElemInitRef = C->inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002802 for (const Expr *IInit : C->private_copies()) {
2803 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002804 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002805 Data.FirstprivateVars.push_back(*IRef);
2806 Data.FirstprivateCopies.push_back(IInit);
2807 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002808 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002809 ++IRef;
2810 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002811 }
2812 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002813 // Get list of lastprivate variables (for taskloops).
2814 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2815 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2816 auto IRef = C->varlist_begin();
2817 auto ID = C->destination_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002818 for (const Expr *IInit : C->private_copies()) {
2819 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00002820 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2821 Data.LastprivateVars.push_back(*IRef);
2822 Data.LastprivateCopies.push_back(IInit);
2823 }
2824 LastprivateDstsOrigs.insert(
2825 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2826 cast<DeclRefExpr>(*IRef)});
2827 ++IRef;
2828 ++ID;
2829 }
2830 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002831 SmallVector<const Expr *, 4> LHSs;
2832 SmallVector<const Expr *, 4> RHSs;
2833 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2834 auto IPriv = C->privates().begin();
2835 auto IRed = C->reduction_ops().begin();
2836 auto ILHS = C->lhs_exprs().begin();
2837 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002838 for (const Expr *Ref : C->varlists()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002839 Data.ReductionVars.emplace_back(Ref);
2840 Data.ReductionCopies.emplace_back(*IPriv);
2841 Data.ReductionOps.emplace_back(*IRed);
2842 LHSs.emplace_back(*ILHS);
2843 RHSs.emplace_back(*IRHS);
2844 std::advance(IPriv, 1);
2845 std::advance(IRed, 1);
2846 std::advance(ILHS, 1);
2847 std::advance(IRHS, 1);
2848 }
2849 }
2850 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002851 *this, S.getBeginLoc(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002852 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002853 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
Alexey Bataevddf3db92018-04-13 17:31:06 +00002854 for (const Expr *IRef : C->varlists())
Alexey Bataev43a919f2018-04-13 17:48:43 +00002855 Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
Alexey Bataev475a7442018-01-12 19:39:11 +00002856 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
2857 CapturedRegion](CodeGenFunction &CGF,
2858 PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002859 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002860 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002861 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2862 !Data.LastprivateVars.empty()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00002863 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00002864 llvm::Value *CopyFn = CGF.Builder.CreateLoad(
2865 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
2866 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
2867 CS->getCapturedDecl()->getParam(PrivatesParam)));
Alexey Bataev48591dd2016-04-20 04:01:36 +00002868 // Map privates.
2869 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2870 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2871 CallArgs.push_back(PrivatesPtr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002872 for (const Expr *E : Data.PrivateVars) {
2873 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev48591dd2016-04-20 04:01:36 +00002874 Address PrivatePtr = CGF.CreateMemTemp(
2875 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00002876 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002877 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002878 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00002879 for (const Expr *E : Data.FirstprivateVars) {
2880 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev48591dd2016-04-20 04:01:36 +00002881 Address PrivatePtr =
2882 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2883 ".firstpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00002884 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002885 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002886 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00002887 for (const Expr *E : Data.LastprivateVars) {
2888 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00002889 Address PrivatePtr =
2890 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2891 ".lastpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00002892 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002893 CallArgs.push_back(PrivatePtr.getPointer());
2894 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002895 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
Alexey Bataev3c595a62017-08-14 15:01:03 +00002896 CopyFn, CallArgs);
Alexey Bataevddf3db92018-04-13 17:31:06 +00002897 for (const auto &Pair : LastprivateDstsOrigs) {
2898 const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00002899 DeclRefExpr DRE(
2900 const_cast<VarDecl *>(OrigVD),
2901 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2902 OrigVD) != nullptr,
2903 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2904 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2905 return CGF.EmitLValue(&DRE).getAddress();
2906 });
2907 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00002908 for (const auto &Pair : PrivatePtrs) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002909 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2910 CGF.getContext().getDeclAlign(Pair.first));
2911 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2912 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002913 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002914 if (Data.Reductions) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002915 OMPLexicalScope LexScope(CGF, S, CapturedRegion);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002916 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2917 Data.ReductionOps);
2918 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2919 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2920 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2921 RedCG.emitSharedLValue(CGF, Cnt);
2922 RedCG.emitAggregateType(CGF, Cnt);
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00002923 // FIXME: This must removed once the runtime library is fixed.
2924 // Emit required threadprivate variables for
2925 // initilizer/combiner/finalizer.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002926 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00002927 RedCG, Cnt);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002928 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002929 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002930 Replacement =
2931 Address(CGF.EmitScalarConversion(
2932 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2933 CGF.getContext().getPointerType(
2934 Data.ReductionCopies[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002935 Data.ReductionCopies[Cnt]->getExprLoc()),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002936 Replacement.getAlignment());
2937 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2938 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2939 [Replacement]() { return Replacement; });
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002940 }
2941 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002942 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002943 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002944 SmallVector<const Expr *, 4> InRedVars;
2945 SmallVector<const Expr *, 4> InRedPrivs;
2946 SmallVector<const Expr *, 4> InRedOps;
2947 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2948 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2949 auto IPriv = C->privates().begin();
2950 auto IRed = C->reduction_ops().begin();
2951 auto ITD = C->taskgroup_descriptors().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00002952 for (const Expr *Ref : C->varlists()) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002953 InRedVars.emplace_back(Ref);
2954 InRedPrivs.emplace_back(*IPriv);
2955 InRedOps.emplace_back(*IRed);
2956 TaskgroupDescriptors.emplace_back(*ITD);
2957 std::advance(IPriv, 1);
2958 std::advance(IRed, 1);
2959 std::advance(ITD, 1);
2960 }
2961 }
2962 // Privatize in_reduction items here, because taskgroup descriptors must be
2963 // privatized earlier.
2964 OMPPrivateScope InRedScope(CGF);
2965 if (!InRedVars.empty()) {
2966 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2967 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2968 RedCG.emitSharedLValue(CGF, Cnt);
2969 RedCG.emitAggregateType(CGF, Cnt);
2970 // The taskgroup descriptor variable is always implicit firstprivate and
2971 // privatized already during procoessing of the firstprivates.
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00002972 // FIXME: This must removed once the runtime library is fixed.
2973 // Emit required threadprivate variables for
2974 // initilizer/combiner/finalizer.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002975 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
Alexey Bataev2e0cbe502018-03-08 15:24:08 +00002976 RedCG, Cnt);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002977 llvm::Value *ReductionsPtr =
2978 CGF.EmitLoadOfScalar(CGF.EmitLValue(TaskgroupDescriptors[Cnt]),
2979 TaskgroupDescriptors[Cnt]->getExprLoc());
Alexey Bataev88202be2017-07-27 13:20:36 +00002980 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002981 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
Alexey Bataev88202be2017-07-27 13:20:36 +00002982 Replacement = Address(
2983 CGF.EmitScalarConversion(
2984 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2985 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002986 InRedPrivs[Cnt]->getExprLoc()),
Alexey Bataev88202be2017-07-27 13:20:36 +00002987 Replacement.getAlignment());
2988 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2989 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2990 [Replacement]() { return Replacement; });
Alexey Bataev88202be2017-07-27 13:20:36 +00002991 }
2992 }
2993 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00002994
2995 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002996 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002997 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00002998 llvm::Value *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00002999 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
3000 Data.NumberOfParts);
3001 OMPLexicalScope Scope(*this, S);
3002 TaskGen(*this, OutlinedFn, Data);
3003}
3004
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003005static ImplicitParamDecl *
3006createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003007 QualType Ty, CapturedDecl *CD,
3008 SourceLocation Loc) {
3009 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3010 ImplicitParamDecl::Other);
3011 auto *OrigRef = DeclRefExpr::Create(
3012 C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
3013 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
3014 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3015 ImplicitParamDecl::Other);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003016 auto *PrivateRef = DeclRefExpr::Create(
3017 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003018 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003019 QualType ElemType = C.getBaseElementType(Ty);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003020 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
3021 ImplicitParamDecl::Other);
3022 auto *InitRef = DeclRefExpr::Create(
3023 C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
3024 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003025 PrivateVD->setInitStyle(VarDecl::CInit);
3026 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
3027 InitRef, /*BasePath=*/nullptr,
3028 VK_RValue));
3029 Data.FirstprivateVars.emplace_back(OrigRef);
3030 Data.FirstprivateCopies.emplace_back(PrivateRef);
3031 Data.FirstprivateInits.emplace_back(InitRef);
3032 return OrigVD;
3033}
3034
3035void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
3036 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
3037 OMPTargetDataInfo &InputInfo) {
3038 // Emit outlined function for task construct.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003039 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
3040 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3041 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3042 auto I = CS->getCapturedDecl()->param_begin();
3043 auto PartId = std::next(I);
3044 auto TaskT = std::next(I, 4);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003045 OMPTaskDataTy Data;
3046 // The task is not final.
3047 Data.Final.setInt(/*IntVal=*/false);
3048 // Get list of firstprivate variables.
3049 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3050 auto IRef = C->varlist_begin();
3051 auto IElemInitRef = C->inits().begin();
3052 for (auto *IInit : C->private_copies()) {
3053 Data.FirstprivateVars.push_back(*IRef);
3054 Data.FirstprivateCopies.push_back(IInit);
3055 Data.FirstprivateInits.push_back(*IElemInitRef);
3056 ++IRef;
3057 ++IElemInitRef;
3058 }
3059 }
3060 OMPPrivateScope TargetScope(*this);
3061 VarDecl *BPVD = nullptr;
3062 VarDecl *PVD = nullptr;
3063 VarDecl *SVD = nullptr;
3064 if (InputInfo.NumberOfTargetItems > 0) {
3065 auto *CD = CapturedDecl::Create(
3066 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
3067 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
3068 QualType BaseAndPointersType = getContext().getConstantArrayType(
3069 getContext().VoidPtrTy, ArrSize, ArrayType::Normal,
3070 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003071 BPVD = createImplicitFirstprivateForType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003072 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003073 PVD = createImplicitFirstprivateForType(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003074 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003075 QualType SizesType = getContext().getConstantArrayType(
3076 getContext().getSizeType(), ArrSize, ArrayType::Normal,
3077 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003078 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003079 S.getBeginLoc());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003080 TargetScope.addPrivate(
3081 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
3082 TargetScope.addPrivate(PVD,
3083 [&InputInfo]() { return InputInfo.PointersArray; });
3084 TargetScope.addPrivate(SVD,
3085 [&InputInfo]() { return InputInfo.SizesArray; });
3086 }
3087 (void)TargetScope.Privatize();
3088 // Build list of dependences.
3089 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
Alexey Bataevddf3db92018-04-13 17:31:06 +00003090 for (const Expr *IRef : C->varlists())
Alexey Bataev43a919f2018-04-13 17:48:43 +00003091 Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003092 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3093 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3094 // Set proper addresses for generated private copies.
3095 OMPPrivateScope Scope(CGF);
3096 if (!Data.FirstprivateVars.empty()) {
3097 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00003098 llvm::Value *CopyFn = CGF.Builder.CreateLoad(
3099 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
3100 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
3101 CS->getCapturedDecl()->getParam(PrivatesParam)));
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003102 // Map privates.
3103 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3104 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3105 CallArgs.push_back(PrivatesPtr);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003106 for (const Expr *E : Data.FirstprivateVars) {
3107 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003108 Address PrivatePtr =
3109 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3110 ".firstpriv.ptr.addr");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003111 PrivatePtrs.emplace_back(VD, PrivatePtr);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003112 CallArgs.push_back(PrivatePtr.getPointer());
3113 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003114 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003115 CopyFn, CallArgs);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003116 for (const auto &Pair : PrivatePtrs) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003117 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3118 CGF.getContext().getDeclAlign(Pair.first));
3119 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3120 }
3121 }
3122 // Privatize all private variables except for in_reduction items.
3123 (void)Scope.Privatize();
Alexey Bataev8451efa2018-01-15 19:06:12 +00003124 if (InputInfo.NumberOfTargetItems > 0) {
3125 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
3126 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0, CGF.getPointerSize());
3127 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
3128 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0, CGF.getPointerSize());
3129 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
3130 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0, CGF.getSizeSize());
3131 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003132
3133 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003134 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003135 BodyGen(CGF);
3136 };
Alexey Bataevddf3db92018-04-13 17:31:06 +00003137 llvm::Value *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003138 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3139 Data.NumberOfParts);
3140 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3141 IntegerLiteral IfCond(getContext(), TrueOrFalse,
3142 getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3143 SourceLocation());
3144
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003145 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn,
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003146 SharedsTy, CapturedStruct, &IfCond, Data);
3147}
3148
Alexey Bataev7292c292016-04-25 12:22:29 +00003149void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3150 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00003151 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003152 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3153 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00003154 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00003155 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3156 if (C->getNameModifier() == OMPD_unknown ||
3157 C->getNameModifier() == OMPD_task) {
3158 IfCond = C->getCondition();
3159 break;
3160 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003161 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003162
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003163 OMPTaskDataTy Data;
3164 // Check if we should emit tied or untied task.
3165 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003166 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3167 CGF.EmitStmt(CS->getCapturedStmt());
3168 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003169 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00003170 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003171 const OMPTaskDataTy &Data) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003172 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003173 SharedsTy, CapturedStruct, IfCond,
3174 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003175 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003176 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003177}
3178
Alexey Bataev9f797f32015-02-05 05:57:51 +00003179void CodeGenFunction::EmitOMPTaskyieldDirective(
3180 const OMPTaskyieldDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003181 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc());
Alexey Bataev68446b72014-07-18 07:47:19 +00003182}
3183
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003184void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003185 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003186}
3187
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003188void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003189 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc());
Alexey Bataev2df347a2014-07-18 10:17:07 +00003190}
3191
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003192void CodeGenFunction::EmitOMPTaskgroupDirective(
3193 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003194 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3195 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003196 if (const Expr *E = S.getReductionRef()) {
3197 SmallVector<const Expr *, 4> LHSs;
3198 SmallVector<const Expr *, 4> RHSs;
3199 OMPTaskDataTy Data;
3200 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3201 auto IPriv = C->privates().begin();
3202 auto IRed = C->reduction_ops().begin();
3203 auto ILHS = C->lhs_exprs().begin();
3204 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003205 for (const Expr *Ref : C->varlists()) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003206 Data.ReductionVars.emplace_back(Ref);
3207 Data.ReductionCopies.emplace_back(*IPriv);
3208 Data.ReductionOps.emplace_back(*IRed);
3209 LHSs.emplace_back(*ILHS);
3210 RHSs.emplace_back(*IRHS);
3211 std::advance(IPriv, 1);
3212 std::advance(IRed, 1);
3213 std::advance(ILHS, 1);
3214 std::advance(IRHS, 1);
3215 }
3216 }
3217 llvm::Value *ReductionDesc =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003218 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(),
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003219 LHSs, RHSs, Data);
3220 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3221 CGF.EmitVarDecl(*VD);
3222 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3223 /*Volatile=*/false, E->getType());
3224 }
Alexey Bataev475a7442018-01-12 19:39:11 +00003225 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003226 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003227 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003228 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003229}
3230
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003231void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003232 CGM.getOpenMPRuntime().emitFlush(
3233 *this,
3234 [&S]() -> ArrayRef<const Expr *> {
3235 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>())
3236 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3237 FlushClause->varlist_end());
3238 return llvm::None;
3239 }(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003240 S.getBeginLoc());
Alexey Bataev6125da92014-07-21 11:26:11 +00003241}
3242
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003243void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3244 const CodeGenLoopTy &CodeGenLoop,
3245 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003246 // Emit the loop iteration variable.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003247 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3248 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003249 EmitVarDecl(*IVDecl);
3250
3251 // Emit the iterations count variable.
3252 // If it is not a variable, Sema decided to calculate iterations count on each
3253 // iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00003254 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003255 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3256 // Emit calculation of the iterations count.
3257 EmitIgnoredExpr(S.getCalcLastIteration());
3258 }
3259
Alexey Bataevddf3db92018-04-13 17:31:06 +00003260 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003261
Carlo Bertolli962bb802017-01-03 18:24:42 +00003262 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003263 // Check pre-condition.
3264 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003265 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003266 // Skip the entire loop if we don't meet the precondition.
3267 // If the condition constant folds and can be elided, avoid emitting the
3268 // whole loop.
3269 bool CondConstant;
3270 llvm::BasicBlock *ContBlock = nullptr;
3271 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3272 if (!CondConstant)
3273 return;
3274 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003275 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003276 ContBlock = createBasicBlock("omp.precond.end");
3277 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3278 getProfileCount(&S));
3279 EmitBlock(ThenBlock);
3280 incrementProfileCounter(&S);
3281 }
3282
Alexey Bataev617db5f2017-12-04 15:38:33 +00003283 emitAlignedClause(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003284 // Emit 'then' code.
3285 {
3286 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003287
3288 LValue LB = EmitOMPHelperVar(
3289 *this, cast<DeclRefExpr>(
3290 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3291 ? S.getCombinedLowerBoundVariable()
3292 : S.getLowerBoundVariable())));
3293 LValue UB = EmitOMPHelperVar(
3294 *this, cast<DeclRefExpr>(
3295 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3296 ? S.getCombinedUpperBoundVariable()
3297 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003298 LValue ST =
3299 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3300 LValue IL =
3301 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3302
3303 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003304 if (EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003305 // Emit implicit barrier to synchronize threads and avoid data races
3306 // on initialization of firstprivate variables and post-update of
Carlo Bertolli962bb802017-01-03 18:24:42 +00003307 // lastprivate variables.
3308 CGM.getOpenMPRuntime().emitBarrierCall(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003309 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
Alexey Bataev617db5f2017-12-04 15:38:33 +00003310 /*ForceSimpleCall=*/true);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003311 }
3312 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev617db5f2017-12-04 15:38:33 +00003313 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
Alexey Bataev999277a2017-12-06 14:31:09 +00003314 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3315 !isOpenMPTeamsDirective(S.getDirectiveKind()))
Alexey Bataev617db5f2017-12-04 15:38:33 +00003316 EmitOMPReductionClauseInit(S, LoopScope);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003317 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003318 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003319 (void)LoopScope.Privatize();
3320
3321 // Detect the distribute schedule kind and chunk.
3322 llvm::Value *Chunk = nullptr;
3323 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003324 if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003325 ScheduleKind = C->getDistScheduleKind();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003326 if (const Expr *Ch = C->getChunkSize()) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003327 Chunk = EmitScalarExpr(Ch);
3328 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
Alexey Bataev617db5f2017-12-04 15:38:33 +00003329 S.getIterationVariable()->getType(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003330 S.getBeginLoc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003331 }
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00003332 } else {
3333 // Default behaviour for dist_schedule clause.
3334 CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk(
3335 *this, S, ScheduleKind, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003336 }
3337 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3338 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3339
3340 // OpenMP [2.10.8, distribute Construct, Description]
3341 // If dist_schedule is specified, kind must be static. If specified,
3342 // iterations are divided into chunks of size chunk_size, chunks are
3343 // assigned to the teams of the league in a round-robin fashion in the
3344 // order of the team number. When no chunk_size is specified, the
3345 // iteration space is divided into chunks that are approximately equal
3346 // in size, and at most one chunk is distributed to each team of the
3347 // league. The size of the chunks is unspecified in this case.
3348 if (RT.isStaticNonchunked(ScheduleKind,
3349 /* Chunked */ Chunk != nullptr)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003350 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3351 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003352 CGOpenMPRuntime::StaticRTInput StaticInit(
3353 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3354 LB.getAddress(), UB.getAddress(), ST.getAddress());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003355 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003356 StaticInit);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003357 JumpDest LoopExit =
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003358 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3359 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003360 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3361 ? S.getCombinedEnsureUpperBound()
3362 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003363 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003364 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3365 ? S.getCombinedInit()
3366 : S.getInit());
3367
Alexey Bataevddf3db92018-04-13 17:31:06 +00003368 const Expr *Cond =
3369 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3370 ? S.getCombinedCond()
3371 : S.getCond();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003372
3373 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003374 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003375 // when combined with 'for' (e.g. as in 'distribute parallel for')
3376 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3377 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3378 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3379 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003380 },
3381 [](CodeGenFunction &) {});
3382 EmitBlock(LoopExit.getBlock());
3383 // Tell the runtime we are done.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003384 RT.emitForStaticFinish(*this, S.getBeginLoc(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003385 } else {
3386 // Emit the outer loop, which requests its work chunk [LB..UB] from
3387 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003388 const OMPLoopArguments LoopArguments = {
3389 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3390 Chunk};
3391 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3392 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003393 }
Alexey Bataev617db5f2017-12-04 15:38:33 +00003394 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003395 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003396 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003397 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Alexey Bataev617db5f2017-12-04 15:38:33 +00003398 });
3399 }
Carlo Bertollibeda2142018-02-22 19:38:14 +00003400 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
3401 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3402 !isOpenMPTeamsDirective(S.getDirectiveKind())) {
Jonas Hahnfeld5aaaece2018-10-02 19:12:47 +00003403 EmitOMPReductionClauseFinal(S, OMPD_simd);
Carlo Bertollibeda2142018-02-22 19:38:14 +00003404 // Emit post-update of the reduction variables if IsLastIter != 0.
3405 emitPostUpdateForReductionClause(
Alexey Bataevddf3db92018-04-13 17:31:06 +00003406 *this, S, [IL, &S](CodeGenFunction &CGF) {
Carlo Bertollibeda2142018-02-22 19:38:14 +00003407 return CGF.Builder.CreateIsNotNull(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003408 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
Carlo Bertollibeda2142018-02-22 19:38:14 +00003409 });
Alexey Bataev617db5f2017-12-04 15:38:33 +00003410 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00003411 // Emit final copy of the lastprivate variables if IsLastIter != 0.
Alexey Bataev617db5f2017-12-04 15:38:33 +00003412 if (HasLastprivateClause) {
Carlo Bertolli962bb802017-01-03 18:24:42 +00003413 EmitOMPLastprivateClauseFinal(
3414 S, /*NoFinals=*/false,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003415 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
Alexey Bataev617db5f2017-12-04 15:38:33 +00003416 }
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003417 }
3418
3419 // We're now done with the loop, so jump to the continuation block.
3420 if (ContBlock) {
3421 EmitBranch(ContBlock);
3422 EmitBlock(ContBlock, true);
3423 }
3424 }
3425}
3426
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003427void CodeGenFunction::EmitOMPDistributeDirective(
3428 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003429 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003430 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003431 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003432 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev10a54312017-11-27 16:54:08 +00003433 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003434}
3435
Alexey Bataev5f600d62015-09-29 03:48:57 +00003436static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3437 const CapturedStmt *S) {
3438 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3439 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3440 CGF.CapturedStmtInfo = &CapStmtInfo;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003441 llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003442 Fn->setDoesNotRecurse();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003443 return Fn;
3444}
3445
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003446void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003447 if (S.hasClausesOfKind<OMPDependClause>()) {
3448 assert(!S.getAssociatedStmt() &&
3449 "No associated statement must be in ordered depend construct.");
Alexey Bataev8b427062016-05-25 12:36:08 +00003450 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3451 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003452 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003453 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003454 const auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003455 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3456 PrePostActionTy &Action) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003457 const CapturedStmt *CS = S.getInnermostCapturedStmt();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003458 if (C) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003459 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3460 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003461 llvm::Function *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003462 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
Alexey Bataev3c595a62017-08-14 15:01:03 +00003463 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003464 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003465 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003466 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev5f600d62015-09-29 03:48:57 +00003467 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003468 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003469 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003470 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003471}
3472
Alexey Bataevb57056f2015-01-22 06:17:56 +00003473static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003474 QualType SrcType, QualType DestType,
3475 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003476 assert(CGF.hasScalarEvaluationKind(DestType) &&
3477 "DestType must have scalar evaluation kind.");
3478 assert(!Val.isAggregate() && "Must be a scalar or complex.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003479 return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3480 DestType, Loc)
3481 : CGF.EmitComplexToScalarConversion(
3482 Val.getComplexVal(), SrcType, DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003483}
3484
3485static CodeGenFunction::ComplexPairTy
3486convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003487 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003488 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3489 "DestType must have complex evaluation kind.");
3490 CodeGenFunction::ComplexPairTy ComplexVal;
3491 if (Val.isScalar()) {
3492 // Convert the input element to the element type of the complex.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003493 QualType DestElementType =
3494 DestType->castAs<ComplexType>()->getElementType();
3495 llvm::Value *ScalarVal = CGF.EmitScalarConversion(
3496 Val.getScalarVal(), SrcType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003497 ComplexVal = CodeGenFunction::ComplexPairTy(
3498 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3499 } else {
3500 assert(Val.isComplex() && "Must be a scalar or complex.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003501 QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3502 QualType DestElementType =
3503 DestType->castAs<ComplexType>()->getElementType();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003504 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003505 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003506 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003507 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003508 }
3509 return ComplexVal;
3510}
3511
Alexey Bataev5e018f92015-04-23 06:35:10 +00003512static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3513 LValue LVal, RValue RVal) {
3514 if (LVal.isGlobalReg()) {
3515 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3516 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003517 CGF.EmitAtomicStore(RVal, LVal,
3518 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3519 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003520 LVal.isVolatile(), /*IsInit=*/false);
3521 }
3522}
3523
Alexey Bataev8524d152016-01-21 12:35:58 +00003524void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3525 QualType RValTy, SourceLocation Loc) {
3526 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003527 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003528 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3529 *this, RVal, RValTy, LVal.getType(), Loc)),
3530 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003531 break;
3532 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003533 EmitStoreOfComplex(
3534 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003535 /*isInit=*/false);
3536 break;
3537 case TEK_Aggregate:
3538 llvm_unreachable("Must be a scalar or complex.");
3539 }
3540}
3541
Alexey Bataevddf3db92018-04-13 17:31:06 +00003542static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb57056f2015-01-22 06:17:56 +00003543 const Expr *X, const Expr *V,
3544 SourceLocation Loc) {
3545 // v = x;
3546 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3547 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3548 LValue XLValue = CGF.EmitLValue(X);
3549 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003550 RValue Res = XLValue.isGlobalReg()
3551 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003552 : CGF.EmitAtomicLoad(
3553 XLValue, Loc,
3554 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3555 : llvm::AtomicOrdering::Monotonic,
3556 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003557 // OpenMP, 2.12.6, atomic Construct
3558 // Any atomic construct with a seq_cst clause forces the atomically
3559 // performed operation to include an implicit flush operation without a
3560 // list.
3561 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003562 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003563 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003564}
3565
Alexey Bataevddf3db92018-04-13 17:31:06 +00003566static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb8329262015-02-27 06:33:30 +00003567 const Expr *X, const Expr *E,
3568 SourceLocation Loc) {
3569 // x = expr;
3570 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003571 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003572 // OpenMP, 2.12.6, atomic Construct
3573 // Any atomic construct with a seq_cst clause forces the atomically
3574 // performed operation to include an implicit flush operation without a
3575 // list.
3576 if (IsSeqCst)
3577 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3578}
3579
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003580static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3581 RValue Update,
3582 BinaryOperatorKind BO,
3583 llvm::AtomicOrdering AO,
3584 bool IsXLHSInRHSPart) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003585 ASTContext &Context = CGF.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003586 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003587 // expression is simple and atomic is allowed for the given type for the
3588 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003589 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003590 !Update.getScalarVal()->getType()->isIntegerTy() ||
3591 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3592 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003593 X.getAddress().getElementType())) ||
3594 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003595 !Context.getTargetInfo().hasBuiltinAtomic(
3596 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003597 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003598
3599 llvm::AtomicRMWInst::BinOp RMWOp;
3600 switch (BO) {
3601 case BO_Add:
3602 RMWOp = llvm::AtomicRMWInst::Add;
3603 break;
3604 case BO_Sub:
3605 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003606 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003607 RMWOp = llvm::AtomicRMWInst::Sub;
3608 break;
3609 case BO_And:
3610 RMWOp = llvm::AtomicRMWInst::And;
3611 break;
3612 case BO_Or:
3613 RMWOp = llvm::AtomicRMWInst::Or;
3614 break;
3615 case BO_Xor:
3616 RMWOp = llvm::AtomicRMWInst::Xor;
3617 break;
3618 case BO_LT:
3619 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3620 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3621 : llvm::AtomicRMWInst::Max)
3622 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3623 : llvm::AtomicRMWInst::UMax);
3624 break;
3625 case BO_GT:
3626 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3627 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3628 : llvm::AtomicRMWInst::Min)
3629 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3630 : llvm::AtomicRMWInst::UMin);
3631 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003632 case BO_Assign:
3633 RMWOp = llvm::AtomicRMWInst::Xchg;
3634 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003635 case BO_Mul:
3636 case BO_Div:
3637 case BO_Rem:
3638 case BO_Shl:
3639 case BO_Shr:
3640 case BO_LAnd:
3641 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003642 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003643 case BO_PtrMemD:
3644 case BO_PtrMemI:
3645 case BO_LE:
3646 case BO_GE:
3647 case BO_EQ:
3648 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00003649 case BO_Cmp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003650 case BO_AddAssign:
3651 case BO_SubAssign:
3652 case BO_AndAssign:
3653 case BO_OrAssign:
3654 case BO_XorAssign:
3655 case BO_MulAssign:
3656 case BO_DivAssign:
3657 case BO_RemAssign:
3658 case BO_ShlAssign:
3659 case BO_ShrAssign:
3660 case BO_Comma:
3661 llvm_unreachable("Unsupported atomic update operation");
3662 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003663 llvm::Value *UpdateVal = Update.getScalarVal();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003664 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3665 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003666 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003667 X.getType()->hasSignedIntegerRepresentation());
3668 }
Alexey Bataevddf3db92018-04-13 17:31:06 +00003669 llvm::Value *Res =
3670 CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003671 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003672}
3673
Alexey Bataev5e018f92015-04-23 06:35:10 +00003674std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003675 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3676 llvm::AtomicOrdering AO, SourceLocation Loc,
Alexey Bataevddf3db92018-04-13 17:31:06 +00003677 const llvm::function_ref<RValue(RValue)> CommonGen) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003678 // Update expressions are allowed to have the following forms:
3679 // x binop= expr; -> xrval + expr;
3680 // x++, ++x -> xrval + 1;
3681 // x--, --x -> xrval - 1;
3682 // x = x binop expr; -> xrval binop expr
3683 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003684 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3685 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003686 if (X.isGlobalReg()) {
3687 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3688 // 'xrval'.
3689 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3690 } else {
3691 // Perform compare-and-swap procedure.
3692 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003693 }
3694 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003695 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003696}
3697
Alexey Bataevddf3db92018-04-13 17:31:06 +00003698static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataevb4505a72015-03-30 05:20:59 +00003699 const Expr *X, const Expr *E,
3700 const Expr *UE, bool IsXLHSInRHSPart,
3701 SourceLocation Loc) {
3702 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3703 "Update expr in 'atomic update' must be a binary operator.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003704 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003705 // Update expressions are allowed to have the following forms:
3706 // x binop= expr; -> xrval + expr;
3707 // x++, ++x -> xrval + 1;
3708 // x--, --x -> xrval - 1;
3709 // x = x binop expr; -> xrval binop expr
3710 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003711 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003712 LValue XLValue = CGF.EmitLValue(X);
3713 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003714 llvm::AtomicOrdering AO = IsSeqCst
3715 ? llvm::AtomicOrdering::SequentiallyConsistent
3716 : llvm::AtomicOrdering::Monotonic;
3717 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3718 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3719 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3720 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3721 auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) {
3722 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3723 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3724 return CGF.EmitAnyExpr(UE);
3725 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003726 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3727 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3728 // OpenMP, 2.12.6, atomic Construct
3729 // Any atomic construct with a seq_cst clause forces the atomically
3730 // performed operation to include an implicit flush operation without a
3731 // list.
3732 if (IsSeqCst)
3733 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3734}
3735
3736static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003737 QualType SourceType, QualType ResType,
3738 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003739 switch (CGF.getEvaluationKind(ResType)) {
3740 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003741 return RValue::get(
3742 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003743 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003744 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003745 return RValue::getComplex(Res.first, Res.second);
3746 }
3747 case TEK_Aggregate:
3748 break;
3749 }
3750 llvm_unreachable("Must be a scalar or complex.");
3751}
3752
Alexey Bataevddf3db92018-04-13 17:31:06 +00003753static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003754 bool IsPostfixUpdate, const Expr *V,
3755 const Expr *X, const Expr *E,
3756 const Expr *UE, bool IsXLHSInRHSPart,
3757 SourceLocation Loc) {
3758 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3759 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3760 RValue NewVVal;
3761 LValue VLValue = CGF.EmitLValue(V);
3762 LValue XLValue = CGF.EmitLValue(X);
3763 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003764 llvm::AtomicOrdering AO = IsSeqCst
3765 ? llvm::AtomicOrdering::SequentiallyConsistent
3766 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003767 QualType NewVValType;
3768 if (UE) {
3769 // 'x' is updated with some additional value.
3770 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3771 "Update expr in 'atomic capture' must be a binary operator.");
Alexey Bataevddf3db92018-04-13 17:31:06 +00003772 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
Alexey Bataev5e018f92015-04-23 06:35:10 +00003773 // Update expressions are allowed to have the following forms:
3774 // x binop= expr; -> xrval + expr;
3775 // x++, ++x -> xrval + 1;
3776 // x--, --x -> xrval - 1;
3777 // x = x binop expr; -> xrval binop expr
3778 // x = expr Op x; - > expr binop xrval;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003779 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3780 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3781 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003782 NewVValType = XRValExpr->getType();
Alexey Bataevddf3db92018-04-13 17:31:06 +00003783 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003784 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Alexey Bataevddf3db92018-04-13 17:31:06 +00003785 IsPostfixUpdate](RValue XRValue) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003786 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3787 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3788 RValue Res = CGF.EmitAnyExpr(UE);
3789 NewVVal = IsPostfixUpdate ? XRValue : Res;
3790 return Res;
3791 };
3792 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3793 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3794 if (Res.first) {
3795 // 'atomicrmw' instruction was generated.
3796 if (IsPostfixUpdate) {
3797 // Use old value from 'atomicrmw'.
3798 NewVVal = Res.second;
3799 } else {
3800 // 'atomicrmw' does not provide new value, so evaluate it using old
3801 // value of 'x'.
3802 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3803 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3804 NewVVal = CGF.EmitAnyExpr(UE);
3805 }
3806 }
3807 } else {
3808 // 'x' is simply rewritten with some 'expr'.
3809 NewVValType = X->getType().getNonReferenceType();
3810 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003811 X->getType().getNonReferenceType(), Loc);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003812 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003813 NewVVal = XRValue;
3814 return ExprRValue;
3815 };
3816 // Try to perform atomicrmw xchg, otherwise simple exchange.
3817 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3818 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3819 Loc, Gen);
3820 if (Res.first) {
3821 // 'atomicrmw' instruction was generated.
3822 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3823 }
3824 }
3825 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003826 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003827 // OpenMP, 2.12.6, atomic Construct
3828 // Any atomic construct with a seq_cst clause forces the atomically
3829 // performed operation to include an implicit flush operation without a
3830 // list.
3831 if (IsSeqCst)
3832 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3833}
3834
Alexey Bataevddf3db92018-04-13 17:31:06 +00003835static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003836 bool IsSeqCst, bool IsPostfixUpdate,
3837 const Expr *X, const Expr *V, const Expr *E,
3838 const Expr *UE, bool IsXLHSInRHSPart,
3839 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003840 switch (Kind) {
3841 case OMPC_read:
Alexey Bataevddf3db92018-04-13 17:31:06 +00003842 emitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003843 break;
3844 case OMPC_write:
Alexey Bataevddf3db92018-04-13 17:31:06 +00003845 emitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
Alexey Bataevb8329262015-02-27 06:33:30 +00003846 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003847 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003848 case OMPC_update:
Alexey Bataevddf3db92018-04-13 17:31:06 +00003849 emitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003850 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003851 case OMPC_capture:
Alexey Bataevddf3db92018-04-13 17:31:06 +00003852 emitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003853 IsXLHSInRHSPart, Loc);
3854 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003855 case OMPC_if:
3856 case OMPC_final:
3857 case OMPC_num_threads:
3858 case OMPC_private:
3859 case OMPC_firstprivate:
3860 case OMPC_lastprivate:
3861 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003862 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003863 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003864 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003865 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003866 case OMPC_collapse:
3867 case OMPC_default:
3868 case OMPC_seq_cst:
3869 case OMPC_shared:
3870 case OMPC_linear:
3871 case OMPC_aligned:
3872 case OMPC_copyin:
3873 case OMPC_copyprivate:
3874 case OMPC_flush:
3875 case OMPC_proc_bind:
3876 case OMPC_schedule:
3877 case OMPC_ordered:
3878 case OMPC_nowait:
3879 case OMPC_untied:
3880 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003881 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003882 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003883 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003884 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003885 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003886 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003887 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003888 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003889 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003890 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003891 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003892 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003893 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003894 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003895 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003896 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003897 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003898 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003899 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003900 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00003901 case OMPC_unified_address:
Alexey Bataev94c50642018-10-01 14:26:31 +00003902 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00003903 case OMPC_reverse_offload:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003904 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3905 }
3906}
3907
3908void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003909 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003910 OpenMPClauseKind Kind = OMPC_unknown;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003911 for (const OMPClause *C : S.clauses()) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003912 // Find first clause (skip seq_cst clause, if it is first).
3913 if (C->getClauseKind() != OMPC_seq_cst) {
3914 Kind = C->getClauseKind();
3915 break;
3916 }
3917 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003918
Alexey Bataevddf3db92018-04-13 17:31:06 +00003919 const Stmt *CS = S.getInnermostCapturedStmt()->IgnoreContainers();
3920 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS))
Alexey Bataev10fec572015-03-11 04:48:56 +00003921 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003922 // Processing for statements under 'atomic capture'.
3923 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00003924 for (const Stmt *C : Compound->body()) {
3925 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003926 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003927 }
3928 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003929
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003930 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3931 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003932 CGF.EmitStopPoint(CS);
Alexey Bataevddf3db92018-04-13 17:31:06 +00003933 emitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
Alexey Bataev5e018f92015-04-23 06:35:10 +00003934 S.getV(), S.getExpr(), S.getUpdateExpr(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003935 S.isXLHSInRHSPart(), S.getBeginLoc());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003936 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003937 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003938 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003939}
3940
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003941static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3942 const OMPExecutableDirective &S,
3943 const RegionCodeGenTy &CodeGen) {
3944 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3945 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00003946
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00003947 // On device emit this construct as inlined code.
3948 if (CGM.getLangOpts().OpenMPIsDevice) {
3949 OMPLexicalScope Scope(CGF, S, OMPD_target);
3950 CGM.getOpenMPRuntime().emitInlinedDirective(
3951 CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev4ac68a22018-05-16 15:08:32 +00003952 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00003953 });
3954 return;
3955 }
3956
Samuel Antaoee8fb302016-01-06 13:42:12 +00003957 llvm::Function *Fn = nullptr;
3958 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003959
Samuel Antaobed3c462015-10-02 16:14:20 +00003960 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003961 // Check for the at most one if clause associated with the target region.
3962 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3963 if (C->getNameModifier() == OMPD_unknown ||
3964 C->getNameModifier() == OMPD_target) {
3965 IfCond = C->getCondition();
3966 break;
3967 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003968 }
3969
3970 // Check if we have any device clause associated with the directive.
3971 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00003972 if (auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaobed3c462015-10-02 16:14:20 +00003973 Device = C->getDevice();
Samuel Antaobed3c462015-10-02 16:14:20 +00003974
Samuel Antaoee8fb302016-01-06 13:42:12 +00003975 // Check if we have an if clause whose conditional always evaluates to false
3976 // or if we do not have any targets specified. If so the target region is not
3977 // an offload entry point.
3978 bool IsOffloadEntry = true;
3979 if (IfCond) {
3980 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003981 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003982 IsOffloadEntry = false;
3983 }
3984 if (CGM.getLangOpts().OMPTargetTriples.empty())
3985 IsOffloadEntry = false;
3986
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003987 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003988 StringRef ParentName;
3989 // In case we have Ctors/Dtors we use the complete type variant to produce
3990 // the mangling of the device outlined kernel.
Alexey Bataevddf3db92018-04-13 17:31:06 +00003991 if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003992 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Alexey Bataevddf3db92018-04-13 17:31:06 +00003993 else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003994 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3995 else
3996 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003997 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003998
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003999 // Emit target region as a standalone region.
4000 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
4001 IsOffloadEntry, CodeGen);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004002 OMPLexicalScope Scope(CGF, S, OMPD_task);
4003 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004004}
4005
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004006static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
4007 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004008 Action.Enter(CGF);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004009 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4010 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4011 CGF.EmitOMPPrivateClause(S, PrivateScope);
4012 (void)PrivateScope.Privatize();
4013
Alexey Bataev475a7442018-01-12 19:39:11 +00004014 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00004015}
4016
4017void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
4018 StringRef ParentName,
4019 const OMPTargetDirective &S) {
4020 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4021 emitTargetRegion(CGF, S, Action);
4022 };
4023 llvm::Function *Fn;
4024 llvm::Constant *Addr;
4025 // Emit target region as a standalone region.
4026 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4027 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4028 assert(Fn && Addr && "Target device function emission failed.");
4029}
4030
4031void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
4032 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4033 emitTargetRegion(CGF, S, Action);
4034 };
4035 emitCommonOMPTargetDirective(*this, S, CodeGen);
4036}
4037
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004038static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
4039 const OMPExecutableDirective &S,
4040 OpenMPDirectiveKind InnermostKind,
4041 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004042 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004043 llvm::Value *OutlinedFn =
4044 CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
4045 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004046
Alexey Bataevddf3db92018-04-13 17:31:06 +00004047 const auto *NT = S.getSingleClause<OMPNumTeamsClause>();
4048 const auto *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004049 if (NT || TL) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004050 const Expr *NumTeams = NT ? NT->getNumTeams() : nullptr;
4051 const Expr *ThreadLimit = TL ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004052
Carlo Bertollic6872252016-04-04 15:55:02 +00004053 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004054 S.getBeginLoc());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004055 }
4056
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004057 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004058 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4059 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004060 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004061 CapturedVars);
4062}
4063
4064void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00004065 // Emit teams region as a standalone region.
Alexey Bataevc99042b2018-03-15 18:10:54 +00004066 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004067 Action.Enter(CGF);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004068 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00004069 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4070 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004071 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004072 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00004073 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004074 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004075 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00004076 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004077 emitPostUpdateForReductionClause(*this, S,
4078 [](CodeGenFunction &) { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00004079}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004080
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004081static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4082 const OMPTargetTeamsDirective &S) {
4083 auto *CS = S.getCapturedStmt(OMPD_teams);
4084 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004085 // Emit teams region as a standalone region.
4086 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004087 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004088 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4089 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4090 CGF.EmitOMPPrivateClause(S, PrivateScope);
4091 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4092 (void)PrivateScope.Privatize();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004093 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004094 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004095 };
4096 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004097 emitPostUpdateForReductionClause(CGF, S,
4098 [](CodeGenFunction &) { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004099}
4100
4101void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4102 CodeGenModule &CGM, StringRef ParentName,
4103 const OMPTargetTeamsDirective &S) {
4104 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4105 emitTargetTeamsRegion(CGF, Action, S);
4106 };
4107 llvm::Function *Fn;
4108 llvm::Constant *Addr;
4109 // Emit target region as a standalone region.
4110 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4111 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4112 assert(Fn && Addr && "Target device function emission failed.");
4113}
4114
4115void CodeGenFunction::EmitOMPTargetTeamsDirective(
4116 const OMPTargetTeamsDirective &S) {
4117 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4118 emitTargetTeamsRegion(CGF, Action, S);
4119 };
4120 emitCommonOMPTargetDirective(*this, S, CodeGen);
4121}
4122
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004123static void
4124emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4125 const OMPTargetTeamsDistributeDirective &S) {
4126 Action.Enter(CGF);
4127 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4128 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4129 };
4130
4131 // Emit teams region as a standalone region.
4132 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004133 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004134 Action.Enter(CGF);
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004135 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4136 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4137 (void)PrivateScope.Privatize();
4138 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4139 CodeGenDistribute);
4140 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4141 };
4142 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4143 emitPostUpdateForReductionClause(CGF, S,
4144 [](CodeGenFunction &) { return nullptr; });
4145}
4146
4147void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4148 CodeGenModule &CGM, StringRef ParentName,
4149 const OMPTargetTeamsDistributeDirective &S) {
4150 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4151 emitTargetTeamsDistributeRegion(CGF, Action, S);
4152 };
4153 llvm::Function *Fn;
4154 llvm::Constant *Addr;
4155 // Emit target region as a standalone region.
4156 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4157 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4158 assert(Fn && Addr && "Target device function emission failed.");
4159}
4160
4161void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4162 const OMPTargetTeamsDistributeDirective &S) {
4163 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4164 emitTargetTeamsDistributeRegion(CGF, Action, S);
4165 };
4166 emitCommonOMPTargetDirective(*this, S, CodeGen);
4167}
4168
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004169static void emitTargetTeamsDistributeSimdRegion(
4170 CodeGenFunction &CGF, PrePostActionTy &Action,
4171 const OMPTargetTeamsDistributeSimdDirective &S) {
4172 Action.Enter(CGF);
4173 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4174 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4175 };
4176
4177 // Emit teams region as a standalone region.
4178 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004179 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004180 Action.Enter(CGF);
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004181 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4182 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4183 (void)PrivateScope.Privatize();
4184 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4185 CodeGenDistribute);
4186 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4187 };
4188 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4189 emitPostUpdateForReductionClause(CGF, S,
4190 [](CodeGenFunction &) { return nullptr; });
4191}
4192
4193void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4194 CodeGenModule &CGM, StringRef ParentName,
4195 const OMPTargetTeamsDistributeSimdDirective &S) {
4196 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4197 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4198 };
4199 llvm::Function *Fn;
4200 llvm::Constant *Addr;
4201 // Emit target region as a standalone region.
4202 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4203 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4204 assert(Fn && Addr && "Target device function emission failed.");
4205}
4206
4207void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4208 const OMPTargetTeamsDistributeSimdDirective &S) {
4209 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4210 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4211 };
4212 emitCommonOMPTargetDirective(*this, S, CodeGen);
4213}
4214
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004215void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4216 const OMPTeamsDistributeDirective &S) {
4217
4218 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4219 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4220 };
4221
4222 // Emit teams region as a standalone region.
4223 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004224 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004225 Action.Enter(CGF);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004226 OMPPrivateScope PrivateScope(CGF);
4227 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4228 (void)PrivateScope.Privatize();
4229 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4230 CodeGenDistribute);
4231 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4232 };
Alexey Bataev95c6dd42017-11-29 15:14:16 +00004233 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004234 emitPostUpdateForReductionClause(*this, S,
4235 [](CodeGenFunction &) { return nullptr; });
4236}
4237
Alexey Bataev999277a2017-12-06 14:31:09 +00004238void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4239 const OMPTeamsDistributeSimdDirective &S) {
4240 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4241 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4242 };
4243
4244 // Emit teams region as a standalone region.
4245 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004246 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004247 Action.Enter(CGF);
Alexey Bataev999277a2017-12-06 14:31:09 +00004248 OMPPrivateScope PrivateScope(CGF);
4249 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4250 (void)PrivateScope.Privatize();
4251 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4252 CodeGenDistribute);
4253 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4254 };
4255 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4256 emitPostUpdateForReductionClause(*this, S,
4257 [](CodeGenFunction &) { return nullptr; });
4258}
4259
Carlo Bertolli62fae152017-11-20 20:46:39 +00004260void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4261 const OMPTeamsDistributeParallelForDirective &S) {
4262 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4263 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4264 S.getDistInc());
4265 };
4266
4267 // Emit teams region as a standalone region.
4268 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004269 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004270 Action.Enter(CGF);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004271 OMPPrivateScope PrivateScope(CGF);
4272 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4273 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00004274 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4275 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004276 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4277 };
4278 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4279 emitPostUpdateForReductionClause(*this, S,
4280 [](CodeGenFunction &) { return nullptr; });
4281}
4282
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004283void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4284 const OMPTeamsDistributeParallelForSimdDirective &S) {
4285 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4286 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4287 S.getDistInc());
4288 };
4289
4290 // Emit teams region as a standalone region.
4291 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004292 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004293 Action.Enter(CGF);
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004294 OMPPrivateScope PrivateScope(CGF);
4295 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4296 (void)PrivateScope.Privatize();
4297 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4298 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4299 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4300 };
4301 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4302 emitPostUpdateForReductionClause(*this, S,
4303 [](CodeGenFunction &) { return nullptr; });
4304}
4305
Carlo Bertolli52978c32018-01-03 21:12:44 +00004306static void emitTargetTeamsDistributeParallelForRegion(
4307 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
4308 PrePostActionTy &Action) {
Carlo Bertolli79712092018-02-28 20:48:35 +00004309 Action.Enter(CGF);
Carlo Bertolli52978c32018-01-03 21:12:44 +00004310 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4311 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4312 S.getDistInc());
4313 };
4314
4315 // Emit teams region as a standalone region.
4316 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004317 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004318 Action.Enter(CGF);
Carlo Bertolli52978c32018-01-03 21:12:44 +00004319 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4320 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4321 (void)PrivateScope.Privatize();
4322 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4323 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4324 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4325 };
4326
4327 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
4328 CodeGenTeams);
4329 emitPostUpdateForReductionClause(CGF, S,
4330 [](CodeGenFunction &) { return nullptr; });
4331}
4332
4333void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
4334 CodeGenModule &CGM, StringRef ParentName,
4335 const OMPTargetTeamsDistributeParallelForDirective &S) {
4336 // Emit SPMD target teams distribute parallel for region as a standalone
4337 // region.
4338 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4339 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4340 };
4341 llvm::Function *Fn;
4342 llvm::Constant *Addr;
4343 // Emit target region as a standalone region.
4344 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4345 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4346 assert(Fn && Addr && "Target device function emission failed.");
4347}
4348
4349void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
4350 const OMPTargetTeamsDistributeParallelForDirective &S) {
4351 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4352 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4353 };
4354 emitCommonOMPTargetDirective(*this, S, CodeGen);
4355}
4356
Alexey Bataev647dd842018-01-15 20:59:40 +00004357static void emitTargetTeamsDistributeParallelForSimdRegion(
4358 CodeGenFunction &CGF,
4359 const OMPTargetTeamsDistributeParallelForSimdDirective &S,
4360 PrePostActionTy &Action) {
Carlo Bertolli79712092018-02-28 20:48:35 +00004361 Action.Enter(CGF);
Alexey Bataev647dd842018-01-15 20:59:40 +00004362 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4363 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4364 S.getDistInc());
4365 };
4366
4367 // Emit teams region as a standalone region.
4368 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
Alexey Bataevc99042b2018-03-15 18:10:54 +00004369 PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004370 Action.Enter(CGF);
Alexey Bataev647dd842018-01-15 20:59:40 +00004371 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4372 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4373 (void)PrivateScope.Privatize();
4374 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4375 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4376 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4377 };
4378
4379 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
4380 CodeGenTeams);
4381 emitPostUpdateForReductionClause(CGF, S,
4382 [](CodeGenFunction &) { return nullptr; });
4383}
4384
4385void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
4386 CodeGenModule &CGM, StringRef ParentName,
4387 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4388 // Emit SPMD target teams distribute parallel for simd region as a standalone
4389 // region.
4390 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4391 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4392 };
4393 llvm::Function *Fn;
4394 llvm::Constant *Addr;
4395 // Emit target region as a standalone region.
4396 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4397 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4398 assert(Fn && Addr && "Target device function emission failed.");
4399}
4400
4401void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
4402 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4403 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4404 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4405 };
4406 emitCommonOMPTargetDirective(*this, S, CodeGen);
4407}
4408
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004409void CodeGenFunction::EmitOMPCancellationPointDirective(
4410 const OMPCancellationPointDirective &S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004411 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00004412 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004413}
4414
Alexey Bataev80909872015-07-02 11:25:17 +00004415void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004416 const Expr *IfCond = nullptr;
4417 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4418 if (C->getNameModifier() == OMPD_unknown ||
4419 C->getNameModifier() == OMPD_cancel) {
4420 IfCond = C->getCondition();
4421 break;
4422 }
4423 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004424 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004425 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00004426}
4427
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004428CodeGenFunction::JumpDest
4429CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00004430 if (Kind == OMPD_parallel || Kind == OMPD_task ||
4431 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004432 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004433 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00004434 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
4435 Kind == OMPD_distribute_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004436 Kind == OMPD_target_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004437 Kind == OMPD_teams_distribute_parallel_for ||
4438 Kind == OMPD_target_teams_distribute_parallel_for);
Alexey Bataev957d8562016-11-17 15:12:05 +00004439 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004440}
Michael Wong65f367f2015-07-21 13:44:28 +00004441
Samuel Antaocc10b852016-07-28 14:23:26 +00004442void CodeGenFunction::EmitOMPUseDevicePtrClause(
4443 const OMPClause &NC, OMPPrivateScope &PrivateScope,
4444 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
4445 const auto &C = cast<OMPUseDevicePtrClause>(NC);
4446 auto OrigVarIt = C.varlist_begin();
4447 auto InitIt = C.inits().begin();
Alexey Bataevddf3db92018-04-13 17:31:06 +00004448 for (const Expr *PvtVarIt : C.private_copies()) {
4449 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
4450 const auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
4451 const auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
Samuel Antaocc10b852016-07-28 14:23:26 +00004452
4453 // In order to identify the right initializer we need to match the
4454 // declaration used by the mapping logic. In some cases we may get
4455 // OMPCapturedExprDecl that refers to the original declaration.
4456 const ValueDecl *MatchingVD = OrigVD;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004457 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004458 // OMPCapturedExprDecl are used to privative fields of the current
4459 // structure.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004460 const auto *ME = cast<MemberExpr>(OED->getInit());
Samuel Antaocc10b852016-07-28 14:23:26 +00004461 assert(isa<CXXThisExpr>(ME->getBase()) &&
4462 "Base should be the current struct!");
4463 MatchingVD = ME->getMemberDecl();
4464 }
4465
4466 // If we don't have information about the current list item, move on to
4467 // the next one.
4468 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
4469 if (InitAddrIt == CaptureDeviceAddrMap.end())
4470 continue;
4471
Alexey Bataevddf3db92018-04-13 17:31:06 +00004472 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, OrigVD,
4473 InitAddrIt, InitVD,
4474 PvtVD]() {
Samuel Antaocc10b852016-07-28 14:23:26 +00004475 // Initialize the temporary initialization variable with the address we
4476 // get from the runtime library. We have to cast the source address
4477 // because it is always a void *. References are materialized in the
4478 // privatization scope, so the initialization here disregards the fact
4479 // the original variable is a reference.
4480 QualType AddrQTy =
4481 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
4482 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
4483 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
4484 setAddrOfLocalVar(InitVD, InitAddr);
4485
4486 // Emit private declaration, it will be initialized by the value we
4487 // declaration we just added to the local declarations map.
4488 EmitDecl(*PvtVD);
4489
4490 // The initialization variables reached its purpose in the emission
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004491 // of the previous declaration, so we don't need it anymore.
Samuel Antaocc10b852016-07-28 14:23:26 +00004492 LocalDeclMap.erase(InitVD);
4493
4494 // Return the address of the private variable.
4495 return GetAddrOfLocalVar(PvtVD);
4496 });
4497 assert(IsRegistered && "firstprivate var already registered as private");
4498 // Silence the warning about unused variable.
4499 (void)IsRegistered;
4500
4501 ++OrigVarIt;
4502 ++InitIt;
4503 }
4504}
4505
Michael Wong65f367f2015-07-21 13:44:28 +00004506// Generate the instructions for '#pragma omp target data' directive.
4507void CodeGenFunction::EmitOMPTargetDataDirective(
4508 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004509 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4510
4511 // Create a pre/post action to signal the privatization of the device pointer.
4512 // This action can be replaced by the OpenMP runtime code generation to
4513 // deactivate privatization.
4514 bool PrivatizeDevicePointers = false;
4515 class DevicePointerPrivActionTy : public PrePostActionTy {
4516 bool &PrivatizeDevicePointers;
4517
4518 public:
4519 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4520 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4521 void Enter(CodeGenFunction &CGF) override {
4522 PrivatizeDevicePointers = true;
4523 }
Samuel Antaodf158d52016-04-27 22:58:19 +00004524 };
Samuel Antaocc10b852016-07-28 14:23:26 +00004525 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4526
4527 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
Alexey Bataev475a7442018-01-12 19:39:11 +00004528 CodeGenFunction &CGF, PrePostActionTy &Action) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004529 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00004530 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Samuel Antaocc10b852016-07-28 14:23:26 +00004531 };
4532
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004533 // Codegen that selects whether to generate the privatization code or not.
Samuel Antaocc10b852016-07-28 14:23:26 +00004534 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4535 &InnermostCodeGen](CodeGenFunction &CGF,
4536 PrePostActionTy &Action) {
4537 RegionCodeGenTy RCG(InnermostCodeGen);
4538 PrivatizeDevicePointers = false;
4539
4540 // Call the pre-action to change the status of PrivatizeDevicePointers if
4541 // needed.
4542 Action.Enter(CGF);
4543
4544 if (PrivatizeDevicePointers) {
4545 OMPPrivateScope PrivateScope(CGF);
4546 // Emit all instances of the use_device_ptr clause.
4547 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4548 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4549 Info.CaptureDeviceAddrMap);
4550 (void)PrivateScope.Privatize();
4551 RCG(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004552 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00004553 RCG(CGF);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004554 }
Samuel Antaocc10b852016-07-28 14:23:26 +00004555 };
4556
4557 // Forward the provided action to the privatization codegen.
4558 RegionCodeGenTy PrivRCG(PrivCodeGen);
4559 PrivRCG.setAction(Action);
4560
4561 // Notwithstanding the body of the region is emitted as inlined directive,
4562 // we don't use an inline scope as changes in the references inside the
4563 // region are expected to be visible outside, so we do not privative them.
4564 OMPLexicalScope Scope(CGF, S);
4565 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4566 PrivRCG);
4567 };
4568
4569 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004570
4571 // If we don't have target devices, don't bother emitting the data mapping
4572 // code.
4573 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004574 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004575 return;
4576 }
4577
4578 // Check if we have any if clause associated with the directive.
4579 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004580 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antaodf158d52016-04-27 22:58:19 +00004581 IfCond = C->getCondition();
4582
4583 // Check if we have any device clause associated with the directive.
4584 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004585 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaodf158d52016-04-27 22:58:19 +00004586 Device = C->getDevice();
4587
Samuel Antaocc10b852016-07-28 14:23:26 +00004588 // Set the action to signal privatization of device pointers.
4589 RCG.setAction(PrivAction);
4590
4591 // Emit region code.
4592 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4593 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004594}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004595
Samuel Antaodf67fc42016-01-19 19:15:56 +00004596void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4597 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004598 // If we don't have target devices, don't bother emitting the data mapping
4599 // code.
4600 if (CGM.getLangOpts().OMPTargetTriples.empty())
4601 return;
4602
4603 // Check if we have any if clause associated with the directive.
4604 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004605 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004606 IfCond = C->getCondition();
4607
4608 // Check if we have any device clause associated with the directive.
4609 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004610 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004611 Device = C->getDevice();
4612
Alexey Bataev475a7442018-01-12 19:39:11 +00004613 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004614 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004615}
4616
Samuel Antao72590762016-01-19 20:04:50 +00004617void CodeGenFunction::EmitOMPTargetExitDataDirective(
4618 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004619 // If we don't have target devices, don't bother emitting the data mapping
4620 // code.
4621 if (CGM.getLangOpts().OMPTargetTriples.empty())
4622 return;
4623
4624 // Check if we have any if clause associated with the directive.
4625 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004626 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antao8dd66282016-04-27 23:14:30 +00004627 IfCond = C->getCondition();
4628
4629 // Check if we have any device clause associated with the directive.
4630 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004631 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antao8dd66282016-04-27 23:14:30 +00004632 Device = C->getDevice();
4633
Alexey Bataev475a7442018-01-12 19:39:11 +00004634 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004635 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004636}
4637
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004638static void emitTargetParallelRegion(CodeGenFunction &CGF,
4639 const OMPTargetParallelDirective &S,
4640 PrePostActionTy &Action) {
4641 // Get the captured statement associated with the 'parallel' region.
Alexey Bataevddf3db92018-04-13 17:31:06 +00004642 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004643 Action.Enter(CGF);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004644 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004645 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004646 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4647 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4648 CGF.EmitOMPPrivateClause(S, PrivateScope);
4649 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4650 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004651 // TODO: Add support for clauses.
4652 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004653 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004654 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004655 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4656 emitEmptyBoundParameters);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004657 emitPostUpdateForReductionClause(CGF, S,
4658 [](CodeGenFunction &) { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004659}
4660
4661void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4662 CodeGenModule &CGM, StringRef ParentName,
4663 const OMPTargetParallelDirective &S) {
4664 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4665 emitTargetParallelRegion(CGF, S, Action);
4666 };
4667 llvm::Function *Fn;
4668 llvm::Constant *Addr;
4669 // Emit target region as a standalone region.
4670 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4671 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4672 assert(Fn && Addr && "Target device function emission failed.");
4673}
4674
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004675void CodeGenFunction::EmitOMPTargetParallelDirective(
4676 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004677 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4678 emitTargetParallelRegion(CGF, S, Action);
4679 };
4680 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004681}
4682
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004683static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4684 const OMPTargetParallelForDirective &S,
4685 PrePostActionTy &Action) {
4686 Action.Enter(CGF);
4687 // Emit directive as a combined directive that consists of two implicit
4688 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00004689 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4690 Action.Enter(CGF);
Alexey Bataev2139ed62017-11-16 18:20:21 +00004691 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4692 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004693 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4694 emitDispatchForLoopBounds);
4695 };
4696 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4697 emitEmptyBoundParameters);
4698}
4699
4700void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4701 CodeGenModule &CGM, StringRef ParentName,
4702 const OMPTargetParallelForDirective &S) {
4703 // Emit SPMD target parallel for region as a standalone region.
4704 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4705 emitTargetParallelForRegion(CGF, S, Action);
4706 };
4707 llvm::Function *Fn;
4708 llvm::Constant *Addr;
4709 // Emit target region as a standalone region.
4710 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4711 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4712 assert(Fn && Addr && "Target device function emission failed.");
4713}
4714
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004715void CodeGenFunction::EmitOMPTargetParallelForDirective(
4716 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004717 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4718 emitTargetParallelForRegion(CGF, S, Action);
4719 };
4720 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004721}
4722
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004723static void
4724emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4725 const OMPTargetParallelForSimdDirective &S,
4726 PrePostActionTy &Action) {
4727 Action.Enter(CGF);
4728 // Emit directive as a combined directive that consists of two implicit
4729 // directives: 'parallel' with 'for' directive.
Alexey Bataevc99042b2018-03-15 18:10:54 +00004730 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4731 Action.Enter(CGF);
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004732 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4733 emitDispatchForLoopBounds);
4734 };
4735 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4736 emitEmptyBoundParameters);
4737}
4738
4739void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4740 CodeGenModule &CGM, StringRef ParentName,
4741 const OMPTargetParallelForSimdDirective &S) {
4742 // Emit SPMD target parallel for region as a standalone region.
4743 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4744 emitTargetParallelForSimdRegion(CGF, S, Action);
4745 };
4746 llvm::Function *Fn;
4747 llvm::Constant *Addr;
4748 // Emit target region as a standalone region.
4749 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4750 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4751 assert(Fn && Addr && "Target device function emission failed.");
4752}
4753
4754void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4755 const OMPTargetParallelForSimdDirective &S) {
4756 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4757 emitTargetParallelForSimdRegion(CGF, S, Action);
4758 };
4759 emitCommonOMPTargetDirective(*this, S, CodeGen);
4760}
4761
Alexey Bataev7292c292016-04-25 12:22:29 +00004762/// Emit a helper variable and return corresponding lvalue.
4763static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4764 const ImplicitParamDecl *PVD,
4765 CodeGenFunction::OMPPrivateScope &Privates) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004766 const auto *VDecl = cast<VarDecl>(Helper->getDecl());
4767 Privates.addPrivate(VDecl,
4768 [&CGF, PVD]() { return CGF.GetAddrOfLocalVar(PVD); });
Alexey Bataev7292c292016-04-25 12:22:29 +00004769}
4770
4771void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4772 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4773 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00004774 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
Alexey Bataevddf3db92018-04-13 17:31:06 +00004775 Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
4776 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev7292c292016-04-25 12:22:29 +00004777 const Expr *IfCond = nullptr;
4778 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4779 if (C->getNameModifier() == OMPD_unknown ||
4780 C->getNameModifier() == OMPD_taskloop) {
4781 IfCond = C->getCondition();
4782 break;
4783 }
4784 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004785
4786 OMPTaskDataTy Data;
4787 // Check if taskloop must be emitted without taskgroup.
4788 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004789 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004790 Data.Tied = true;
4791 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004792 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4793 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004794 Data.Schedule.setInt(/*IntVal=*/false);
4795 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004796 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4797 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004798 Data.Schedule.setInt(/*IntVal=*/true);
4799 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004800 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004801
4802 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4803 // if (PreCond) {
4804 // for (IV in 0..LastIteration) BODY;
4805 // <Final counter/linear vars updates>;
4806 // }
4807 //
4808
4809 // Emit: if (PreCond) - begin.
4810 // If the condition constant folds and can be elided, avoid emitting the
4811 // whole loop.
4812 bool CondConstant;
4813 llvm::BasicBlock *ContBlock = nullptr;
4814 OMPLoopScope PreInitScope(CGF, S);
4815 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4816 if (!CondConstant)
4817 return;
4818 } else {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004819 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
Alexey Bataev7292c292016-04-25 12:22:29 +00004820 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4821 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4822 CGF.getProfileCount(&S));
4823 CGF.EmitBlock(ThenBlock);
4824 CGF.incrementProfileCounter(&S);
4825 }
4826
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004827 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4828 CGF.EmitOMPSimdInit(S);
4829
Alexey Bataev7292c292016-04-25 12:22:29 +00004830 OMPPrivateScope LoopScope(CGF);
4831 // Emit helper vars inits.
4832 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4833 auto *I = CS->getCapturedDecl()->param_begin();
4834 auto *LBP = std::next(I, LowerBound);
4835 auto *UBP = std::next(I, UpperBound);
4836 auto *STP = std::next(I, Stride);
4837 auto *LIP = std::next(I, LastIter);
4838 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4839 LoopScope);
4840 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4841 LoopScope);
4842 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4843 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4844 LoopScope);
4845 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004846 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004847 (void)LoopScope.Privatize();
4848 // Emit the loop iteration variable.
4849 const Expr *IVExpr = S.getIterationVariable();
Alexey Bataevddf3db92018-04-13 17:31:06 +00004850 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
Alexey Bataev7292c292016-04-25 12:22:29 +00004851 CGF.EmitVarDecl(*IVDecl);
4852 CGF.EmitIgnoredExpr(S.getInit());
4853
4854 // Emit the iterations count variable.
4855 // If it is not a variable, Sema decided to calculate iterations count on
4856 // each iteration (e.g., it is foldable into a constant).
Alexey Bataevddf3db92018-04-13 17:31:06 +00004857 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004858 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4859 // Emit calculation of the iterations count.
4860 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4861 }
4862
4863 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4864 S.getInc(),
4865 [&S](CodeGenFunction &CGF) {
4866 CGF.EmitOMPLoopBody(S, JumpDest());
4867 CGF.EmitStopPoint(&S);
4868 },
4869 [](CodeGenFunction &) {});
4870 // Emit: if (PreCond) - end.
4871 if (ContBlock) {
4872 CGF.EmitBranch(ContBlock);
4873 CGF.EmitBlock(ContBlock, true);
4874 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004875 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4876 if (HasLastprivateClause) {
4877 CGF.EmitOMPLastprivateClauseFinal(
4878 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4879 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4880 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004881 (*LIP)->getType(), S.getBeginLoc())));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004882 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004883 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004884 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4885 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4886 const OMPTaskDataTy &Data) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004887 auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond,
4888 &Data](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004889 OMPLoopScope PreInitScope(CGF, S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004890 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004891 OutlinedFn, SharedsTy,
4892 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004893 };
4894 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4895 CodeGen);
4896 };
Alexey Bataev475a7442018-01-12 19:39:11 +00004897 if (Data.Nogroup) {
4898 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
4899 } else {
Alexey Bataev33446032017-07-12 18:09:32 +00004900 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4901 *this,
4902 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4903 PrePostActionTy &Action) {
4904 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00004905 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
4906 Data);
Alexey Bataev33446032017-07-12 18:09:32 +00004907 },
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004908 S.getBeginLoc());
Alexey Bataev33446032017-07-12 18:09:32 +00004909 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004910}
4911
Alexey Bataev49f6e782015-12-01 04:18:41 +00004912void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004913 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004914}
4915
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004916void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4917 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004918 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004919}
Samuel Antao686c70c2016-05-26 17:30:50 +00004920
4921// Generate the instructions for '#pragma omp target update' directive.
4922void CodeGenFunction::EmitOMPTargetUpdateDirective(
4923 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00004924 // If we don't have target devices, don't bother emitting the data mapping
4925 // code.
4926 if (CGM.getLangOpts().OMPTargetTriples.empty())
4927 return;
4928
4929 // Check if we have any if clause associated with the directive.
4930 const Expr *IfCond = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004931 if (const auto *C = S.getSingleClause<OMPIfClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00004932 IfCond = C->getCondition();
4933
4934 // Check if we have any device clause associated with the directive.
4935 const Expr *Device = nullptr;
Alexey Bataevddf3db92018-04-13 17:31:06 +00004936 if (const auto *C = S.getSingleClause<OMPDeviceClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00004937 Device = C->getDevice();
4938
Alexey Bataev475a7442018-01-12 19:39:11 +00004939 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004940 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00004941}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00004942
4943void CodeGenFunction::EmitSimpleOMPExecutableDirective(
4944 const OMPExecutableDirective &D) {
4945 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
4946 return;
4947 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
4948 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
4949 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
4950 } else {
4951 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataevddf3db92018-04-13 17:31:06 +00004952 for (const Expr *E : LD->counters()) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00004953 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
4954 cast<DeclRefExpr>(E)->getDecl())) {
4955 // Emit only those that were not explicitly referenced in clauses.
4956 if (!CGF.LocalDeclMap.count(VD))
4957 CGF.EmitVarDecl(*VD);
4958 }
4959 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00004960 for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) {
4961 if (!C->getNumForLoops())
4962 continue;
4963 for (unsigned I = LD->getCollapsedNumber(),
4964 E = C->getLoopNumIterations().size();
4965 I < E; ++I) {
4966 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
Mike Rice0ed46662018-09-20 17:19:41 +00004967 cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00004968 // Emit only those that were not explicitly referenced in clauses.
4969 if (!CGF.LocalDeclMap.count(VD))
4970 CGF.EmitVarDecl(*VD);
4971 }
4972 }
4973 }
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00004974 }
Alexey Bataev475a7442018-01-12 19:39:11 +00004975 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00004976 }
4977 };
4978 OMPSimdLexicalScope Scope(*this, D);
4979 CGM.getOpenMPRuntime().emitInlinedDirective(
4980 *this,
4981 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
4982 : D.getDirectiveKind(),
4983 CodeGen);
4984}
Alexey Bataevddf3db92018-04-13 17:31:06 +00004985