blob: fb919d7b0283a8b8fce41be0930b0b4eeb258d99 [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()) {
32 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
33 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000034 for (const auto *I : PreInit->decls()) {
35 if (!I->hasAttr<OMPCaptureNoInitAttr>())
36 CGF.EmitVarDecl(cast<VarDecl>(*I));
37 else {
38 CodeGenFunction::AutoVarEmission Emission =
39 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
40 CGF.EmitAutoVarCleanups(Emission);
41 }
42 }
Alexey Bataev3392d762016-02-16 11:18:12 +000043 }
44 }
45 }
46 }
Alexey Bataev4ba78a42016-04-27 07:56:03 +000047 CodeGenFunction::OMPPrivateScope InlinedShareds;
48
49 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
50 return CGF.LambdaCaptureFields.lookup(VD) ||
51 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
52 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
53 }
Alexey Bataev3392d762016-02-16 11:18:12 +000054
Alexey Bataev3392d762016-02-16 11:18:12 +000055public:
Alexey Bataev475a7442018-01-12 19:39:11 +000056 OMPLexicalScope(
57 CodeGenFunction &CGF, const OMPExecutableDirective &S,
58 const llvm::Optional<OpenMPDirectiveKind> CapturedRegion = llvm::None,
59 const bool EmitPreInitStmt = true)
Alexey Bataev4ba78a42016-04-27 07:56:03 +000060 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
61 InlinedShareds(CGF) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000062 if (EmitPreInitStmt)
63 emitPreInitStmt(CGF, S);
Alexey Bataev475a7442018-01-12 19:39:11 +000064 if (!CapturedRegion.hasValue())
65 return;
66 assert(S.hasAssociatedStmt() &&
67 "Expected associated statement for inlined directive.");
68 const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion);
69 for (auto &C : CS->captures()) {
70 if (C.capturesVariable() || C.capturesVariableByCopy()) {
71 auto *VD = C.getCapturedVar();
72 assert(VD == VD->getCanonicalDecl() &&
73 "Canonical decl must be captured.");
74 DeclRefExpr DRE(
75 const_cast<VarDecl *>(VD),
76 isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo &&
77 InlinedShareds.isGlobalVarCaptured(VD)),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +000078 VD->getType().getNonReferenceType(), VK_LValue, C.getLocation());
Alexey Bataev475a7442018-01-12 19:39:11 +000079 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
80 return CGF.EmitLValue(&DRE).getAddress();
81 });
Alexey Bataev4ba78a42016-04-27 07:56:03 +000082 }
83 }
Alexey Bataev475a7442018-01-12 19:39:11 +000084 (void)InlinedShareds.Privatize();
Alexey Bataev3392d762016-02-16 11:18:12 +000085 }
86};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000087
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000088/// Lexical scope for OpenMP parallel construct, that handles correct codegen
89/// for captured expressions.
90class OMPParallelScope final : public OMPLexicalScope {
91 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
92 OpenMPDirectiveKind Kind = S.getDirectiveKind();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +000093 return !(isOpenMPTargetExecutionDirective(Kind) ||
94 isOpenMPLoopBoundSharingDirective(Kind)) &&
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000095 isOpenMPParallelDirective(Kind);
96 }
97
98public:
99 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +0000100 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
101 EmitPreInitStmt(S)) {}
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +0000102};
103
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000104/// Lexical scope for OpenMP teams construct, that handles correct codegen
105/// for captured expressions.
106class OMPTeamsScope final : public OMPLexicalScope {
107 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
108 OpenMPDirectiveKind Kind = S.getDirectiveKind();
109 return !isOpenMPTargetExecutionDirective(Kind) &&
110 isOpenMPTeamsDirective(Kind);
111 }
112
113public:
114 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
Alexey Bataev475a7442018-01-12 19:39:11 +0000115 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
116 EmitPreInitStmt(S)) {}
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000117};
118
Alexey Bataev5a3af132016-03-29 08:58:54 +0000119/// Private scope for OpenMP loop-based directives, that supports capturing
120/// of used expression from loop statement.
121class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
122 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
Alexey Bataevc2e88a82017-12-04 21:30:42 +0000123 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000124 for (auto *E : S.counters()) {
125 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
126 (void)PreCondScope.addPrivate(VD, [&CGF, VD]() {
127 return CGF.CreateMemTemp(VD->getType().getNonReferenceType());
128 });
129 }
Alexey Bataevc2e88a82017-12-04 21:30:42 +0000130 (void)PreCondScope.Privatize();
Alexey Bataev5a3af132016-03-29 08:58:54 +0000131 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
132 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
133 for (const auto *I : PreInits->decls())
134 CGF.EmitVarDecl(cast<VarDecl>(*I));
135 }
136 }
137 }
138
139public:
140 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
141 : CodeGenFunction::RunCleanupsScope(CGF) {
142 emitPreInitStmt(CGF, S);
143 }
144};
145
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000146class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
147 CodeGenFunction::OMPPrivateScope InlinedShareds;
148
149 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
150 return CGF.LambdaCaptureFields.lookup(VD) ||
151 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
152 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
153 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
154 }
155
156public:
157 OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
158 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
159 InlinedShareds(CGF) {
160 for (const auto *C : S.clauses()) {
161 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
162 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
163 for (const auto *I : PreInit->decls()) {
164 if (!I->hasAttr<OMPCaptureNoInitAttr>())
165 CGF.EmitVarDecl(cast<VarDecl>(*I));
166 else {
167 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) {
218 if (auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
219 if (auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
220 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) {
234 auto &C = getContext();
235 llvm::Value *Size = nullptr;
236 auto SizeInChars = C.getTypeSizeInChars(Ty);
237 if (SizeInChars.isZero()) {
238 // getTypeSizeInChars() returns 0 for a VLA.
239 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
240 llvm::Value *ArraySize;
241 std::tie(ArraySize, Ty) = getVLASize(VAT);
242 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
243 }
244 SizeInChars = C.getTypeSizeInChars(Ty);
245 if (SizeInChars.isZero())
246 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
247 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
248 } else
249 Size = CGM.getSize(SizeInChars);
250 return Size;
251}
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()) {
262 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000263 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000264 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000265 } else if (CurCap->capturesThis())
266 CapturedVars.push_back(CXXThisValue);
Samuel Antao6d004262016-06-16 18:39:34 +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()) {
273 auto &Ctx = getContext();
274 auto DstAddr = CreateMemTemp(
275 Ctx.getUIntPtrType(),
276 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
277 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
278
279 auto *SrcAddrVal = EmitScalarConversion(
280 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 Bataeva9b9cc02018-01-23 18:12:38 +0000305 auto *CastedPtr = CGF.EmitScalarConversion(AddrLV.getAddress().getPointer(),
306 Ctx.getUIntPtrType(),
307 Ctx.getPointerType(DstType), Loc);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000308 auto TmpAddr =
309 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);
316 auto *RefVal = TmpAddr.getPointer();
317 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
318 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
Akira Hatanaka642f7992016-10-18 19:05:41 +0000319 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) {
326 if (T->isLValueReferenceType()) {
327 return C.getLValueReferenceType(
328 getCanonicalParamType(C, T.getNonReferenceType()),
329 /*SpelledAsLValue=*/false);
330 }
331 if (T->isPointerType())
332 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000333 if (auto *A = T->getAsArrayTypeUnsafe()) {
334 if (auto *VLA = dyn_cast<VariableArrayType>(A))
335 return getCanonicalParamType(C, VLA->getElementType());
336 else if (!A->isVariablyModifiedType())
337 return C.getCanonicalType(T);
338 }
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000339 return C.getCanonicalParamType(T);
340}
341
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000342namespace {
343 /// Contains required data for proper outlined function codegen.
344 struct FunctionOptions {
345 /// Captured statement for which the function is generated.
346 const CapturedStmt *S = nullptr;
347 /// true if cast to/from UIntPtr is required for variables captured by
348 /// value.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000349 const bool UIntPtrCastRequired = true;
Alexey Bataeve754b182017-08-09 19:38:53 +0000350 /// true if only casted arguments must be registered as local args or VLA
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000351 /// sizes.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000352 const bool RegisterCastedArgsOnly = false;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000353 /// Name of the generated function.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000354 const StringRef FunctionName;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000355 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
356 bool RegisterCastedArgsOnly,
Alexey Bataev4aa19052017-08-08 16:45:36 +0000357 StringRef FunctionName)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000358 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
359 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
Alexey Bataev4aa19052017-08-08 16:45:36 +0000360 FunctionName(FunctionName) {}
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000361 };
362}
363
Alexey Bataeve754b182017-08-09 19:38:53 +0000364static llvm::Function *emitOutlinedFunctionPrologue(
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000365 CodeGenFunction &CGF, FunctionArgList &Args,
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000366 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000367 &LocalAddrs,
368 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
369 &VLASizes,
370 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
371 const CapturedDecl *CD = FO.S->getCapturedDecl();
372 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000373 assert(CD->hasBody() && "missing CapturedDecl body");
374
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000375 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000376 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000377 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000378 ASTContext &Ctx = CGM.getContext();
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000379 FunctionArgList TargetArgs;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000380 Args.append(CD->param_begin(),
381 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000382 TargetArgs.append(
383 CD->param_begin(),
384 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000385 auto I = FO.S->captures().begin();
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000386 FunctionDecl *DebugFunctionDecl = nullptr;
387 if (!FO.UIntPtrCastRequired) {
388 FunctionProtoType::ExtProtoInfo EPI;
389 DebugFunctionDecl = FunctionDecl::Create(
390 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getLocStart(),
391 SourceLocation(), DeclarationName(), Ctx.VoidTy,
392 Ctx.getTrivialTypeSourceInfo(
393 Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI)),
394 SC_Static, /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
395 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000396 for (auto *FD : RD->fields()) {
397 QualType ArgType = FD->getType();
398 IdentifierInfo *II = nullptr;
399 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000400
401 // If this is a capture by copy and the type is not a pointer, the outlined
402 // function argument type should be uintptr and the value properly casted to
403 // uintptr. This is necessary given that the runtime library is only able to
404 // deal with pointers. We can pass in the same way the VLA type sizes to the
405 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000406 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000407 I->capturesVariableArrayType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000408 if (FO.UIntPtrCastRequired)
409 ArgType = Ctx.getUIntPtrType();
410 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000411
412 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000413 CapVar = I->getCapturedVar();
414 II = CapVar->getIdentifier();
415 } else if (I->capturesThis())
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000416 II = &Ctx.Idents.get("this");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000417 else {
418 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000419 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000420 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000421 if (ArgType->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000422 ArgType = getCanonicalParamType(Ctx, ArgType);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000423 VarDecl *Arg;
424 if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
425 Arg = ParmVarDecl::Create(
426 Ctx, DebugFunctionDecl,
427 CapVar ? CapVar->getLocStart() : FD->getLocStart(),
428 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
429 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
430 } else {
431 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
432 II, ArgType, ImplicitParamDecl::Other);
433 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000434 Args.emplace_back(Arg);
435 // Do not cast arguments if we emit function with non-original types.
436 TargetArgs.emplace_back(
437 FO.UIntPtrCastRequired
438 ? Arg
439 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000440 ++I;
441 }
442 Args.append(
443 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
444 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000445 TargetArgs.append(
446 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
447 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000448
449 // Create the function declaration.
Alexey Bataev2377fe92015-09-10 08:12:02 +0000450 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000451 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000452 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
453
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000454 llvm::Function *F =
455 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
456 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000457 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
458 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000459 F->setDoesNotThrow();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000460
461 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000462 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
463 FO.S->getLocStart(), CD->getBody()->getLocStart());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000464 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000465 I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000466 for (auto *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000467 // Do not map arguments if we emit function with non-original types.
468 Address LocalAddr(Address::invalid());
469 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
470 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
471 TargetArgs[Cnt]);
472 } else {
473 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
474 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000475 // If we are capturing a pointer by copy we don't need to do anything, just
476 // use the value that we get from the arguments.
477 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000478 const VarDecl *CurVD = I->getCapturedVar();
Samuel Antao403ffd42016-07-27 22:49:49 +0000479 // If the variable is a reference we need to materialize it here.
480 if (CurVD->getType()->isReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000481 Address RefAddr = CGF.CreateMemTemp(
482 CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
483 CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
484 /*Volatile=*/false, CurVD->getType());
Samuel Antao403ffd42016-07-27 22:49:49 +0000485 LocalAddr = RefAddr;
486 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000487 if (!FO.RegisterCastedArgsOnly)
488 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000489 ++Cnt;
490 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000491 continue;
492 }
493
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000494 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
495 AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000496 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000497 if (FO.UIntPtrCastRequired) {
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000498 ArgLVal = CGF.MakeAddrLValue(
499 castValueFromUintptr(CGF, I->getLocation(), FD->getType(),
500 Args[Cnt]->getName(), ArgLVal),
501 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000502 }
Alexey Bataev1e491372018-01-23 18:44:14 +0000503 auto *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000504 auto VAT = FD->getCapturedVLAType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000505 VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000506 } else if (I->capturesVariable()) {
507 auto *Var = I->getCapturedVar();
508 QualType VarTy = Var->getType();
509 Address ArgAddr = ArgLVal.getAddress();
510 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000511 if (ArgLVal.getType()->isLValueReferenceType()) {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +0000512 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000513 } else if (!VarTy->isVariablyModifiedType() || !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.");
527 auto *Var = I->getCapturedVar();
528 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);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000589 Args.clear();
590 LocalAddrs.clear();
591 VLASizes.clear();
592 llvm::Function *WrapperF =
593 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000594 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000595 llvm::SmallVector<llvm::Value *, 4> CallArgs;
596 for (const auto *Arg : Args) {
597 llvm::Value *CallArg;
598 auto I = LocalAddrs.find(Arg);
599 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000600 LValue LV = WrapperCGF.MakeAddrLValue(
601 I->second.second,
602 I->second.first ? I->second.first->getType() : Arg->getType(),
603 AlignmentSource::Decl);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000604 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getLocStart());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000605 } else {
606 auto EI = VLASizes.find(Arg);
607 if (EI != VLASizes.end())
608 CallArg = EI->second.second;
609 else {
610 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000611 Arg->getType(),
612 AlignmentSource::Decl);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000613 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getLocStart());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000614 }
615 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000616 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000617 }
Alexey Bataev3c595a62017-08-14 15:01:03 +0000618 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getLocStart(),
619 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000620 WrapperCGF.FinishFunction();
621 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000622}
623
Alexey Bataev9959db52014-05-06 10:08:46 +0000624//===----------------------------------------------------------------------===//
625// OpenMP Directive Emission
626//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000627void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000628 Address DestAddr, Address SrcAddr, QualType OriginalType,
629 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000630 // Perform element-by-element initialization.
631 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000632
633 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000634 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000635 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
636 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
637
638 auto SrcBegin = SrcAddr.getPointer();
639 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000640 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000641 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
642 // The basic structure here is a while-do loop.
643 auto BodyBB = createBasicBlock("omp.arraycpy.body");
644 auto DoneBB = createBasicBlock("omp.arraycpy.done");
645 auto IsEmpty =
646 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
647 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000648
Alexey Bataev420d45b2015-04-14 05:11:24 +0000649 // Enter the loop body, making that address the current address.
650 auto EntryBB = Builder.GetInsertBlock();
651 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000652
653 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
654
655 llvm::PHINode *SrcElementPHI =
656 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
657 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
658 Address SrcElementCurrent =
659 Address(SrcElementPHI,
660 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
661
662 llvm::PHINode *DestElementPHI =
663 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
664 DestElementPHI->addIncoming(DestBegin, EntryBB);
665 Address DestElementCurrent =
666 Address(DestElementPHI,
667 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000668
Alexey Bataev420d45b2015-04-14 05:11:24 +0000669 // Emit copy.
670 CopyGen(DestElementCurrent, SrcElementCurrent);
671
672 // Shift the address forward by one element.
673 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000674 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000675 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000676 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000677 // Check whether we've reached the end.
678 auto Done =
679 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
680 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000681 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
682 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000683
684 // Done.
685 EmitBlock(DoneBB, /*IsFinished=*/true);
686}
687
John McCall7f416cc2015-09-08 08:05:57 +0000688void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
689 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000690 const VarDecl *SrcVD, const Expr *Copy) {
691 if (OriginalType->isArrayType()) {
692 auto *BO = dyn_cast<BinaryOperator>(Copy);
693 if (BO && BO->getOpcode() == BO_Assign) {
694 // Perform simple memcpy for simple copying.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000695 LValue Dest = MakeAddrLValue(DestAddr, OriginalType);
696 LValue Src = MakeAddrLValue(SrcAddr, OriginalType);
697 EmitAggregateAssign(Dest, Src, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000698 } else {
699 // For arrays with complex element types perform element by element
700 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000701 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000702 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000703 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000704 // Working with the single array element, so have to remap
705 // destination and source variables to corresponding array
706 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000707 CodeGenFunction::OMPPrivateScope Remap(*this);
708 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000709 return DestElement;
710 });
711 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000712 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000713 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000714 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000715 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000716 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000717 } else {
718 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000719 CodeGenFunction::OMPPrivateScope Remap(*this);
720 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
721 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000722 (void)Remap.Privatize();
723 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000724 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000725 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000726}
727
Alexey Bataev69c62a92015-04-15 04:52:20 +0000728bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
729 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000730 if (!HaveInsertPoint())
731 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000732 bool FirstprivateIsLastprivate = false;
733 llvm::DenseSet<const VarDecl *> Lastprivates;
734 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
735 for (const auto *D : C->varlists())
736 Lastprivates.insert(
737 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
738 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000739 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev475a7442018-01-12 19:39:11 +0000740 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
741 getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind());
742 // Force emission of the firstprivate copy if the directive does not emit
743 // outlined function, like omp for, omp simd, omp distribute etc.
744 bool MustEmitFirstprivateCopy =
745 CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000746 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000747 auto IRef = C->varlist_begin();
748 auto InitsRef = C->inits().begin();
749 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000750 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000751 bool ThisFirstprivateIsLastprivate =
752 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
753 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev475a7442018-01-12 19:39:11 +0000754 if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000755 !FD->getType()->isReferenceType()) {
756 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
757 ++IRef;
758 ++InitsRef;
759 continue;
760 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000761 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000762 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000763 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000764 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
765 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
766 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000767 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
768 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
769 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000770 LValue OriginalLVal = EmitLValue(&DRE);
771 Address OriginalAddr = OriginalLVal.getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000772 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000773 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000774 // Emit VarDecl with copy init for arrays.
775 // Get the address of the original variable captured in current
776 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000777 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000778 auto Emission = EmitAutoVarAlloca(*VD);
779 auto *Init = VD->getInit();
780 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
781 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000782 LValue Dest = MakeAddrLValue(Emission.getAllocatedAddress(),
783 Type);
784 EmitAggregateAssign(Dest, OriginalLVal, Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000785 } else {
786 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000787 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000788 [this, VDInit, Init](Address DestElement,
789 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000790 // Clean up any temporaries needed by the initialization.
791 RunCleanupsScope InitScope(*this);
792 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000793 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000794 EmitAnyExprToMem(Init, DestElement,
795 Init->getType().getQualifiers(),
796 /*IsInitializer*/ false);
797 LocalDeclMap.erase(VDInit);
798 });
799 }
800 EmitAutoVarCleanups(Emission);
801 return Emission.getAllocatedAddress();
802 });
803 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000804 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000805 // Emit private VarDecl with copy init.
806 // Remap temp VDInit variable to the address of the original
807 // variable
808 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000809 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000810 EmitDecl(*VD);
811 LocalDeclMap.erase(VDInit);
812 return GetAddrOfLocalVar(VD);
813 });
814 }
815 assert(IsRegistered &&
816 "firstprivate var already registered as private");
817 // Silence the warning about unused variable.
818 (void)IsRegistered;
819 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000820 ++IRef;
821 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000822 }
823 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000824 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000825}
826
Alexey Bataev03b340a2014-10-21 03:16:40 +0000827void CodeGenFunction::EmitOMPPrivateClause(
828 const OMPExecutableDirective &D,
829 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000830 if (!HaveInsertPoint())
831 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000832 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000833 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000834 auto IRef = C->varlist_begin();
835 for (auto IInit : C->private_copies()) {
836 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000837 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
838 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
839 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000840 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000841 // Emit private VarDecl with copy init.
842 EmitDecl(*VD);
843 return GetAddrOfLocalVar(VD);
844 });
845 assert(IsRegistered && "private var already registered as private");
846 // Silence the warning about unused variable.
847 (void)IsRegistered;
848 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000849 ++IRef;
850 }
851 }
852}
853
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000854bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000855 if (!HaveInsertPoint())
856 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000857 // threadprivate_var1 = master_threadprivate_var1;
858 // operator=(threadprivate_var2, master_threadprivate_var2);
859 // ...
860 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000861 llvm::DenseSet<const VarDecl *> CopiedVars;
862 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000863 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000864 auto IRef = C->varlist_begin();
865 auto ISrcRef = C->source_exprs().begin();
866 auto IDestRef = C->destination_exprs().begin();
867 for (auto *AssignOp : C->assignment_ops()) {
868 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000869 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000870 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000871 // Get the address of the master variable. If we are emitting code with
872 // TLS support, the address is passed from the master as field in the
873 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000874 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000875 if (getLangOpts().OpenMPUseTLS &&
876 getContext().getTargetInfo().isTLSSupported()) {
877 assert(CapturedStmtInfo->lookup(VD) &&
878 "Copyin threadprivates should have been captured!");
879 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
880 VK_LValue, (*IRef)->getExprLoc());
881 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000882 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000883 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000884 MasterAddr =
885 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
886 : CGM.GetAddrOfGlobal(VD),
887 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000888 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000889 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000890 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000891 if (CopiedVars.size() == 1) {
892 // At first check if current thread is a master thread. If it is, no
893 // need to copy data.
894 CopyBegin = createBasicBlock("copyin.not.master");
895 CopyEnd = createBasicBlock("copyin.not.master.end");
896 Builder.CreateCondBr(
897 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000898 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
899 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000900 CopyBegin, CopyEnd);
901 EmitBlock(CopyBegin);
902 }
903 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
904 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000905 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000906 }
907 ++IRef;
908 ++ISrcRef;
909 ++IDestRef;
910 }
911 }
912 if (CopyEnd) {
913 // Exit out of copying procedure for non-master thread.
914 EmitBlock(CopyEnd, /*IsFinished=*/true);
915 return true;
916 }
917 return false;
918}
919
Alexey Bataev38e89532015-04-16 04:54:05 +0000920bool CodeGenFunction::EmitOMPLastprivateClauseInit(
921 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000922 if (!HaveInsertPoint())
923 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000924 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000925 llvm::DenseSet<const VarDecl *> SIMDLCVs;
926 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
927 auto *LoopDirective = cast<OMPLoopDirective>(&D);
928 for (auto *C : LoopDirective->counters()) {
929 SIMDLCVs.insert(
930 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
931 }
932 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000933 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000934 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000935 HasAtLeastOneLastprivate = true;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000936 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
937 !getLangOpts().OpenMPSimd)
Alexey Bataevf93095a2016-05-05 08:46:22 +0000938 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000939 auto IRef = C->varlist_begin();
940 auto IDestRef = C->destination_exprs().begin();
941 for (auto *IInit : C->private_copies()) {
942 // Keep the address of the original variable for future update at the end
943 // of the loop.
944 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000945 // Taskloops do not require additional initialization, it is done in
946 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000947 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
948 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000949 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000950 DeclRefExpr DRE(
951 const_cast<VarDecl *>(OrigVD),
952 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
953 OrigVD) != nullptr,
954 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
955 return EmitLValue(&DRE).getAddress();
956 });
957 // Check if the variable is also a firstprivate: in this case IInit is
958 // not generated. Initialization of this variable will happen in codegen
959 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000960 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000961 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000962 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
963 // Emit private VarDecl with copy init.
964 EmitDecl(*VD);
965 return GetAddrOfLocalVar(VD);
966 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000967 assert(IsRegistered &&
968 "lastprivate var already registered as private");
969 (void)IsRegistered;
970 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000971 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000972 ++IRef;
973 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000974 }
975 }
976 return HasAtLeastOneLastprivate;
977}
978
979void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000980 const OMPExecutableDirective &D, bool NoFinals,
981 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000982 if (!HaveInsertPoint())
983 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000984 // Emit following code:
985 // if (<IsLastIterCond>) {
986 // orig_var1 = private_orig_var1;
987 // ...
988 // orig_varn = private_orig_varn;
989 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000990 llvm::BasicBlock *ThenBB = nullptr;
991 llvm::BasicBlock *DoneBB = nullptr;
992 if (IsLastIterCond) {
993 ThenBB = createBasicBlock(".omp.lastprivate.then");
994 DoneBB = createBasicBlock(".omp.lastprivate.done");
995 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
996 EmitBlock(ThenBB);
997 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000998 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
999 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001000 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001001 auto IC = LoopDirective->counters().begin();
1002 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001003 auto *D =
1004 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1005 if (NoFinals)
1006 AlreadyEmittedVars.insert(D);
1007 else
1008 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001009 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001010 }
1011 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001012 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1013 auto IRef = C->varlist_begin();
1014 auto ISrcRef = C->source_exprs().begin();
1015 auto IDestRef = C->destination_exprs().begin();
1016 for (auto *AssignOp : C->assignment_ops()) {
1017 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1018 QualType Type = PrivateVD->getType();
1019 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
1020 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1021 // If lastprivate variable is a loop control variable for loop-based
1022 // directive, update its value before copyin back to original
1023 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001024 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
1025 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001026 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1027 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1028 // Get the address of the original variable.
1029 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
1030 // Get the address of the private variable.
1031 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
1032 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
1033 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +00001034 Address(Builder.CreateLoad(PrivateAddr),
1035 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001036 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +00001037 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001038 ++IRef;
1039 ++ISrcRef;
1040 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +00001041 }
Alexey Bataev005248a2016-02-25 05:25:57 +00001042 if (auto *PostUpdate = C->getPostUpdateExpr())
1043 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001044 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001045 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001046 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +00001047}
1048
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001049void CodeGenFunction::EmitOMPReductionClauseInit(
1050 const OMPExecutableDirective &D,
1051 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001052 if (!HaveInsertPoint())
1053 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001054 SmallVector<const Expr *, 4> Shareds;
1055 SmallVector<const Expr *, 4> Privates;
1056 SmallVector<const Expr *, 4> ReductionOps;
1057 SmallVector<const Expr *, 4> LHSs;
1058 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001059 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001060 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001061 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001062 auto ILHS = C->lhs_exprs().begin();
1063 auto IRHS = C->rhs_exprs().begin();
1064 for (const auto *Ref : C->varlists()) {
1065 Shareds.emplace_back(Ref);
1066 Privates.emplace_back(*IPriv);
1067 ReductionOps.emplace_back(*IRed);
1068 LHSs.emplace_back(*ILHS);
1069 RHSs.emplace_back(*IRHS);
1070 std::advance(IPriv, 1);
1071 std::advance(IRed, 1);
1072 std::advance(ILHS, 1);
1073 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001074 }
1075 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001076 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1077 unsigned Count = 0;
1078 auto ILHS = LHSs.begin();
1079 auto IRHS = RHSs.begin();
1080 auto IPriv = Privates.begin();
1081 for (const auto *IRef : Shareds) {
1082 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
1083 // Emit private VarDecl with reduction init.
1084 RedCG.emitSharedLValue(*this, Count);
1085 RedCG.emitAggregateType(*this, Count);
1086 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1087 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1088 RedCG.getSharedLValue(Count),
1089 [&Emission](CodeGenFunction &CGF) {
1090 CGF.EmitAutoVarInit(Emission);
1091 return true;
1092 });
1093 EmitAutoVarCleanups(Emission);
1094 Address BaseAddr = RedCG.adjustPrivateAddress(
1095 *this, Count, Emission.getAllocatedAddress());
1096 bool IsRegistered = PrivateScope.addPrivate(
1097 RedCG.getBaseDecl(Count), [BaseAddr]() -> Address { return BaseAddr; });
1098 assert(IsRegistered && "private var already registered as private");
1099 // Silence the warning about unused variable.
1100 (void)IsRegistered;
1101
1102 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1103 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001104 QualType Type = PrivateVD->getType();
1105 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1106 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001107 // Store the address of the original variable associated with the LHS
1108 // implicit variable.
1109 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1110 return RedCG.getSharedLValue(Count).getAddress();
1111 });
1112 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1113 return GetAddrOfLocalVar(PrivateVD);
1114 });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001115 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1116 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001117 // Store the address of the original variable associated with the LHS
1118 // implicit variable.
1119 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1120 return RedCG.getSharedLValue(Count).getAddress();
1121 });
1122 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1123 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1124 ConvertTypeForMem(RHSVD->getType()),
1125 "rhs.begin");
1126 });
1127 } else {
1128 QualType Type = PrivateVD->getType();
1129 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1130 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1131 // Store the address of the original variable associated with the LHS
1132 // implicit variable.
1133 if (IsArray) {
1134 OriginalAddr = Builder.CreateElementBitCast(
1135 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1136 }
1137 PrivateScope.addPrivate(
1138 LHSVD, [OriginalAddr]() -> Address { return OriginalAddr; });
1139 PrivateScope.addPrivate(
1140 RHSVD, [this, PrivateVD, RHSVD, IsArray]() -> Address {
1141 return IsArray
1142 ? Builder.CreateElementBitCast(
1143 GetAddrOfLocalVar(PrivateVD),
1144 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1145 : GetAddrOfLocalVar(PrivateVD);
1146 });
1147 }
1148 ++ILHS;
1149 ++IRHS;
1150 ++IPriv;
1151 ++Count;
1152 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001153}
1154
1155void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001156 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001157 if (!HaveInsertPoint())
1158 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001159 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001160 llvm::SmallVector<const Expr *, 8> LHSExprs;
1161 llvm::SmallVector<const Expr *, 8> RHSExprs;
1162 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001163 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001164 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001165 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001166 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001167 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1168 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1169 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1170 }
1171 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001172 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1173 isOpenMPParallelDirective(D.getDirectiveKind()) ||
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001174 ReductionKind == OMPD_simd;
1175 bool SimpleReduction = ReductionKind == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001176 // Emit nowait reduction if nowait clause is present or directive is a
1177 // parallel directive (it always has implicit barrier).
1178 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001179 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001180 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001181 }
1182}
1183
Alexey Bataev61205072016-03-02 04:57:40 +00001184static void emitPostUpdateForReductionClause(
1185 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1186 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1187 if (!CGF.HaveInsertPoint())
1188 return;
1189 llvm::BasicBlock *DoneBB = nullptr;
1190 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1191 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1192 if (!DoneBB) {
1193 if (auto *Cond = CondGen(CGF)) {
1194 // If the first post-update expression is found, emit conditional
1195 // block if it was requested.
1196 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1197 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1198 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1199 CGF.EmitBlock(ThenBB);
1200 }
1201 }
1202 CGF.EmitIgnoredExpr(PostUpdate);
1203 }
1204 }
1205 if (DoneBB)
1206 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1207}
1208
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001209namespace {
1210/// Codegen lambda for appending distribute lower and upper bounds to outlined
1211/// parallel function. This is necessary for combined constructs such as
1212/// 'distribute parallel for'
1213typedef llvm::function_ref<void(CodeGenFunction &,
1214 const OMPExecutableDirective &,
1215 llvm::SmallVectorImpl<llvm::Value *> &)>
1216 CodeGenBoundParametersTy;
1217} // anonymous namespace
1218
1219static void emitCommonOMPParallelDirective(
1220 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1221 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1222 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001223 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1224 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1225 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001226 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001227 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001228 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1229 /*IgnoreResultAssign*/ true);
1230 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1231 CGF, NumThreads, NumThreadsClause->getLocStart());
1232 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001233 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001234 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001235 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1236 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1237 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001238 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001239 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1240 if (C->getNameModifier() == OMPD_unknown ||
1241 C->getNameModifier() == OMPD_parallel) {
1242 IfCond = C->getCondition();
1243 break;
1244 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001245 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001246
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001247 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001248 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001249 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1250 // lower and upper bounds with the pragma 'for' chunking mechanism.
1251 // The following lambda takes care of appending the lower and upper bound
1252 // parameters when necessary
1253 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001254 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001255 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001256 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001257}
1258
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001259static void emitEmptyBoundParameters(CodeGenFunction &,
1260 const OMPExecutableDirective &,
1261 llvm::SmallVectorImpl<llvm::Value *> &) {}
1262
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001263void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001264 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001265 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001266 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001267 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001268 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1269 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001270 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001271 // propagation master's thread values of threadprivate variables to local
1272 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001273 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1274 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1275 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001276 }
1277 CGF.EmitOMPPrivateClause(S, PrivateScope);
1278 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1279 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00001280 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001281 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001282 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001283 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1284 emitEmptyBoundParameters);
Alexey Bataev61205072016-03-02 04:57:40 +00001285 emitPostUpdateForReductionClause(
1286 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001287}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001288
Alexey Bataev0f34da12015-07-02 04:17:07 +00001289void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1290 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001291 RunCleanupsScope BodyScope(*this);
1292 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001293 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001294 EmitIgnoredExpr(I);
1295 }
Alexander Musman3276a272015-03-21 10:12:56 +00001296 // Update the linear variables.
Alexey Bataev617db5f2017-12-04 15:38:33 +00001297 // In distribute directives only loop counters may be marked as linear, no
1298 // need to generate the code for them.
1299 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1300 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1301 for (auto *U : C->updates())
1302 EmitIgnoredExpr(U);
1303 }
Alexander Musman3276a272015-03-21 10:12:56 +00001304 }
1305
Alexander Musmana5f070a2014-10-01 06:03:56 +00001306 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001307 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001308 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001309 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001310 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001311 // The end (updates/cleanups).
1312 EmitBlock(Continue.getBlock());
1313 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001314}
1315
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001316void CodeGenFunction::EmitOMPInnerLoop(
1317 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1318 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001319 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1320 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001321 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001322
1323 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001324 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001325 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001326 const SourceRange &R = S.getSourceRange();
1327 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1328 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001329
1330 // If there are any cleanups between here and the loop-exit scope,
1331 // create a block to stage a loop exit along.
1332 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001333 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001334 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001335
Alexander Musmand196ef22014-10-07 08:57:09 +00001336 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001337
Alexey Bataev2df54a02015-03-12 08:53:29 +00001338 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001339 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001340 if (ExitBlock != LoopExit.getBlock()) {
1341 EmitBlock(ExitBlock);
1342 EmitBranchThroughCleanup(LoopExit);
1343 }
1344
1345 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001346 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001347
1348 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001349 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001350 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1351
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001352 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001353
1354 // Emit "IV = IV + 1" and a back-edge to the condition block.
1355 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001356 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001357 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001358 BreakContinueStack.pop_back();
1359 EmitBranch(CondBlock);
1360 LoopStack.pop();
1361 // Emit the fall-through block.
1362 EmitBlock(LoopExit.getBlock());
1363}
1364
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001365bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001366 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001367 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001368 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001369 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001370 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001371 for (auto *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001372 HasLinears = true;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001373 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001374 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1375 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1376 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1377 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1378 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1379 VD->getInit()->getType(), VK_LValue,
1380 VD->getInit()->getExprLoc());
1381 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1382 VD->getType()),
1383 /*capturedByInit=*/false);
1384 EmitAutoVarCleanups(Emission);
1385 } else
1386 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001387 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001388 // Emit the linear steps for the linear clauses.
1389 // If a step is not constant, it is pre-calculated before the loop.
1390 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1391 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001392 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001393 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001394 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001395 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001396 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001397 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001398}
1399
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001400void CodeGenFunction::EmitOMPLinearClauseFinal(
1401 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001402 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001403 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001404 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001405 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001406 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001407 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001408 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001409 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001410 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001411 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001412 // If the first post-update expression is found, emit conditional
1413 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001414 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1415 DoneBB = createBasicBlock(".omp.linear.pu.done");
1416 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1417 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001418 }
1419 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001420 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1421 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001422 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001423 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001424 Address OrigAddr = EmitLValue(&DRE).getAddress();
1425 CodeGenFunction::OMPPrivateScope VarScope(*this);
1426 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001427 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001428 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001429 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001430 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001431 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001432 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001433 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001434 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001435 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001436}
1437
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001438static void emitAlignedClause(CodeGenFunction &CGF,
1439 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001440 if (!CGF.HaveInsertPoint())
1441 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001442 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001443 unsigned ClauseAlignment = 0;
1444 if (auto AlignmentExpr = Clause->getAlignment()) {
1445 auto AlignmentCI =
1446 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1447 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001448 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001449 for (auto E : Clause->varlists()) {
1450 unsigned Alignment = ClauseAlignment;
1451 if (Alignment == 0) {
1452 // OpenMP [2.8.1, Description]
1453 // If no optional parameter is specified, implementation-defined default
1454 // alignments for SIMD instructions on the target platforms are assumed.
1455 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001456 CGF.getContext()
1457 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1458 E->getType()->getPointeeType()))
1459 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001460 }
1461 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1462 "alignment is not power of 2");
1463 if (Alignment != 0) {
1464 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1465 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1466 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001467 }
1468 }
1469}
1470
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001471void CodeGenFunction::EmitOMPPrivateLoopCounters(
1472 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1473 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001474 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001475 auto I = S.private_counters().begin();
1476 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001477 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1478 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001479 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001480 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001481 if (!LocalDeclMap.count(PrivateVD)) {
1482 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1483 EmitAutoVarCleanups(VarEmission);
1484 }
1485 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1486 /*RefersToEnclosingVariableOrCapture=*/false,
1487 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1488 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001489 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001490 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1491 VD->hasGlobalStorage()) {
1492 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1493 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1494 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1495 E->getType(), VK_LValue, E->getExprLoc());
1496 return EmitLValue(&DRE).getAddress();
1497 });
1498 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001499 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001500 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001501}
1502
Alexey Bataev62dbb972015-04-22 11:59:37 +00001503static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1504 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1505 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001506 if (!CGF.HaveInsertPoint())
1507 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001508 {
1509 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001510 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001511 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001512 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001513 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001514 CGF.EmitIgnoredExpr(I);
1515 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001516 }
1517 // Check that loop is executed at least one time.
1518 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1519}
1520
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001521void CodeGenFunction::EmitOMPLinearClause(
1522 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1523 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001524 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001525 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1526 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1527 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1528 for (auto *C : LoopDirective->counters()) {
1529 SIMDLCVs.insert(
1530 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1531 }
1532 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001533 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001534 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001535 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001536 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1537 auto *PrivateVD =
1538 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001539 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1540 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1541 // Emit private VarDecl with copy init.
1542 EmitVarDecl(*PrivateVD);
1543 return GetAddrOfLocalVar(PrivateVD);
1544 });
1545 assert(IsRegistered && "linear var already registered as private");
1546 // Silence the warning about unused variable.
1547 (void)IsRegistered;
1548 } else
1549 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001550 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001551 }
1552 }
1553}
1554
Alexey Bataev45bfad52015-08-21 12:19:04 +00001555static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001556 const OMPExecutableDirective &D,
1557 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001558 if (!CGF.HaveInsertPoint())
1559 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001560 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001561 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1562 /*ignoreResult=*/true);
1563 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1564 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1565 // In presence of finite 'safelen', it may be unsafe to mark all
1566 // the memory instructions parallel, because loop-carried
1567 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001568 if (!IsMonotonic)
1569 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001570 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001571 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1572 /*ignoreResult=*/true);
1573 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001574 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001575 // In presence of finite 'safelen', it may be unsafe to mark all
1576 // the memory instructions parallel, because loop-carried
1577 // dependences of 'safelen' iterations are possible.
1578 CGF.LoopStack.setParallel(false);
1579 }
1580}
1581
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001582void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1583 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001584 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001585 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001586 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001587 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001588}
1589
Alexey Bataevef549a82016-03-09 09:49:09 +00001590void CodeGenFunction::EmitOMPSimdFinal(
1591 const OMPLoopDirective &D,
1592 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001593 if (!HaveInsertPoint())
1594 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001595 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001596 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001597 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001598 for (auto F : D.finals()) {
1599 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001600 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1601 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1602 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1603 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001604 if (!DoneBB) {
1605 if (auto *Cond = CondGen(*this)) {
1606 // If the first post-update expression is found, emit conditional
1607 // block if it was requested.
1608 auto *ThenBB = createBasicBlock(".omp.final.then");
1609 DoneBB = createBasicBlock(".omp.final.done");
1610 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1611 EmitBlock(ThenBB);
1612 }
1613 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001614 Address OrigAddr = Address::invalid();
1615 if (CED)
1616 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1617 else {
1618 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1619 /*RefersToEnclosingVariableOrCapture=*/false,
1620 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1621 OrigAddr = EmitLValue(&DRE).getAddress();
1622 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001623 OMPPrivateScope VarScope(*this);
1624 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001625 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001626 (void)VarScope.Privatize();
1627 EmitIgnoredExpr(F);
1628 }
1629 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001630 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001631 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001632 if (DoneBB)
1633 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001634}
1635
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001636static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1637 const OMPLoopDirective &S,
1638 CodeGenFunction::JumpDest LoopExit) {
1639 CGF.EmitOMPLoopBody(S, LoopExit);
1640 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001641}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001642
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001643/// Emit a helper variable and return corresponding lvalue.
1644static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1645 const DeclRefExpr *Helper) {
1646 auto VDecl = cast<VarDecl>(Helper->getDecl());
1647 CGF.EmitVarDecl(*VDecl);
1648 return CGF.EmitLValue(Helper);
1649}
1650
Alexey Bataevf8365372017-11-17 17:57:25 +00001651static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1652 PrePostActionTy &Action) {
1653 Action.Enter(CGF);
1654 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1655 "Expected simd directive");
1656 OMPLoopScope PreInitScope(CGF, S);
1657 // if (PreCond) {
1658 // for (IV in 0..LastIteration) BODY;
1659 // <Final counter/linear vars updates>;
1660 // }
1661 //
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001662 if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
1663 isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
1664 isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
1665 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1666 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1667 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001668
Alexey Bataevf8365372017-11-17 17:57:25 +00001669 // Emit: if (PreCond) - begin.
1670 // If the condition constant folds and can be elided, avoid emitting the
1671 // whole loop.
1672 bool CondConstant;
1673 llvm::BasicBlock *ContBlock = nullptr;
1674 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1675 if (!CondConstant)
1676 return;
1677 } else {
1678 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1679 ContBlock = CGF.createBasicBlock("simd.if.end");
1680 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1681 CGF.getProfileCount(&S));
1682 CGF.EmitBlock(ThenBlock);
1683 CGF.incrementProfileCounter(&S);
1684 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001685
Alexey Bataevf8365372017-11-17 17:57:25 +00001686 // Emit the loop iteration variable.
1687 const Expr *IVExpr = S.getIterationVariable();
1688 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1689 CGF.EmitVarDecl(*IVDecl);
1690 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001691
Alexey Bataevf8365372017-11-17 17:57:25 +00001692 // Emit the iterations count variable.
1693 // If it is not a variable, Sema decided to calculate iterations count on
1694 // each iteration (e.g., it is foldable into a constant).
1695 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1696 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1697 // Emit calculation of the iterations count.
1698 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1699 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001700
Alexey Bataevf8365372017-11-17 17:57:25 +00001701 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001702
Alexey Bataevf8365372017-11-17 17:57:25 +00001703 emitAlignedClause(CGF, S);
1704 (void)CGF.EmitOMPLinearClauseInit(S);
1705 {
1706 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1707 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1708 CGF.EmitOMPLinearClause(S, LoopScope);
1709 CGF.EmitOMPPrivateClause(S, LoopScope);
1710 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1711 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1712 (void)LoopScope.Privatize();
1713 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1714 S.getInc(),
1715 [&S](CodeGenFunction &CGF) {
1716 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1717 CGF.EmitStopPoint(&S);
1718 },
1719 [](CodeGenFunction &) {});
1720 CGF.EmitOMPSimdFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001721 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001722 // Emit final copy of the lastprivate variables at the end of loops.
1723 if (HasLastprivateClause)
1724 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1725 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
1726 emitPostUpdateForReductionClause(
1727 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1728 }
1729 CGF.EmitOMPLinearClauseFinal(
1730 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1731 // Emit: if (PreCond) - end.
1732 if (ContBlock) {
1733 CGF.EmitBranch(ContBlock);
1734 CGF.EmitBlock(ContBlock, true);
1735 }
1736}
1737
1738void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1739 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1740 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001741 };
Alexey Bataev475a7442018-01-12 19:39:11 +00001742 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001743 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001744}
1745
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001746void CodeGenFunction::EmitOMPOuterLoop(
1747 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1748 CodeGenFunction::OMPPrivateScope &LoopScope,
1749 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1750 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1751 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001752 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001753
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001754 const Expr *IVExpr = S.getIterationVariable();
1755 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1756 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1757
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001758 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1759
1760 // Start the loop with a block that tests the condition.
1761 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1762 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001763 const SourceRange &R = S.getSourceRange();
1764 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1765 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001766
1767 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001768 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001769 // UB = min(UB, GlobalUB) or
1770 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1771 // 'distribute parallel for')
1772 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001773 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001774 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001775 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001776 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001777 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001778 BoolCondVal =
1779 RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1780 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001781 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001782
1783 // If there are any cleanups between here and the loop-exit scope,
1784 // create a block to stage a loop exit along.
1785 auto ExitBlock = LoopExit.getBlock();
1786 if (LoopScope.requiresCleanups())
1787 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1788
1789 auto LoopBody = createBasicBlock("omp.dispatch.body");
1790 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1791 if (ExitBlock != LoopExit.getBlock()) {
1792 EmitBlock(ExitBlock);
1793 EmitBranchThroughCleanup(LoopExit);
1794 }
1795 EmitBlock(LoopBody);
1796
Alexander Musman92bdaab2015-03-12 13:37:50 +00001797 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1798 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001799 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001800 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001801
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001802 // Create a block for the increment.
1803 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1804 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1805
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001806 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1807 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001808 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1809 LoopStack.setParallel(!IsMonotonic);
1810 else
1811 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001812
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001813 SourceLocation Loc = S.getLocStart();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001814
1815 // when 'distribute' is not combined with a 'for':
1816 // while (idx <= UB) { BODY; ++idx; }
1817 // when 'distribute' is combined with a 'for'
1818 // (e.g. 'distribute parallel for')
1819 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1820 EmitOMPInnerLoop(
1821 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1822 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1823 CodeGenLoop(CGF, S, LoopExit);
1824 },
1825 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1826 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1827 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001828
1829 EmitBlock(Continue.getBlock());
1830 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001831 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001832 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001833 EmitIgnoredExpr(LoopArgs.NextLB);
1834 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001835 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001836
1837 EmitBranch(CondBlock);
1838 LoopStack.pop();
1839 // Emit the fall-through block.
1840 EmitBlock(LoopExit.getBlock());
1841
1842 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001843 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1844 if (!DynamicOrOrdered)
Alexey Bataevf43f7142017-09-06 16:17:35 +00001845 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
1846 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00001847 };
1848 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001849}
1850
1851void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001852 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001853 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001854 const OMPLoopArguments &LoopArgs,
1855 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001856 auto &RT = CGM.getOpenMPRuntime();
1857
1858 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001859 const bool DynamicOrOrdered =
1860 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001861
1862 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001863 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001864 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001865 "static non-chunked schedule does not need outer loop");
1866
1867 // Emit outer loop.
1868 //
1869 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1870 // When schedule(dynamic,chunk_size) is specified, the iterations are
1871 // distributed to threads in the team in chunks as the threads request them.
1872 // Each thread executes a chunk of iterations, then requests another chunk,
1873 // until no chunks remain to be distributed. Each chunk contains chunk_size
1874 // iterations, except for the last chunk to be distributed, which may have
1875 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1876 //
1877 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1878 // to threads in the team in chunks as the executing threads request them.
1879 // Each thread executes a chunk of iterations, then requests another chunk,
1880 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1881 // each chunk is proportional to the number of unassigned iterations divided
1882 // by the number of threads in the team, decreasing to 1. For a chunk_size
1883 // with value k (greater than 1), the size of each chunk is determined in the
1884 // same way, with the restriction that the chunks do not contain fewer than k
1885 // iterations (except for the last chunk to be assigned, which may have fewer
1886 // than k iterations).
1887 //
1888 // When schedule(auto) is specified, the decision regarding scheduling is
1889 // delegated to the compiler and/or runtime system. The programmer gives the
1890 // implementation the freedom to choose any possible mapping of iterations to
1891 // threads in the team.
1892 //
1893 // When schedule(runtime) is specified, the decision regarding scheduling is
1894 // deferred until run time, and the schedule and chunk size are taken from the
1895 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1896 // implementation defined
1897 //
1898 // while(__kmpc_dispatch_next(&LB, &UB)) {
1899 // idx = LB;
1900 // while (idx <= UB) { BODY; ++idx;
1901 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1902 // } // inner loop
1903 // }
1904 //
1905 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1906 // When schedule(static, chunk_size) is specified, iterations are divided into
1907 // chunks of size chunk_size, and the chunks are assigned to the threads in
1908 // the team in a round-robin fashion in the order of the thread number.
1909 //
1910 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1911 // while (idx <= UB) { BODY; ++idx; } // inner loop
1912 // LB = LB + ST;
1913 // UB = UB + ST;
1914 // }
1915 //
1916
1917 const Expr *IVExpr = S.getIterationVariable();
1918 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1919 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1920
1921 if (DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001922 auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1923 llvm::Value *LBVal = DispatchBounds.first;
1924 llvm::Value *UBVal = DispatchBounds.second;
1925 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1926 LoopArgs.Chunk};
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001927 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001928 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001929 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001930 CGOpenMPRuntime::StaticRTInput StaticInit(
1931 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1932 LoopArgs.ST, LoopArgs.Chunk);
1933 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
1934 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001935 }
1936
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001937 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1938 const unsigned IVSize,
1939 const bool IVSigned) {
1940 if (Ordered) {
1941 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1942 IVSigned);
1943 }
1944 };
1945
1946 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1947 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1948 OuterLoopArgs.IncExpr = S.getInc();
1949 OuterLoopArgs.Init = S.getInit();
1950 OuterLoopArgs.Cond = S.getCond();
1951 OuterLoopArgs.NextLB = S.getNextLowerBound();
1952 OuterLoopArgs.NextUB = S.getNextUpperBound();
1953 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1954 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001955}
1956
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001957static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1958 const unsigned IVSize, const bool IVSigned) {}
1959
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001960void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001961 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1962 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1963 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001964
1965 auto &RT = CGM.getOpenMPRuntime();
1966
1967 // Emit outer loop.
1968 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1969 // dynamic
1970 //
1971
1972 const Expr *IVExpr = S.getIterationVariable();
1973 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1974 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1975
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001976 CGOpenMPRuntime::StaticRTInput StaticInit(
1977 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
1978 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
1979 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001980
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001981 // for combined 'distribute' and 'for' the increment expression of distribute
1982 // is store in DistInc. For 'distribute' alone, it is in Inc.
1983 Expr *IncExpr;
1984 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1985 IncExpr = S.getDistInc();
1986 else
1987 IncExpr = S.getInc();
1988
1989 // this routine is shared by 'omp distribute parallel for' and
1990 // 'omp distribute': select the right EUB expression depending on the
1991 // directive
1992 OMPLoopArguments OuterLoopArgs;
1993 OuterLoopArgs.LB = LoopArgs.LB;
1994 OuterLoopArgs.UB = LoopArgs.UB;
1995 OuterLoopArgs.ST = LoopArgs.ST;
1996 OuterLoopArgs.IL = LoopArgs.IL;
1997 OuterLoopArgs.Chunk = LoopArgs.Chunk;
1998 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1999 ? S.getCombinedEnsureUpperBound()
2000 : S.getEnsureUpperBound();
2001 OuterLoopArgs.IncExpr = IncExpr;
2002 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2003 ? S.getCombinedInit()
2004 : S.getInit();
2005 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2006 ? S.getCombinedCond()
2007 : S.getCond();
2008 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2009 ? S.getCombinedNextLowerBound()
2010 : S.getNextLowerBound();
2011 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2012 ? S.getCombinedNextUpperBound()
2013 : S.getNextUpperBound();
2014
2015 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
2016 LoopScope, OuterLoopArgs, CodeGenLoopContent,
2017 emitEmptyOrdered);
2018}
2019
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002020static std::pair<LValue, LValue>
2021emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
2022 const OMPExecutableDirective &S) {
2023 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2024 LValue LB =
2025 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2026 LValue UB =
2027 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2028
2029 // When composing 'distribute' with 'for' (e.g. as in 'distribute
2030 // parallel for') we need to use the 'distribute'
2031 // chunk lower and upper bounds rather than the whole loop iteration
2032 // space. These are parameters to the outlined function for 'parallel'
2033 // and we copy the bounds of the previous schedule into the
2034 // the current ones.
2035 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
2036 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002037 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
2038 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002039 PrevLBVal = CGF.EmitScalarConversion(
2040 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002041 LS.getIterationVariable()->getType(),
2042 LS.getPrevLowerBoundVariable()->getExprLoc());
2043 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
2044 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002045 PrevUBVal = CGF.EmitScalarConversion(
2046 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002047 LS.getIterationVariable()->getType(),
2048 LS.getPrevUpperBoundVariable()->getExprLoc());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002049
2050 CGF.EmitStoreOfScalar(PrevLBVal, LB);
2051 CGF.EmitStoreOfScalar(PrevUBVal, UB);
2052
2053 return {LB, UB};
2054}
2055
2056/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
2057/// we need to use the LB and UB expressions generated by the worksharing
2058/// code generation support, whereas in non combined situations we would
2059/// just emit 0 and the LastIteration expression
2060/// This function is necessary due to the difference of the LB and UB
2061/// types for the RT emission routines for 'for_static_init' and
2062/// 'for_dispatch_init'
2063static std::pair<llvm::Value *, llvm::Value *>
2064emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
2065 const OMPExecutableDirective &S,
2066 Address LB, Address UB) {
2067 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2068 const Expr *IVExpr = LS.getIterationVariable();
2069 // when implementing a dynamic schedule for a 'for' combined with a
2070 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
2071 // is not normalized as each team only executes its own assigned
2072 // distribute chunk
2073 QualType IteratorTy = IVExpr->getType();
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002074 llvm::Value *LBVal =
2075 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getLocStart());
2076 llvm::Value *UBVal =
2077 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getLocStart());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002078 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00002079}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002080
2081static void emitDistributeParallelForDistributeInnerBoundParams(
2082 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2083 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2084 const auto &Dir = cast<OMPLoopDirective>(S);
2085 LValue LB =
2086 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
2087 auto LBCast = CGF.Builder.CreateIntCast(
2088 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2089 CapturedVars.push_back(LBCast);
2090 LValue UB =
2091 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2092
2093 auto UBCast = CGF.Builder.CreateIntCast(
2094 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2095 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00002096}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002097
2098static void
2099emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2100 const OMPLoopDirective &S,
2101 CodeGenFunction::JumpDest LoopExit) {
2102 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
2103 PrePostActionTy &) {
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002104 bool HasCancel = false;
2105 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2106 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2107 HasCancel = D->hasCancel();
2108 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2109 HasCancel = D->hasCancel();
Alexey Bataev16e79882017-11-22 21:12:03 +00002110 else if (const auto *D =
2111 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2112 HasCancel = D->hasCancel();
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002113 }
2114 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2115 HasCancel);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002116 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2117 emitDistributeParallelForInnerBounds,
2118 emitDistributeParallelForDispatchBounds);
2119 };
2120
2121 emitCommonOMPParallelDirective(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002122 CGF, S,
2123 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2124 CGInlinedWorksharingLoop,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002125 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002126}
2127
Carlo Bertolli9925f152016-06-27 14:55:37 +00002128void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2129 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002130 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2131 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2132 S.getDistInc());
2133 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002134 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev10a54312017-11-27 16:54:08 +00002135 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002136}
2137
Kelvin Li4a39add2016-07-05 05:00:15 +00002138void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2139 const OMPDistributeParallelForSimdDirective &S) {
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002140 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2141 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2142 S.getDistInc());
2143 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002144 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002145 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Kelvin Li4a39add2016-07-05 05:00:15 +00002146}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002147
2148void CodeGenFunction::EmitOMPDistributeSimdDirective(
2149 const OMPDistributeSimdDirective &S) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00002150 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2151 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2152 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002153 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev617db5f2017-12-04 15:38:33 +00002154 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002155}
2156
Alexey Bataevf8365372017-11-17 17:57:25 +00002157void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2158 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2159 // Emit SPMD target parallel for region as a standalone region.
2160 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2161 emitOMPSimdRegion(CGF, S, Action);
2162 };
2163 llvm::Function *Fn;
2164 llvm::Constant *Addr;
2165 // Emit target region as a standalone region.
2166 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2167 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2168 assert(Fn && Addr && "Target device function emission failed.");
2169}
2170
Kelvin Li986330c2016-07-20 22:57:10 +00002171void CodeGenFunction::EmitOMPTargetSimdDirective(
2172 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002173 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2174 emitOMPSimdRegion(CGF, S, Action);
2175 };
2176 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002177}
2178
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002179namespace {
2180 struct ScheduleKindModifiersTy {
2181 OpenMPScheduleClauseKind Kind;
2182 OpenMPScheduleClauseModifier M1;
2183 OpenMPScheduleClauseModifier M2;
2184 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2185 OpenMPScheduleClauseModifier M1,
2186 OpenMPScheduleClauseModifier M2)
2187 : Kind(Kind), M1(M1), M2(M2) {}
2188 };
2189} // namespace
2190
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002191bool CodeGenFunction::EmitOMPWorksharingLoop(
2192 const OMPLoopDirective &S, Expr *EUB,
2193 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2194 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002195 // Emit the loop iteration variable.
2196 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2197 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2198 EmitVarDecl(*IVDecl);
2199
2200 // Emit the iterations count variable.
2201 // If it is not a variable, Sema decided to calculate iterations count on each
2202 // iteration (e.g., it is foldable into a constant).
2203 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2204 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2205 // Emit calculation of the iterations count.
2206 EmitIgnoredExpr(S.getCalcLastIteration());
2207 }
2208
2209 auto &RT = CGM.getOpenMPRuntime();
2210
Alexey Bataev38e89532015-04-16 04:54:05 +00002211 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002212 // Check pre-condition.
2213 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002214 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002215 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002216 // If the condition constant folds and can be elided, avoid emitting the
2217 // whole loop.
2218 bool CondConstant;
2219 llvm::BasicBlock *ContBlock = nullptr;
2220 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2221 if (!CondConstant)
2222 return false;
2223 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002224 auto *ThenBlock = createBasicBlock("omp.precond.then");
2225 ContBlock = createBasicBlock("omp.precond.end");
2226 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002227 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002228 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002229 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002230 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002231
Alexey Bataev8b427062016-05-25 12:36:08 +00002232 bool Ordered = false;
2233 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2234 if (OrderedClause->getNumForLoops())
2235 RT.emitDoacrossInit(*this, S);
2236 else
2237 Ordered = true;
2238 }
2239
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002240 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002241 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002242 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002243 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002244
2245 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2246 LValue LB = Bounds.first;
2247 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002248 LValue ST =
2249 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2250 LValue IL =
2251 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2252
Alexander Musmanc6388682014-12-15 07:07:06 +00002253 // Emit 'then' code.
2254 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002255 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002256 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002257 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002258 // initialization of firstprivate variables and post-update of
2259 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002260 CGM.getOpenMPRuntime().emitBarrierCall(
2261 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2262 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002263 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002264 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002265 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002266 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002267 EmitOMPPrivateLoopCounters(S, LoopScope);
2268 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002269 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002270
2271 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002272 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002273 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002274 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002275 ScheduleKind.Schedule = C->getScheduleKind();
2276 ScheduleKind.M1 = C->getFirstScheduleModifier();
2277 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002278 if (const auto *Ch = C->getChunkSize()) {
2279 Chunk = EmitScalarExpr(Ch);
2280 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2281 S.getIterationVariable()->getType(),
2282 S.getLocStart());
2283 }
2284 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002285 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2286 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002287 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2288 // If the static schedule kind is specified or if the ordered clause is
2289 // specified, and if no monotonic modifier is specified, the effect will
2290 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002291 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002292 /* Chunked */ Chunk != nullptr) &&
2293 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002294 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2295 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002296 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2297 // When no chunk_size is specified, the iteration space is divided into
2298 // chunks that are approximately equal in size, and at most one chunk is
2299 // distributed to each thread. Note that the size of the chunks is
2300 // unspecified in this case.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002301 CGOpenMPRuntime::StaticRTInput StaticInit(
2302 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
2303 UB.getAddress(), ST.getAddress());
2304 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
2305 ScheduleKind, StaticInit);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002306 auto LoopExit =
2307 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002308 // UB = min(UB, GlobalUB);
2309 EmitIgnoredExpr(S.getEnsureUpperBound());
2310 // IV = LB;
2311 EmitIgnoredExpr(S.getInit());
2312 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002313 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2314 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002315 [&S, LoopExit](CodeGenFunction &CGF) {
2316 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002317 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002318 },
2319 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002320 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002321 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002322 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002323 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2324 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002325 };
2326 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002327 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002328 const bool IsMonotonic =
2329 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2330 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2331 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2332 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002333 // Emit the outer loop, which requests its work chunk [LB..UB] from
2334 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002335 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2336 ST.getAddress(), IL.getAddress(),
2337 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002338 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002339 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002340 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002341 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2342 EmitOMPSimdFinal(S,
2343 [&](CodeGenFunction &CGF) -> llvm::Value * {
2344 return CGF.Builder.CreateIsNotNull(
2345 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2346 });
2347 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002348 EmitOMPReductionClauseFinal(
2349 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2350 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2351 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002352 // Emit post-update of the reduction variables if IsLastIter != 0.
2353 emitPostUpdateForReductionClause(
2354 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2355 return CGF.Builder.CreateIsNotNull(
2356 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2357 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002358 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2359 if (HasLastprivateClause)
2360 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002361 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2362 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002363 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002364 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002365 return CGF.Builder.CreateIsNotNull(
2366 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2367 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002368 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002369 if (ContBlock) {
2370 EmitBranch(ContBlock);
2371 EmitBlock(ContBlock, true);
2372 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002373 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002374 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002375}
2376
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002377/// The following two functions generate expressions for the loop lower
2378/// and upper bounds in case of static and dynamic (dispatch) schedule
2379/// of the associated 'for' or 'distribute' loop.
2380static std::pair<LValue, LValue>
2381emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2382 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2383 LValue LB =
2384 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2385 LValue UB =
2386 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2387 return {LB, UB};
2388}
2389
2390/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2391/// consider the lower and upper bound expressions generated by the
2392/// worksharing loop support, but we use 0 and the iteration space size as
2393/// constants
2394static std::pair<llvm::Value *, llvm::Value *>
2395emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2396 Address LB, Address UB) {
2397 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2398 const Expr *IVExpr = LS.getIterationVariable();
2399 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2400 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2401 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2402 return {LBVal, UBVal};
2403}
2404
Alexander Musmanc6388682014-12-15 07:07:06 +00002405void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002406 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002407 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2408 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002409 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002410 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2411 emitForLoopBounds,
2412 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002413 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002414 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002415 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002416 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2417 S.hasCancel());
2418 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002419
2420 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002421 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002422 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2423 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002424}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002425
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002426void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002427 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002428 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2429 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002430 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2431 emitForLoopBounds,
2432 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002433 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002434 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002435 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002436 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2437 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002438
2439 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002440 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002441 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2442 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002443}
2444
Alexey Bataev2df54a02015-03-12 08:53:29 +00002445static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2446 const Twine &Name,
2447 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002448 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002449 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002450 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002451 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002452}
2453
Alexey Bataev3392d762016-02-16 11:18:12 +00002454void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002455 const Stmt *Stmt = S.getInnermostCapturedStmt()->getCapturedStmt();
2456 const auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002457 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002458 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2459 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002460 auto &C = CGF.CGM.getContext();
2461 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2462 // Emit helper vars inits.
2463 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2464 CGF.Builder.getInt32(0));
2465 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2466 : CGF.Builder.getInt32(0);
2467 LValue UB =
2468 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2469 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2470 CGF.Builder.getInt32(1));
2471 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2472 CGF.Builder.getInt32(0));
2473 // Loop counter.
2474 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2475 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2476 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2477 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2478 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2479 // Generate condition for loop.
2480 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002481 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002482 // Increment for loop counter.
2483 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00002484 S.getLocStart(), true);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002485 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2486 // Iterate through all sections and emit a switch construct:
2487 // switch (IV) {
2488 // case 0:
2489 // <SectionStmt[0]>;
2490 // break;
2491 // ...
2492 // case <NumSection> - 1:
2493 // <SectionStmt[<NumSection> - 1]>;
2494 // break;
2495 // }
2496 // .omp.sections.exit:
2497 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002498 auto *SwitchStmt =
2499 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getLocStart()),
2500 ExitBB, CS == nullptr ? 1 : CS->size());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002501 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002502 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002503 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002504 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2505 CGF.EmitBlock(CaseBB);
2506 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002507 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002508 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002509 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002510 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002511 } else {
2512 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2513 CGF.EmitBlock(CaseBB);
2514 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2515 CGF.EmitStmt(Stmt);
2516 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002517 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002518 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002519 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002520
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002521 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2522 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002523 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002524 // initialization of firstprivate variables and post-update of lastprivate
2525 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002526 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2527 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2528 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002529 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002530 CGF.EmitOMPPrivateClause(S, LoopScope);
2531 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2532 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2533 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002534
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002535 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002536 OpenMPScheduleTy ScheduleKind;
2537 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002538 CGOpenMPRuntime::StaticRTInput StaticInit(
2539 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2540 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002541 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002542 CGF, S.getLocStart(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002543 // UB = min(UB, GlobalUB);
2544 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2545 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2546 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2547 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2548 // IV = LB;
2549 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2550 // while (idx <= UB) { BODY; ++idx; }
2551 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2552 [](CodeGenFunction &) {});
2553 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002554 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002555 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2556 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002557 };
2558 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002559 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002560 // Emit post-update of the reduction variables if IsLastIter != 0.
2561 emitPostUpdateForReductionClause(
2562 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2563 return CGF.Builder.CreateIsNotNull(
2564 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2565 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002566
2567 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2568 if (HasLastprivates)
2569 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002570 S, /*NoFinals=*/false,
2571 CGF.Builder.CreateIsNotNull(
2572 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002573 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002574
2575 bool HasCancel = false;
2576 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2577 HasCancel = OSD->hasCancel();
2578 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2579 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002580 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002581 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2582 HasCancel);
2583 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2584 // clause. Otherwise the barrier will be generated by the codegen for the
2585 // directive.
2586 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002587 // Emit implicit barrier to synchronize threads and avoid data races on
2588 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002589 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2590 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002591 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002592}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002593
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002594void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002595 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002596 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002597 EmitSections(S);
2598 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002599 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002600 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002601 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2602 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002603 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002604}
2605
2606void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002607 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002608 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002609 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002610 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002611 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2612 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002613}
2614
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002615void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002616 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002617 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002618 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002619 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002620 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002621 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002622 // Build a list of copyprivate variables along with helper expressions
2623 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002624 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002625 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002626 DestExprs.append(C->destination_exprs().begin(),
2627 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002628 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002629 AssignmentOps.append(C->assignment_ops().begin(),
2630 C->assignment_ops().end());
2631 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002632 // Emit code for 'single' region along with 'copyprivate' clauses
2633 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2634 Action.Enter(CGF);
2635 OMPPrivateScope SingleScope(CGF);
2636 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2637 CGF.EmitOMPPrivateClause(S, SingleScope);
2638 (void)SingleScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00002639 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002640 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002641 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002642 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002643 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2644 CopyprivateVars, DestExprs,
2645 SrcExprs, AssignmentOps);
2646 }
2647 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2648 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002649 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002650 CGM.getOpenMPRuntime().emitBarrierCall(
2651 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002652 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002653 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002654}
2655
Alexey Bataev8d690652014-12-04 07:23:53 +00002656void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002657 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2658 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002659 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002660 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002661 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002662 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002663}
2664
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002665void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002666 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2667 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002668 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002669 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002670 Expr *Hint = nullptr;
2671 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2672 Hint = HintClause->getHint();
Alexey Bataev475a7442018-01-12 19:39:11 +00002673 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002674 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2675 S.getDirectiveName().getAsString(),
2676 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002677}
2678
Alexey Bataev671605e2015-04-13 05:28:11 +00002679void CodeGenFunction::EmitOMPParallelForDirective(
2680 const OMPParallelForDirective &S) {
2681 // Emit directive as a combined directive that consists of two implicit
2682 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002683 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002684 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002685 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2686 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002687 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002688 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2689 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002690}
2691
Alexander Musmane4e893b2014-09-23 09:33:00 +00002692void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002693 const OMPParallelForSimdDirective &S) {
2694 // Emit directive as a combined directive that consists of two implicit
2695 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002696 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002697 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2698 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002699 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002700 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2701 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002702}
2703
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002704void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002705 const OMPParallelSectionsDirective &S) {
2706 // Emit directive as a combined directive that consists of two implicit
2707 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002708 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2709 CGF.EmitSections(S);
2710 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002711 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2712 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002713}
2714
Alexey Bataev475a7442018-01-12 19:39:11 +00002715void CodeGenFunction::EmitOMPTaskBasedDirective(
2716 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
2717 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
2718 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002719 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00002720 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002721 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002722 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002723 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002724 // Check if the task is final
2725 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2726 // If the condition constant folds and can be elided, try to avoid emitting
2727 // the condition and the dead arm of the if/else.
2728 auto *Cond = Clause->getCondition();
2729 bool CondConstant;
2730 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2731 Data.Final.setInt(CondConstant);
2732 else
2733 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2734 } else {
2735 // By default the task is not final.
2736 Data.Final.setInt(/*IntVal=*/false);
2737 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002738 // Check if the task has 'priority' clause.
2739 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002740 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002741 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002742 Data.Priority.setPointer(EmitScalarConversion(
2743 EmitScalarExpr(Prio), Prio->getType(),
2744 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2745 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002746 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002747 // The first function argument for tasks is a thread id, the second one is a
2748 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002749 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2750 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002751 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002752 auto IRef = C->varlist_begin();
2753 for (auto *IInit : C->private_copies()) {
2754 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2755 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002756 Data.PrivateVars.push_back(*IRef);
2757 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002758 }
2759 ++IRef;
2760 }
2761 }
2762 EmittedAsPrivate.clear();
2763 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002764 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002765 auto IRef = C->varlist_begin();
2766 auto IElemInitRef = C->inits().begin();
2767 for (auto *IInit : C->private_copies()) {
2768 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2769 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002770 Data.FirstprivateVars.push_back(*IRef);
2771 Data.FirstprivateCopies.push_back(IInit);
2772 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002773 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002774 ++IRef;
2775 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002776 }
2777 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002778 // Get list of lastprivate variables (for taskloops).
2779 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2780 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2781 auto IRef = C->varlist_begin();
2782 auto ID = C->destination_exprs().begin();
2783 for (auto *IInit : C->private_copies()) {
2784 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2785 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2786 Data.LastprivateVars.push_back(*IRef);
2787 Data.LastprivateCopies.push_back(IInit);
2788 }
2789 LastprivateDstsOrigs.insert(
2790 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2791 cast<DeclRefExpr>(*IRef)});
2792 ++IRef;
2793 ++ID;
2794 }
2795 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002796 SmallVector<const Expr *, 4> LHSs;
2797 SmallVector<const Expr *, 4> RHSs;
2798 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2799 auto IPriv = C->privates().begin();
2800 auto IRed = C->reduction_ops().begin();
2801 auto ILHS = C->lhs_exprs().begin();
2802 auto IRHS = C->rhs_exprs().begin();
2803 for (const auto *Ref : C->varlists()) {
2804 Data.ReductionVars.emplace_back(Ref);
2805 Data.ReductionCopies.emplace_back(*IPriv);
2806 Data.ReductionOps.emplace_back(*IRed);
2807 LHSs.emplace_back(*ILHS);
2808 RHSs.emplace_back(*IRHS);
2809 std::advance(IPriv, 1);
2810 std::advance(IRed, 1);
2811 std::advance(ILHS, 1);
2812 std::advance(IRHS, 1);
2813 }
2814 }
2815 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2816 *this, S.getLocStart(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002817 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002818 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2819 for (auto *IRef : C->varlists())
2820 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataev475a7442018-01-12 19:39:11 +00002821 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
2822 CapturedRegion](CodeGenFunction &CGF,
2823 PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002824 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002825 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002826 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2827 !Data.LastprivateVars.empty()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00002828 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataev48591dd2016-04-20 04:01:36 +00002829 auto *CopyFn = CGF.Builder.CreateLoad(
2830 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2831 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2832 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2833 // Map privates.
2834 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2835 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2836 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002837 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002838 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2839 Address PrivatePtr = CGF.CreateMemTemp(
2840 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2841 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2842 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002843 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002844 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002845 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2846 Address PrivatePtr =
2847 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2848 ".firstpriv.ptr.addr");
2849 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2850 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002851 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002852 for (auto *E : Data.LastprivateVars) {
2853 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2854 Address PrivatePtr =
2855 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2856 ".lastpriv.ptr.addr");
2857 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2858 CallArgs.push_back(PrivatePtr.getPointer());
2859 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00002860 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
2861 CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002862 for (auto &&Pair : LastprivateDstsOrigs) {
2863 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2864 DeclRefExpr DRE(
2865 const_cast<VarDecl *>(OrigVD),
2866 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2867 OrigVD) != nullptr,
2868 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2869 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2870 return CGF.EmitLValue(&DRE).getAddress();
2871 });
2872 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002873 for (auto &&Pair : PrivatePtrs) {
2874 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2875 CGF.getContext().getDeclAlign(Pair.first));
2876 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2877 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002878 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002879 if (Data.Reductions) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002880 OMPLexicalScope LexScope(CGF, S, CapturedRegion);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002881 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2882 Data.ReductionOps);
2883 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2884 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2885 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2886 RedCG.emitSharedLValue(CGF, Cnt);
2887 RedCG.emitAggregateType(CGF, Cnt);
2888 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2889 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2890 Replacement =
2891 Address(CGF.EmitScalarConversion(
2892 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2893 CGF.getContext().getPointerType(
2894 Data.ReductionCopies[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002895 Data.ReductionCopies[Cnt]->getExprLoc()),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002896 Replacement.getAlignment());
2897 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2898 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2899 [Replacement]() { return Replacement; });
2900 // FIXME: This must removed once the runtime library is fixed.
2901 // Emit required threadprivate variables for
2902 // initilizer/combiner/finalizer.
2903 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2904 RedCG, Cnt);
2905 }
2906 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002907 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002908 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002909 SmallVector<const Expr *, 4> InRedVars;
2910 SmallVector<const Expr *, 4> InRedPrivs;
2911 SmallVector<const Expr *, 4> InRedOps;
2912 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2913 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2914 auto IPriv = C->privates().begin();
2915 auto IRed = C->reduction_ops().begin();
2916 auto ITD = C->taskgroup_descriptors().begin();
2917 for (const auto *Ref : C->varlists()) {
2918 InRedVars.emplace_back(Ref);
2919 InRedPrivs.emplace_back(*IPriv);
2920 InRedOps.emplace_back(*IRed);
2921 TaskgroupDescriptors.emplace_back(*ITD);
2922 std::advance(IPriv, 1);
2923 std::advance(IRed, 1);
2924 std::advance(ITD, 1);
2925 }
2926 }
2927 // Privatize in_reduction items here, because taskgroup descriptors must be
2928 // privatized earlier.
2929 OMPPrivateScope InRedScope(CGF);
2930 if (!InRedVars.empty()) {
2931 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2932 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2933 RedCG.emitSharedLValue(CGF, Cnt);
2934 RedCG.emitAggregateType(CGF, Cnt);
2935 // The taskgroup descriptor variable is always implicit firstprivate and
2936 // privatized already during procoessing of the firstprivates.
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002937 llvm::Value *ReductionsPtr =
2938 CGF.EmitLoadOfScalar(CGF.EmitLValue(TaskgroupDescriptors[Cnt]),
2939 TaskgroupDescriptors[Cnt]->getExprLoc());
Alexey Bataev88202be2017-07-27 13:20:36 +00002940 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2941 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2942 Replacement = Address(
2943 CGF.EmitScalarConversion(
2944 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2945 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002946 InRedPrivs[Cnt]->getExprLoc()),
Alexey Bataev88202be2017-07-27 13:20:36 +00002947 Replacement.getAlignment());
2948 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2949 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2950 [Replacement]() { return Replacement; });
2951 // FIXME: This must removed once the runtime library is fixed.
2952 // Emit required threadprivate variables for
2953 // initilizer/combiner/finalizer.
2954 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2955 RedCG, Cnt);
2956 }
2957 }
2958 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00002959
2960 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002961 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002962 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002963 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2964 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2965 Data.NumberOfParts);
2966 OMPLexicalScope Scope(*this, S);
2967 TaskGen(*this, OutlinedFn, Data);
2968}
2969
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002970static ImplicitParamDecl *
2971createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002972 QualType Ty, CapturedDecl *CD,
2973 SourceLocation Loc) {
2974 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
2975 ImplicitParamDecl::Other);
2976 auto *OrigRef = DeclRefExpr::Create(
2977 C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
2978 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
2979 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
2980 ImplicitParamDecl::Other);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002981 auto *PrivateRef = DeclRefExpr::Create(
2982 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002983 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002984 QualType ElemType = C.getBaseElementType(Ty);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002985 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
2986 ImplicitParamDecl::Other);
2987 auto *InitRef = DeclRefExpr::Create(
2988 C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
2989 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002990 PrivateVD->setInitStyle(VarDecl::CInit);
2991 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
2992 InitRef, /*BasePath=*/nullptr,
2993 VK_RValue));
2994 Data.FirstprivateVars.emplace_back(OrigRef);
2995 Data.FirstprivateCopies.emplace_back(PrivateRef);
2996 Data.FirstprivateInits.emplace_back(InitRef);
2997 return OrigVD;
2998}
2999
3000void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
3001 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
3002 OMPTargetDataInfo &InputInfo) {
3003 // Emit outlined function for task construct.
3004 auto CS = S.getCapturedStmt(OMPD_task);
3005 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
3006 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3007 auto *I = CS->getCapturedDecl()->param_begin();
3008 auto *PartId = std::next(I);
3009 auto *TaskT = std::next(I, 4);
3010 OMPTaskDataTy Data;
3011 // The task is not final.
3012 Data.Final.setInt(/*IntVal=*/false);
3013 // Get list of firstprivate variables.
3014 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3015 auto IRef = C->varlist_begin();
3016 auto IElemInitRef = C->inits().begin();
3017 for (auto *IInit : C->private_copies()) {
3018 Data.FirstprivateVars.push_back(*IRef);
3019 Data.FirstprivateCopies.push_back(IInit);
3020 Data.FirstprivateInits.push_back(*IElemInitRef);
3021 ++IRef;
3022 ++IElemInitRef;
3023 }
3024 }
3025 OMPPrivateScope TargetScope(*this);
3026 VarDecl *BPVD = nullptr;
3027 VarDecl *PVD = nullptr;
3028 VarDecl *SVD = nullptr;
3029 if (InputInfo.NumberOfTargetItems > 0) {
3030 auto *CD = CapturedDecl::Create(
3031 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
3032 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
3033 QualType BaseAndPointersType = getContext().getConstantArrayType(
3034 getContext().VoidPtrTy, ArrSize, ArrayType::Normal,
3035 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003036 BPVD = createImplicitFirstprivateForType(
3037 getContext(), Data, BaseAndPointersType, CD, S.getLocStart());
3038 PVD = createImplicitFirstprivateForType(
3039 getContext(), Data, BaseAndPointersType, CD, S.getLocStart());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003040 QualType SizesType = getContext().getConstantArrayType(
3041 getContext().getSizeType(), ArrSize, ArrayType::Normal,
3042 /*IndexTypeQuals=*/0);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003043 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
3044 S.getLocStart());
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003045 TargetScope.addPrivate(
3046 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
3047 TargetScope.addPrivate(PVD,
3048 [&InputInfo]() { return InputInfo.PointersArray; });
3049 TargetScope.addPrivate(SVD,
3050 [&InputInfo]() { return InputInfo.SizesArray; });
3051 }
3052 (void)TargetScope.Privatize();
3053 // Build list of dependences.
3054 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
3055 for (auto *IRef : C->varlists())
3056 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
3057 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3058 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3059 // Set proper addresses for generated private copies.
3060 OMPPrivateScope Scope(CGF);
3061 if (!Data.FirstprivateVars.empty()) {
3062 enum { PrivatesParam = 2, CopyFnParam = 3 };
3063 auto *CopyFn = CGF.Builder.CreateLoad(
3064 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
3065 auto *PrivatesPtr = CGF.Builder.CreateLoad(
3066 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
3067 // Map privates.
3068 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3069 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3070 CallArgs.push_back(PrivatesPtr);
3071 for (auto *E : Data.FirstprivateVars) {
3072 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3073 Address PrivatePtr =
3074 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3075 ".firstpriv.ptr.addr");
3076 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
3077 CallArgs.push_back(PrivatePtr.getPointer());
3078 }
3079 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3080 CopyFn, CallArgs);
3081 for (auto &&Pair : PrivatePtrs) {
3082 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3083 CGF.getContext().getDeclAlign(Pair.first));
3084 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3085 }
3086 }
3087 // Privatize all private variables except for in_reduction items.
3088 (void)Scope.Privatize();
Alexey Bataev8451efa2018-01-15 19:06:12 +00003089 if (InputInfo.NumberOfTargetItems > 0) {
3090 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
3091 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0, CGF.getPointerSize());
3092 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
3093 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0, CGF.getPointerSize());
3094 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
3095 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0, CGF.getSizeSize());
3096 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003097
3098 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003099 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003100 BodyGen(CGF);
3101 };
3102 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
3103 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3104 Data.NumberOfParts);
3105 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3106 IntegerLiteral IfCond(getContext(), TrueOrFalse,
3107 getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3108 SourceLocation());
3109
3110 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getLocStart(), S, OutlinedFn,
3111 SharedsTy, CapturedStruct, &IfCond, Data);
3112}
3113
Alexey Bataev7292c292016-04-25 12:22:29 +00003114void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3115 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00003116 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
Alexey Bataev7292c292016-04-25 12:22:29 +00003117 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003118 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00003119 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00003120 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3121 if (C->getNameModifier() == OMPD_unknown ||
3122 C->getNameModifier() == OMPD_task) {
3123 IfCond = C->getCondition();
3124 break;
3125 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003126 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003127
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003128 OMPTaskDataTy Data;
3129 // Check if we should emit tied or untied task.
3130 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003131 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3132 CGF.EmitStmt(CS->getCapturedStmt());
3133 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003134 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00003135 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003136 const OMPTaskDataTy &Data) {
3137 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
3138 SharedsTy, CapturedStruct, IfCond,
3139 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003140 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003141 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003142}
3143
Alexey Bataev9f797f32015-02-05 05:57:51 +00003144void CodeGenFunction::EmitOMPTaskyieldDirective(
3145 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003146 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00003147}
3148
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003149void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00003150 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003151}
3152
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003153void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
3154 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00003155}
3156
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003157void CodeGenFunction::EmitOMPTaskgroupDirective(
3158 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003159 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3160 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003161 if (const Expr *E = S.getReductionRef()) {
3162 SmallVector<const Expr *, 4> LHSs;
3163 SmallVector<const Expr *, 4> RHSs;
3164 OMPTaskDataTy Data;
3165 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3166 auto IPriv = C->privates().begin();
3167 auto IRed = C->reduction_ops().begin();
3168 auto ILHS = C->lhs_exprs().begin();
3169 auto IRHS = C->rhs_exprs().begin();
3170 for (const auto *Ref : C->varlists()) {
3171 Data.ReductionVars.emplace_back(Ref);
3172 Data.ReductionCopies.emplace_back(*IPriv);
3173 Data.ReductionOps.emplace_back(*IRed);
3174 LHSs.emplace_back(*ILHS);
3175 RHSs.emplace_back(*IRHS);
3176 std::advance(IPriv, 1);
3177 std::advance(IRed, 1);
3178 std::advance(ILHS, 1);
3179 std::advance(IRHS, 1);
3180 }
3181 }
3182 llvm::Value *ReductionDesc =
3183 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getLocStart(),
3184 LHSs, RHSs, Data);
3185 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3186 CGF.EmitVarDecl(*VD);
3187 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3188 /*Volatile=*/false, E->getType());
3189 }
Alexey Bataev475a7442018-01-12 19:39:11 +00003190 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003191 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003192 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003193 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
3194}
3195
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003196void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003197 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003198 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003199 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3200 FlushClause->varlist_end());
3201 }
3202 return llvm::None;
3203 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00003204}
3205
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003206void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3207 const CodeGenLoopTy &CodeGenLoop,
3208 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003209 // Emit the loop iteration variable.
3210 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3211 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
3212 EmitVarDecl(*IVDecl);
3213
3214 // Emit the iterations count variable.
3215 // If it is not a variable, Sema decided to calculate iterations count on each
3216 // iteration (e.g., it is foldable into a constant).
3217 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3218 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3219 // Emit calculation of the iterations count.
3220 EmitIgnoredExpr(S.getCalcLastIteration());
3221 }
3222
3223 auto &RT = CGM.getOpenMPRuntime();
3224
Carlo Bertolli962bb802017-01-03 18:24:42 +00003225 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003226 // Check pre-condition.
3227 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003228 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003229 // Skip the entire loop if we don't meet the precondition.
3230 // If the condition constant folds and can be elided, avoid emitting the
3231 // whole loop.
3232 bool CondConstant;
3233 llvm::BasicBlock *ContBlock = nullptr;
3234 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3235 if (!CondConstant)
3236 return;
3237 } else {
3238 auto *ThenBlock = createBasicBlock("omp.precond.then");
3239 ContBlock = createBasicBlock("omp.precond.end");
3240 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3241 getProfileCount(&S));
3242 EmitBlock(ThenBlock);
3243 incrementProfileCounter(&S);
3244 }
3245
Alexey Bataev617db5f2017-12-04 15:38:33 +00003246 emitAlignedClause(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003247 // Emit 'then' code.
3248 {
3249 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003250
3251 LValue LB = EmitOMPHelperVar(
3252 *this, cast<DeclRefExpr>(
3253 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3254 ? S.getCombinedLowerBoundVariable()
3255 : S.getLowerBoundVariable())));
3256 LValue UB = EmitOMPHelperVar(
3257 *this, cast<DeclRefExpr>(
3258 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3259 ? S.getCombinedUpperBoundVariable()
3260 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003261 LValue ST =
3262 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3263 LValue IL =
3264 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3265
3266 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003267 if (EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003268 // Emit implicit barrier to synchronize threads and avoid data races
3269 // on initialization of firstprivate variables and post-update of
Carlo Bertolli962bb802017-01-03 18:24:42 +00003270 // lastprivate variables.
3271 CGM.getOpenMPRuntime().emitBarrierCall(
Alexey Bataev617db5f2017-12-04 15:38:33 +00003272 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3273 /*ForceSimpleCall=*/true);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003274 }
3275 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev617db5f2017-12-04 15:38:33 +00003276 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
Alexey Bataev999277a2017-12-06 14:31:09 +00003277 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3278 !isOpenMPTeamsDirective(S.getDirectiveKind()))
Alexey Bataev617db5f2017-12-04 15:38:33 +00003279 EmitOMPReductionClauseInit(S, LoopScope);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003280 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003281 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003282 (void)LoopScope.Privatize();
3283
3284 // Detect the distribute schedule kind and chunk.
3285 llvm::Value *Chunk = nullptr;
3286 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3287 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3288 ScheduleKind = C->getDistScheduleKind();
3289 if (const auto *Ch = C->getChunkSize()) {
3290 Chunk = EmitScalarExpr(Ch);
3291 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
Alexey Bataev617db5f2017-12-04 15:38:33 +00003292 S.getIterationVariable()->getType(),
3293 S.getLocStart());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003294 }
3295 }
3296 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3297 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3298
3299 // OpenMP [2.10.8, distribute Construct, Description]
3300 // If dist_schedule is specified, kind must be static. If specified,
3301 // iterations are divided into chunks of size chunk_size, chunks are
3302 // assigned to the teams of the league in a round-robin fashion in the
3303 // order of the team number. When no chunk_size is specified, the
3304 // iteration space is divided into chunks that are approximately equal
3305 // in size, and at most one chunk is distributed to each team of the
3306 // league. The size of the chunks is unspecified in this case.
3307 if (RT.isStaticNonchunked(ScheduleKind,
3308 /* Chunked */ Chunk != nullptr)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003309 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3310 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003311 CGOpenMPRuntime::StaticRTInput StaticInit(
3312 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3313 LB.getAddress(), UB.getAddress(), ST.getAddress());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003314 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003315 StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003316 auto LoopExit =
3317 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3318 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003319 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3320 ? S.getCombinedEnsureUpperBound()
3321 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003322 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003323 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3324 ? S.getCombinedInit()
3325 : S.getInit());
3326
3327 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3328 ? S.getCombinedCond()
3329 : S.getCond();
3330
3331 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003332 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003333 // when combined with 'for' (e.g. as in 'distribute parallel for')
3334 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3335 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3336 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3337 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003338 },
3339 [](CodeGenFunction &) {});
3340 EmitBlock(LoopExit.getBlock());
3341 // Tell the runtime we are done.
Alexey Bataevf43f7142017-09-06 16:17:35 +00003342 RT.emitForStaticFinish(*this, S.getLocStart(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003343 } else {
3344 // Emit the outer loop, which requests its work chunk [LB..UB] from
3345 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003346 const OMPLoopArguments LoopArguments = {
3347 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3348 Chunk};
3349 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3350 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003351 }
Alexey Bataev617db5f2017-12-04 15:38:33 +00003352 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3353 EmitOMPSimdFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3354 return CGF.Builder.CreateIsNotNull(
3355 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3356 });
3357 }
3358 OpenMPDirectiveKind ReductionKind = OMPD_unknown;
3359 if (isOpenMPParallelDirective(S.getDirectiveKind()) &&
3360 isOpenMPSimdDirective(S.getDirectiveKind())) {
3361 ReductionKind = OMPD_parallel_for_simd;
3362 } else if (isOpenMPParallelDirective(S.getDirectiveKind())) {
3363 ReductionKind = OMPD_parallel_for;
3364 } else if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3365 ReductionKind = OMPD_simd;
3366 } else if (!isOpenMPTeamsDirective(S.getDirectiveKind()) &&
3367 S.hasClausesOfKind<OMPReductionClause>()) {
3368 llvm_unreachable(
3369 "No reduction clauses is allowed in distribute directive.");
3370 }
3371 EmitOMPReductionClauseFinal(S, ReductionKind);
3372 // Emit post-update of the reduction variables if IsLastIter != 0.
3373 emitPostUpdateForReductionClause(
3374 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3375 return CGF.Builder.CreateIsNotNull(
3376 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3377 });
Carlo Bertolli962bb802017-01-03 18:24:42 +00003378 // Emit final copy of the lastprivate variables if IsLastIter != 0.
Alexey Bataev617db5f2017-12-04 15:38:33 +00003379 if (HasLastprivateClause) {
Carlo Bertolli962bb802017-01-03 18:24:42 +00003380 EmitOMPLastprivateClauseFinal(
3381 S, /*NoFinals=*/false,
Alexey Bataev617db5f2017-12-04 15:38:33 +00003382 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
3383 }
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003384 }
3385
3386 // We're now done with the loop, so jump to the continuation block.
3387 if (ContBlock) {
3388 EmitBranch(ContBlock);
3389 EmitBlock(ContBlock, true);
3390 }
3391 }
3392}
3393
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003394void CodeGenFunction::EmitOMPDistributeDirective(
3395 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003396 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003397
3398 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003399 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003400 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev10a54312017-11-27 16:54:08 +00003401 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003402}
3403
Alexey Bataev5f600d62015-09-29 03:48:57 +00003404static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3405 const CapturedStmt *S) {
3406 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3407 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3408 CGF.CapturedStmtInfo = &CapStmtInfo;
3409 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3410 Fn->addFnAttr(llvm::Attribute::NoInline);
3411 return Fn;
3412}
3413
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003414void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003415 if (S.hasClausesOfKind<OMPDependClause>()) {
3416 assert(!S.getAssociatedStmt() &&
3417 "No associated statement must be in ordered depend construct.");
Alexey Bataev8b427062016-05-25 12:36:08 +00003418 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3419 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003420 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003421 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003422 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003423 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3424 PrePostActionTy &Action) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003425 const CapturedStmt *CS = S.getInnermostCapturedStmt();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003426 if (C) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003427 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3428 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3429 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Alexey Bataev3c595a62017-08-14 15:01:03 +00003430 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3431 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003432 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003433 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003434 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev5f600d62015-09-29 03:48:57 +00003435 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003436 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003437 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003438 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003439}
3440
Alexey Bataevb57056f2015-01-22 06:17:56 +00003441static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003442 QualType SrcType, QualType DestType,
3443 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003444 assert(CGF.hasScalarEvaluationKind(DestType) &&
3445 "DestType must have scalar evaluation kind.");
3446 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3447 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003448 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3449 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00003450 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003451 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003452}
3453
3454static CodeGenFunction::ComplexPairTy
3455convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003456 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003457 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3458 "DestType must have complex evaluation kind.");
3459 CodeGenFunction::ComplexPairTy ComplexVal;
3460 if (Val.isScalar()) {
3461 // Convert the input element to the element type of the complex.
3462 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003463 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3464 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003465 ComplexVal = CodeGenFunction::ComplexPairTy(
3466 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3467 } else {
3468 assert(Val.isComplex() && "Must be a scalar or complex.");
3469 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3470 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3471 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003472 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003473 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003474 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003475 }
3476 return ComplexVal;
3477}
3478
Alexey Bataev5e018f92015-04-23 06:35:10 +00003479static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3480 LValue LVal, RValue RVal) {
3481 if (LVal.isGlobalReg()) {
3482 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3483 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003484 CGF.EmitAtomicStore(RVal, LVal,
3485 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3486 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003487 LVal.isVolatile(), /*IsInit=*/false);
3488 }
3489}
3490
Alexey Bataev8524d152016-01-21 12:35:58 +00003491void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3492 QualType RValTy, SourceLocation Loc) {
3493 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003494 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003495 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3496 *this, RVal, RValTy, LVal.getType(), Loc)),
3497 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003498 break;
3499 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003500 EmitStoreOfComplex(
3501 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003502 /*isInit=*/false);
3503 break;
3504 case TEK_Aggregate:
3505 llvm_unreachable("Must be a scalar or complex.");
3506 }
3507}
3508
Alexey Bataevb57056f2015-01-22 06:17:56 +00003509static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3510 const Expr *X, const Expr *V,
3511 SourceLocation Loc) {
3512 // v = x;
3513 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3514 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3515 LValue XLValue = CGF.EmitLValue(X);
3516 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003517 RValue Res = XLValue.isGlobalReg()
3518 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003519 : CGF.EmitAtomicLoad(
3520 XLValue, Loc,
3521 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3522 : llvm::AtomicOrdering::Monotonic,
3523 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003524 // OpenMP, 2.12.6, atomic Construct
3525 // Any atomic construct with a seq_cst clause forces the atomically
3526 // performed operation to include an implicit flush operation without a
3527 // list.
3528 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003529 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003530 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003531}
3532
Alexey Bataevb8329262015-02-27 06:33:30 +00003533static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3534 const Expr *X, const Expr *E,
3535 SourceLocation Loc) {
3536 // x = expr;
3537 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003538 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003539 // OpenMP, 2.12.6, atomic Construct
3540 // Any atomic construct with a seq_cst clause forces the atomically
3541 // performed operation to include an implicit flush operation without a
3542 // list.
3543 if (IsSeqCst)
3544 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3545}
3546
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003547static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3548 RValue Update,
3549 BinaryOperatorKind BO,
3550 llvm::AtomicOrdering AO,
3551 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003552 auto &Context = CGF.CGM.getContext();
3553 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003554 // expression is simple and atomic is allowed for the given type for the
3555 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003556 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003557 !Update.getScalarVal()->getType()->isIntegerTy() ||
3558 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3559 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003560 X.getAddress().getElementType())) ||
3561 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003562 !Context.getTargetInfo().hasBuiltinAtomic(
3563 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003564 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003565
3566 llvm::AtomicRMWInst::BinOp RMWOp;
3567 switch (BO) {
3568 case BO_Add:
3569 RMWOp = llvm::AtomicRMWInst::Add;
3570 break;
3571 case BO_Sub:
3572 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003573 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003574 RMWOp = llvm::AtomicRMWInst::Sub;
3575 break;
3576 case BO_And:
3577 RMWOp = llvm::AtomicRMWInst::And;
3578 break;
3579 case BO_Or:
3580 RMWOp = llvm::AtomicRMWInst::Or;
3581 break;
3582 case BO_Xor:
3583 RMWOp = llvm::AtomicRMWInst::Xor;
3584 break;
3585 case BO_LT:
3586 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3587 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3588 : llvm::AtomicRMWInst::Max)
3589 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3590 : llvm::AtomicRMWInst::UMax);
3591 break;
3592 case BO_GT:
3593 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3594 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3595 : llvm::AtomicRMWInst::Min)
3596 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3597 : llvm::AtomicRMWInst::UMin);
3598 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003599 case BO_Assign:
3600 RMWOp = llvm::AtomicRMWInst::Xchg;
3601 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003602 case BO_Mul:
3603 case BO_Div:
3604 case BO_Rem:
3605 case BO_Shl:
3606 case BO_Shr:
3607 case BO_LAnd:
3608 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003609 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003610 case BO_PtrMemD:
3611 case BO_PtrMemI:
3612 case BO_LE:
3613 case BO_GE:
3614 case BO_EQ:
3615 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00003616 case BO_Cmp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003617 case BO_AddAssign:
3618 case BO_SubAssign:
3619 case BO_AndAssign:
3620 case BO_OrAssign:
3621 case BO_XorAssign:
3622 case BO_MulAssign:
3623 case BO_DivAssign:
3624 case BO_RemAssign:
3625 case BO_ShlAssign:
3626 case BO_ShrAssign:
3627 case BO_Comma:
3628 llvm_unreachable("Unsupported atomic update operation");
3629 }
3630 auto *UpdateVal = Update.getScalarVal();
3631 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3632 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003633 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003634 X.getType()->hasSignedIntegerRepresentation());
3635 }
John McCall7f416cc2015-09-08 08:05:57 +00003636 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003637 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003638}
3639
Alexey Bataev5e018f92015-04-23 06:35:10 +00003640std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003641 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3642 llvm::AtomicOrdering AO, SourceLocation Loc,
3643 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3644 // Update expressions are allowed to have the following forms:
3645 // x binop= expr; -> xrval + expr;
3646 // x++, ++x -> xrval + 1;
3647 // x--, --x -> xrval - 1;
3648 // x = x binop expr; -> xrval binop expr
3649 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003650 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3651 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003652 if (X.isGlobalReg()) {
3653 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3654 // 'xrval'.
3655 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3656 } else {
3657 // Perform compare-and-swap procedure.
3658 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003659 }
3660 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003661 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003662}
3663
3664static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3665 const Expr *X, const Expr *E,
3666 const Expr *UE, bool IsXLHSInRHSPart,
3667 SourceLocation Loc) {
3668 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3669 "Update expr in 'atomic update' must be a binary operator.");
3670 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3671 // Update expressions are allowed to have the following forms:
3672 // x binop= expr; -> xrval + expr;
3673 // x++, ++x -> xrval + 1;
3674 // x--, --x -> xrval - 1;
3675 // x = x binop expr; -> xrval binop expr
3676 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003677 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003678 LValue XLValue = CGF.EmitLValue(X);
3679 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003680 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3681 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003682 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3683 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3684 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3685 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3686 auto Gen =
3687 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3688 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3689 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3690 return CGF.EmitAnyExpr(UE);
3691 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003692 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3693 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3694 // OpenMP, 2.12.6, atomic Construct
3695 // Any atomic construct with a seq_cst clause forces the atomically
3696 // performed operation to include an implicit flush operation without a
3697 // list.
3698 if (IsSeqCst)
3699 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3700}
3701
3702static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003703 QualType SourceType, QualType ResType,
3704 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003705 switch (CGF.getEvaluationKind(ResType)) {
3706 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003707 return RValue::get(
3708 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003709 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003710 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003711 return RValue::getComplex(Res.first, Res.second);
3712 }
3713 case TEK_Aggregate:
3714 break;
3715 }
3716 llvm_unreachable("Must be a scalar or complex.");
3717}
3718
3719static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3720 bool IsPostfixUpdate, const Expr *V,
3721 const Expr *X, const Expr *E,
3722 const Expr *UE, bool IsXLHSInRHSPart,
3723 SourceLocation Loc) {
3724 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3725 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3726 RValue NewVVal;
3727 LValue VLValue = CGF.EmitLValue(V);
3728 LValue XLValue = CGF.EmitLValue(X);
3729 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003730 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3731 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003732 QualType NewVValType;
3733 if (UE) {
3734 // 'x' is updated with some additional value.
3735 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3736 "Update expr in 'atomic capture' must be a binary operator.");
3737 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3738 // Update expressions are allowed to have the following forms:
3739 // x binop= expr; -> xrval + expr;
3740 // x++, ++x -> xrval + 1;
3741 // x--, --x -> xrval - 1;
3742 // x = x binop expr; -> xrval binop expr
3743 // x = expr Op x; - > expr binop xrval;
3744 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3745 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3746 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3747 NewVValType = XRValExpr->getType();
3748 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3749 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003750 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003751 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3752 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3753 RValue Res = CGF.EmitAnyExpr(UE);
3754 NewVVal = IsPostfixUpdate ? XRValue : Res;
3755 return Res;
3756 };
3757 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3758 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3759 if (Res.first) {
3760 // 'atomicrmw' instruction was generated.
3761 if (IsPostfixUpdate) {
3762 // Use old value from 'atomicrmw'.
3763 NewVVal = Res.second;
3764 } else {
3765 // 'atomicrmw' does not provide new value, so evaluate it using old
3766 // value of 'x'.
3767 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3768 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3769 NewVVal = CGF.EmitAnyExpr(UE);
3770 }
3771 }
3772 } else {
3773 // 'x' is simply rewritten with some 'expr'.
3774 NewVValType = X->getType().getNonReferenceType();
3775 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003776 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003777 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003778 NewVVal = XRValue;
3779 return ExprRValue;
3780 };
3781 // Try to perform atomicrmw xchg, otherwise simple exchange.
3782 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3783 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3784 Loc, Gen);
3785 if (Res.first) {
3786 // 'atomicrmw' instruction was generated.
3787 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3788 }
3789 }
3790 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003791 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003792 // OpenMP, 2.12.6, atomic Construct
3793 // Any atomic construct with a seq_cst clause forces the atomically
3794 // performed operation to include an implicit flush operation without a
3795 // list.
3796 if (IsSeqCst)
3797 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3798}
3799
Alexey Bataevb57056f2015-01-22 06:17:56 +00003800static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003801 bool IsSeqCst, bool IsPostfixUpdate,
3802 const Expr *X, const Expr *V, const Expr *E,
3803 const Expr *UE, bool IsXLHSInRHSPart,
3804 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003805 switch (Kind) {
3806 case OMPC_read:
3807 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3808 break;
3809 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003810 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3811 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003812 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003813 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003814 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3815 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003816 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003817 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3818 IsXLHSInRHSPart, Loc);
3819 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003820 case OMPC_if:
3821 case OMPC_final:
3822 case OMPC_num_threads:
3823 case OMPC_private:
3824 case OMPC_firstprivate:
3825 case OMPC_lastprivate:
3826 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003827 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003828 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003829 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003830 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003831 case OMPC_collapse:
3832 case OMPC_default:
3833 case OMPC_seq_cst:
3834 case OMPC_shared:
3835 case OMPC_linear:
3836 case OMPC_aligned:
3837 case OMPC_copyin:
3838 case OMPC_copyprivate:
3839 case OMPC_flush:
3840 case OMPC_proc_bind:
3841 case OMPC_schedule:
3842 case OMPC_ordered:
3843 case OMPC_nowait:
3844 case OMPC_untied:
3845 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003846 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003847 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003848 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003849 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003850 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003851 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003852 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003853 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003854 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003855 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003856 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003857 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003858 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003859 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003860 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003861 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003862 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003863 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003864 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003865 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003866 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3867 }
3868}
3869
3870void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003871 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003872 OpenMPClauseKind Kind = OMPC_unknown;
3873 for (auto *C : S.clauses()) {
3874 // Find first clause (skip seq_cst clause, if it is first).
3875 if (C->getClauseKind() != OMPC_seq_cst) {
3876 Kind = C->getClauseKind();
3877 break;
3878 }
3879 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003880
Alexey Bataev475a7442018-01-12 19:39:11 +00003881 const auto *CS = S.getInnermostCapturedStmt()->IgnoreContainers();
Alexey Bataev5e018f92015-04-23 06:35:10 +00003882 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003883 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003884 }
3885 // Processing for statements under 'atomic capture'.
3886 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3887 for (const auto *C : Compound->body()) {
3888 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3889 enterFullExpression(EWC);
3890 }
3891 }
3892 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003893
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003894 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3895 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003896 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003897 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3898 S.getV(), S.getExpr(), S.getUpdateExpr(),
3899 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003900 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003901 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003902 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003903}
3904
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003905static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3906 const OMPExecutableDirective &S,
3907 const RegionCodeGenTy &CodeGen) {
3908 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3909 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00003910
Samuel Antaoee8fb302016-01-06 13:42:12 +00003911 llvm::Function *Fn = nullptr;
3912 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003913
Samuel Antaobed3c462015-10-02 16:14:20 +00003914 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003915 // Check for the at most one if clause associated with the target region.
3916 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3917 if (C->getNameModifier() == OMPD_unknown ||
3918 C->getNameModifier() == OMPD_target) {
3919 IfCond = C->getCondition();
3920 break;
3921 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003922 }
3923
3924 // Check if we have any device clause associated with the directive.
3925 const Expr *Device = nullptr;
3926 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3927 Device = C->getDevice();
3928 }
3929
Samuel Antaoee8fb302016-01-06 13:42:12 +00003930 // Check if we have an if clause whose conditional always evaluates to false
3931 // or if we do not have any targets specified. If so the target region is not
3932 // an offload entry point.
3933 bool IsOffloadEntry = true;
3934 if (IfCond) {
3935 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003936 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003937 IsOffloadEntry = false;
3938 }
3939 if (CGM.getLangOpts().OMPTargetTriples.empty())
3940 IsOffloadEntry = false;
3941
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003942 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003943 StringRef ParentName;
3944 // In case we have Ctors/Dtors we use the complete type variant to produce
3945 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003946 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003947 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003948 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003949 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3950 else
3951 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003952 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003953
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003954 // Emit target region as a standalone region.
3955 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3956 IsOffloadEntry, CodeGen);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003957 OMPLexicalScope Scope(CGF, S, OMPD_task);
3958 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003959}
3960
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003961static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3962 PrePostActionTy &Action) {
3963 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3964 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3965 CGF.EmitOMPPrivateClause(S, PrivateScope);
3966 (void)PrivateScope.Privatize();
3967
3968 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003969 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003970}
3971
3972void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3973 StringRef ParentName,
3974 const OMPTargetDirective &S) {
3975 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3976 emitTargetRegion(CGF, S, Action);
3977 };
3978 llvm::Function *Fn;
3979 llvm::Constant *Addr;
3980 // Emit target region as a standalone region.
3981 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3982 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3983 assert(Fn && Addr && "Target device function emission failed.");
3984}
3985
3986void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3987 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3988 emitTargetRegion(CGF, S, Action);
3989 };
3990 emitCommonOMPTargetDirective(*this, S, CodeGen);
3991}
3992
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003993static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3994 const OMPExecutableDirective &S,
3995 OpenMPDirectiveKind InnermostKind,
3996 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003997 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
3998 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
3999 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004000
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004001 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
4002 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004003 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00004004 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
4005 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004006
Carlo Bertollic6872252016-04-04 15:55:02 +00004007 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
4008 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004009 }
4010
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004011 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004012 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4013 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004014 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
4015 CapturedVars);
4016}
4017
4018void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00004019 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004020 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004021 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00004022 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4023 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004024 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004025 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00004026 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004027 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004028 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00004029 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004030 emitPostUpdateForReductionClause(
4031 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00004032}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004033
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004034static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4035 const OMPTargetTeamsDirective &S) {
4036 auto *CS = S.getCapturedStmt(OMPD_teams);
4037 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004038 // Emit teams region as a standalone region.
4039 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
4040 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4041 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4042 CGF.EmitOMPPrivateClause(S, PrivateScope);
4043 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4044 (void)PrivateScope.Privatize();
4045 Action.Enter(CGF);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004046 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004047 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004048 };
4049 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004050 emitPostUpdateForReductionClause(
4051 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004052}
4053
4054void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4055 CodeGenModule &CGM, StringRef ParentName,
4056 const OMPTargetTeamsDirective &S) {
4057 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4058 emitTargetTeamsRegion(CGF, Action, S);
4059 };
4060 llvm::Function *Fn;
4061 llvm::Constant *Addr;
4062 // Emit target region as a standalone region.
4063 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4064 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4065 assert(Fn && Addr && "Target device function emission failed.");
4066}
4067
4068void CodeGenFunction::EmitOMPTargetTeamsDirective(
4069 const OMPTargetTeamsDirective &S) {
4070 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4071 emitTargetTeamsRegion(CGF, Action, S);
4072 };
4073 emitCommonOMPTargetDirective(*this, S, CodeGen);
4074}
4075
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004076static void
4077emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4078 const OMPTargetTeamsDistributeDirective &S) {
4079 Action.Enter(CGF);
4080 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4081 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4082 };
4083
4084 // Emit teams region as a standalone region.
4085 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4086 PrePostActionTy &) {
4087 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4088 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4089 (void)PrivateScope.Privatize();
4090 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4091 CodeGenDistribute);
4092 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4093 };
4094 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4095 emitPostUpdateForReductionClause(CGF, S,
4096 [](CodeGenFunction &) { return nullptr; });
4097}
4098
4099void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4100 CodeGenModule &CGM, StringRef ParentName,
4101 const OMPTargetTeamsDistributeDirective &S) {
4102 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4103 emitTargetTeamsDistributeRegion(CGF, Action, S);
4104 };
4105 llvm::Function *Fn;
4106 llvm::Constant *Addr;
4107 // Emit target region as a standalone region.
4108 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4109 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4110 assert(Fn && Addr && "Target device function emission failed.");
4111}
4112
4113void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4114 const OMPTargetTeamsDistributeDirective &S) {
4115 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4116 emitTargetTeamsDistributeRegion(CGF, Action, S);
4117 };
4118 emitCommonOMPTargetDirective(*this, S, CodeGen);
4119}
4120
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004121static void emitTargetTeamsDistributeSimdRegion(
4122 CodeGenFunction &CGF, PrePostActionTy &Action,
4123 const OMPTargetTeamsDistributeSimdDirective &S) {
4124 Action.Enter(CGF);
4125 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4126 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4127 };
4128
4129 // Emit teams region as a standalone region.
4130 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4131 PrePostActionTy &) {
4132 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4133 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4134 (void)PrivateScope.Privatize();
4135 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4136 CodeGenDistribute);
4137 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4138 };
4139 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4140 emitPostUpdateForReductionClause(CGF, S,
4141 [](CodeGenFunction &) { return nullptr; });
4142}
4143
4144void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4145 CodeGenModule &CGM, StringRef ParentName,
4146 const OMPTargetTeamsDistributeSimdDirective &S) {
4147 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4148 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4149 };
4150 llvm::Function *Fn;
4151 llvm::Constant *Addr;
4152 // Emit target region as a standalone region.
4153 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4154 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4155 assert(Fn && Addr && "Target device function emission failed.");
4156}
4157
4158void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4159 const OMPTargetTeamsDistributeSimdDirective &S) {
4160 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4161 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4162 };
4163 emitCommonOMPTargetDirective(*this, S, CodeGen);
4164}
4165
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004166void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4167 const OMPTeamsDistributeDirective &S) {
4168
4169 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4170 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4171 };
4172
4173 // Emit teams region as a standalone region.
4174 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4175 PrePostActionTy &) {
4176 OMPPrivateScope PrivateScope(CGF);
4177 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4178 (void)PrivateScope.Privatize();
4179 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4180 CodeGenDistribute);
4181 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4182 };
Alexey Bataev95c6dd42017-11-29 15:14:16 +00004183 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004184 emitPostUpdateForReductionClause(*this, S,
4185 [](CodeGenFunction &) { return nullptr; });
4186}
4187
Alexey Bataev999277a2017-12-06 14:31:09 +00004188void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4189 const OMPTeamsDistributeSimdDirective &S) {
4190 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4191 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4192 };
4193
4194 // Emit teams region as a standalone region.
4195 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4196 PrePostActionTy &) {
4197 OMPPrivateScope PrivateScope(CGF);
4198 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4199 (void)PrivateScope.Privatize();
4200 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4201 CodeGenDistribute);
4202 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4203 };
4204 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4205 emitPostUpdateForReductionClause(*this, S,
4206 [](CodeGenFunction &) { return nullptr; });
4207}
4208
Carlo Bertolli62fae152017-11-20 20:46:39 +00004209void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4210 const OMPTeamsDistributeParallelForDirective &S) {
4211 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4212 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4213 S.getDistInc());
4214 };
4215
4216 // Emit teams region as a standalone region.
4217 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4218 PrePostActionTy &) {
4219 OMPPrivateScope PrivateScope(CGF);
4220 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4221 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00004222 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4223 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004224 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4225 };
4226 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4227 emitPostUpdateForReductionClause(*this, S,
4228 [](CodeGenFunction &) { return nullptr; });
4229}
4230
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004231void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4232 const OMPTeamsDistributeParallelForSimdDirective &S) {
4233 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4234 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4235 S.getDistInc());
4236 };
4237
4238 // Emit teams region as a standalone region.
4239 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4240 PrePostActionTy &) {
4241 OMPPrivateScope PrivateScope(CGF);
4242 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4243 (void)PrivateScope.Privatize();
4244 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4245 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4246 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4247 };
4248 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4249 emitPostUpdateForReductionClause(*this, S,
4250 [](CodeGenFunction &) { return nullptr; });
4251}
4252
Carlo Bertolli52978c32018-01-03 21:12:44 +00004253static void emitTargetTeamsDistributeParallelForRegion(
4254 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
4255 PrePostActionTy &Action) {
4256 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4257 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4258 S.getDistInc());
4259 };
4260
4261 // Emit teams region as a standalone region.
4262 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4263 PrePostActionTy &) {
4264 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4265 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4266 (void)PrivateScope.Privatize();
4267 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4268 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4269 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4270 };
4271
4272 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
4273 CodeGenTeams);
4274 emitPostUpdateForReductionClause(CGF, S,
4275 [](CodeGenFunction &) { return nullptr; });
4276}
4277
4278void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
4279 CodeGenModule &CGM, StringRef ParentName,
4280 const OMPTargetTeamsDistributeParallelForDirective &S) {
4281 // Emit SPMD target teams distribute parallel for region as a standalone
4282 // region.
4283 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4284 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4285 };
4286 llvm::Function *Fn;
4287 llvm::Constant *Addr;
4288 // Emit target region as a standalone region.
4289 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4290 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4291 assert(Fn && Addr && "Target device function emission failed.");
4292}
4293
4294void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
4295 const OMPTargetTeamsDistributeParallelForDirective &S) {
4296 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4297 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4298 };
4299 emitCommonOMPTargetDirective(*this, S, CodeGen);
4300}
4301
Alexey Bataev647dd842018-01-15 20:59:40 +00004302static void emitTargetTeamsDistributeParallelForSimdRegion(
4303 CodeGenFunction &CGF,
4304 const OMPTargetTeamsDistributeParallelForSimdDirective &S,
4305 PrePostActionTy &Action) {
4306 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4307 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4308 S.getDistInc());
4309 };
4310
4311 // Emit teams region as a standalone region.
4312 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4313 PrePostActionTy &) {
4314 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4315 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4316 (void)PrivateScope.Privatize();
4317 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4318 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4319 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4320 };
4321
4322 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
4323 CodeGenTeams);
4324 emitPostUpdateForReductionClause(CGF, S,
4325 [](CodeGenFunction &) { return nullptr; });
4326}
4327
4328void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
4329 CodeGenModule &CGM, StringRef ParentName,
4330 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4331 // Emit SPMD target teams distribute parallel for simd region as a standalone
4332 // region.
4333 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4334 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4335 };
4336 llvm::Function *Fn;
4337 llvm::Constant *Addr;
4338 // Emit target region as a standalone region.
4339 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4340 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4341 assert(Fn && Addr && "Target device function emission failed.");
4342}
4343
4344void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
4345 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4346 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4347 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4348 };
4349 emitCommonOMPTargetDirective(*this, S, CodeGen);
4350}
4351
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004352void CodeGenFunction::EmitOMPCancellationPointDirective(
4353 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00004354 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
4355 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004356}
4357
Alexey Bataev80909872015-07-02 11:25:17 +00004358void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004359 const Expr *IfCond = nullptr;
4360 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4361 if (C->getNameModifier() == OMPD_unknown ||
4362 C->getNameModifier() == OMPD_cancel) {
4363 IfCond = C->getCondition();
4364 break;
4365 }
4366 }
4367 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004368 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00004369}
4370
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004371CodeGenFunction::JumpDest
4372CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00004373 if (Kind == OMPD_parallel || Kind == OMPD_task ||
4374 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004375 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004376 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00004377 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
4378 Kind == OMPD_distribute_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004379 Kind == OMPD_target_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004380 Kind == OMPD_teams_distribute_parallel_for ||
4381 Kind == OMPD_target_teams_distribute_parallel_for);
Alexey Bataev957d8562016-11-17 15:12:05 +00004382 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004383}
Michael Wong65f367f2015-07-21 13:44:28 +00004384
Samuel Antaocc10b852016-07-28 14:23:26 +00004385void CodeGenFunction::EmitOMPUseDevicePtrClause(
4386 const OMPClause &NC, OMPPrivateScope &PrivateScope,
4387 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
4388 const auto &C = cast<OMPUseDevicePtrClause>(NC);
4389 auto OrigVarIt = C.varlist_begin();
4390 auto InitIt = C.inits().begin();
4391 for (auto PvtVarIt : C.private_copies()) {
4392 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
4393 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
4394 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
4395
4396 // In order to identify the right initializer we need to match the
4397 // declaration used by the mapping logic. In some cases we may get
4398 // OMPCapturedExprDecl that refers to the original declaration.
4399 const ValueDecl *MatchingVD = OrigVD;
4400 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
4401 // OMPCapturedExprDecl are used to privative fields of the current
4402 // structure.
4403 auto *ME = cast<MemberExpr>(OED->getInit());
4404 assert(isa<CXXThisExpr>(ME->getBase()) &&
4405 "Base should be the current struct!");
4406 MatchingVD = ME->getMemberDecl();
4407 }
4408
4409 // If we don't have information about the current list item, move on to
4410 // the next one.
4411 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
4412 if (InitAddrIt == CaptureDeviceAddrMap.end())
4413 continue;
4414
4415 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
4416 // Initialize the temporary initialization variable with the address we
4417 // get from the runtime library. We have to cast the source address
4418 // because it is always a void *. References are materialized in the
4419 // privatization scope, so the initialization here disregards the fact
4420 // the original variable is a reference.
4421 QualType AddrQTy =
4422 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
4423 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
4424 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
4425 setAddrOfLocalVar(InitVD, InitAddr);
4426
4427 // Emit private declaration, it will be initialized by the value we
4428 // declaration we just added to the local declarations map.
4429 EmitDecl(*PvtVD);
4430
4431 // The initialization variables reached its purpose in the emission
4432 // ofthe previous declaration, so we don't need it anymore.
4433 LocalDeclMap.erase(InitVD);
4434
4435 // Return the address of the private variable.
4436 return GetAddrOfLocalVar(PvtVD);
4437 });
4438 assert(IsRegistered && "firstprivate var already registered as private");
4439 // Silence the warning about unused variable.
4440 (void)IsRegistered;
4441
4442 ++OrigVarIt;
4443 ++InitIt;
4444 }
4445}
4446
Michael Wong65f367f2015-07-21 13:44:28 +00004447// Generate the instructions for '#pragma omp target data' directive.
4448void CodeGenFunction::EmitOMPTargetDataDirective(
4449 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004450 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4451
4452 // Create a pre/post action to signal the privatization of the device pointer.
4453 // This action can be replaced by the OpenMP runtime code generation to
4454 // deactivate privatization.
4455 bool PrivatizeDevicePointers = false;
4456 class DevicePointerPrivActionTy : public PrePostActionTy {
4457 bool &PrivatizeDevicePointers;
4458
4459 public:
4460 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4461 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4462 void Enter(CodeGenFunction &CGF) override {
4463 PrivatizeDevicePointers = true;
4464 }
Samuel Antaodf158d52016-04-27 22:58:19 +00004465 };
Samuel Antaocc10b852016-07-28 14:23:26 +00004466 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4467
4468 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
Alexey Bataev475a7442018-01-12 19:39:11 +00004469 CodeGenFunction &CGF, PrePostActionTy &Action) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004470 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00004471 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Samuel Antaocc10b852016-07-28 14:23:26 +00004472 };
4473
4474 // Codegen that selects wheather to generate the privatization code or not.
4475 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4476 &InnermostCodeGen](CodeGenFunction &CGF,
4477 PrePostActionTy &Action) {
4478 RegionCodeGenTy RCG(InnermostCodeGen);
4479 PrivatizeDevicePointers = false;
4480
4481 // Call the pre-action to change the status of PrivatizeDevicePointers if
4482 // needed.
4483 Action.Enter(CGF);
4484
4485 if (PrivatizeDevicePointers) {
4486 OMPPrivateScope PrivateScope(CGF);
4487 // Emit all instances of the use_device_ptr clause.
4488 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4489 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4490 Info.CaptureDeviceAddrMap);
4491 (void)PrivateScope.Privatize();
4492 RCG(CGF);
4493 } else
4494 RCG(CGF);
4495 };
4496
4497 // Forward the provided action to the privatization codegen.
4498 RegionCodeGenTy PrivRCG(PrivCodeGen);
4499 PrivRCG.setAction(Action);
4500
4501 // Notwithstanding the body of the region is emitted as inlined directive,
4502 // we don't use an inline scope as changes in the references inside the
4503 // region are expected to be visible outside, so we do not privative them.
4504 OMPLexicalScope Scope(CGF, S);
4505 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4506 PrivRCG);
4507 };
4508
4509 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004510
4511 // If we don't have target devices, don't bother emitting the data mapping
4512 // code.
4513 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004514 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004515 return;
4516 }
4517
4518 // Check if we have any if clause associated with the directive.
4519 const Expr *IfCond = nullptr;
4520 if (auto *C = S.getSingleClause<OMPIfClause>())
4521 IfCond = C->getCondition();
4522
4523 // Check if we have any device clause associated with the directive.
4524 const Expr *Device = nullptr;
4525 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4526 Device = C->getDevice();
4527
Samuel Antaocc10b852016-07-28 14:23:26 +00004528 // Set the action to signal privatization of device pointers.
4529 RCG.setAction(PrivAction);
4530
4531 // Emit region code.
4532 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4533 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004534}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004535
Samuel Antaodf67fc42016-01-19 19:15:56 +00004536void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4537 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004538 // If we don't have target devices, don't bother emitting the data mapping
4539 // code.
4540 if (CGM.getLangOpts().OMPTargetTriples.empty())
4541 return;
4542
4543 // Check if we have any if clause associated with the directive.
4544 const Expr *IfCond = nullptr;
4545 if (auto *C = S.getSingleClause<OMPIfClause>())
4546 IfCond = C->getCondition();
4547
4548 // Check if we have any device clause associated with the directive.
4549 const Expr *Device = nullptr;
4550 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4551 Device = C->getDevice();
4552
Alexey Bataev475a7442018-01-12 19:39:11 +00004553 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004554 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004555}
4556
Samuel Antao72590762016-01-19 20:04:50 +00004557void CodeGenFunction::EmitOMPTargetExitDataDirective(
4558 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004559 // If we don't have target devices, don't bother emitting the data mapping
4560 // code.
4561 if (CGM.getLangOpts().OMPTargetTriples.empty())
4562 return;
4563
4564 // Check if we have any if clause associated with the directive.
4565 const Expr *IfCond = nullptr;
4566 if (auto *C = S.getSingleClause<OMPIfClause>())
4567 IfCond = C->getCondition();
4568
4569 // Check if we have any device clause associated with the directive.
4570 const Expr *Device = nullptr;
4571 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4572 Device = C->getDevice();
4573
Alexey Bataev475a7442018-01-12 19:39:11 +00004574 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004575 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004576}
4577
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004578static void emitTargetParallelRegion(CodeGenFunction &CGF,
4579 const OMPTargetParallelDirective &S,
4580 PrePostActionTy &Action) {
4581 // Get the captured statement associated with the 'parallel' region.
4582 auto *CS = S.getCapturedStmt(OMPD_parallel);
4583 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004584 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
4585 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4586 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4587 CGF.EmitOMPPrivateClause(S, PrivateScope);
4588 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4589 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004590 // TODO: Add support for clauses.
4591 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004592 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004593 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004594 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4595 emitEmptyBoundParameters);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004596 emitPostUpdateForReductionClause(
4597 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004598}
4599
4600void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4601 CodeGenModule &CGM, StringRef ParentName,
4602 const OMPTargetParallelDirective &S) {
4603 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4604 emitTargetParallelRegion(CGF, S, Action);
4605 };
4606 llvm::Function *Fn;
4607 llvm::Constant *Addr;
4608 // Emit target region as a standalone region.
4609 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4610 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4611 assert(Fn && Addr && "Target device function emission failed.");
4612}
4613
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004614void CodeGenFunction::EmitOMPTargetParallelDirective(
4615 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004616 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4617 emitTargetParallelRegion(CGF, S, Action);
4618 };
4619 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004620}
4621
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004622static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4623 const OMPTargetParallelForDirective &S,
4624 PrePostActionTy &Action) {
4625 Action.Enter(CGF);
4626 // Emit directive as a combined directive that consists of two implicit
4627 // directives: 'parallel' with 'for' directive.
4628 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev2139ed62017-11-16 18:20:21 +00004629 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4630 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004631 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4632 emitDispatchForLoopBounds);
4633 };
4634 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4635 emitEmptyBoundParameters);
4636}
4637
4638void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4639 CodeGenModule &CGM, StringRef ParentName,
4640 const OMPTargetParallelForDirective &S) {
4641 // Emit SPMD target parallel for region as a standalone region.
4642 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4643 emitTargetParallelForRegion(CGF, S, Action);
4644 };
4645 llvm::Function *Fn;
4646 llvm::Constant *Addr;
4647 // Emit target region as a standalone region.
4648 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4649 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4650 assert(Fn && Addr && "Target device function emission failed.");
4651}
4652
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004653void CodeGenFunction::EmitOMPTargetParallelForDirective(
4654 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004655 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4656 emitTargetParallelForRegion(CGF, S, Action);
4657 };
4658 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004659}
4660
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004661static void
4662emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4663 const OMPTargetParallelForSimdDirective &S,
4664 PrePostActionTy &Action) {
4665 Action.Enter(CGF);
4666 // Emit directive as a combined directive that consists of two implicit
4667 // directives: 'parallel' with 'for' directive.
4668 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4669 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4670 emitDispatchForLoopBounds);
4671 };
4672 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4673 emitEmptyBoundParameters);
4674}
4675
4676void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4677 CodeGenModule &CGM, StringRef ParentName,
4678 const OMPTargetParallelForSimdDirective &S) {
4679 // Emit SPMD target parallel for region as a standalone region.
4680 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4681 emitTargetParallelForSimdRegion(CGF, S, Action);
4682 };
4683 llvm::Function *Fn;
4684 llvm::Constant *Addr;
4685 // Emit target region as a standalone region.
4686 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4687 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4688 assert(Fn && Addr && "Target device function emission failed.");
4689}
4690
4691void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4692 const OMPTargetParallelForSimdDirective &S) {
4693 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4694 emitTargetParallelForSimdRegion(CGF, S, Action);
4695 };
4696 emitCommonOMPTargetDirective(*this, S, CodeGen);
4697}
4698
Alexey Bataev7292c292016-04-25 12:22:29 +00004699/// Emit a helper variable and return corresponding lvalue.
4700static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4701 const ImplicitParamDecl *PVD,
4702 CodeGenFunction::OMPPrivateScope &Privates) {
4703 auto *VDecl = cast<VarDecl>(Helper->getDecl());
4704 Privates.addPrivate(
4705 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
4706}
4707
4708void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4709 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4710 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00004711 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
Alexey Bataev7292c292016-04-25 12:22:29 +00004712 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
4713 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4714 const Expr *IfCond = nullptr;
4715 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4716 if (C->getNameModifier() == OMPD_unknown ||
4717 C->getNameModifier() == OMPD_taskloop) {
4718 IfCond = C->getCondition();
4719 break;
4720 }
4721 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004722
4723 OMPTaskDataTy Data;
4724 // Check if taskloop must be emitted without taskgroup.
4725 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004726 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004727 Data.Tied = true;
4728 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004729 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4730 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004731 Data.Schedule.setInt(/*IntVal=*/false);
4732 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004733 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4734 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004735 Data.Schedule.setInt(/*IntVal=*/true);
4736 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004737 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004738
4739 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4740 // if (PreCond) {
4741 // for (IV in 0..LastIteration) BODY;
4742 // <Final counter/linear vars updates>;
4743 // }
4744 //
4745
4746 // Emit: if (PreCond) - begin.
4747 // If the condition constant folds and can be elided, avoid emitting the
4748 // whole loop.
4749 bool CondConstant;
4750 llvm::BasicBlock *ContBlock = nullptr;
4751 OMPLoopScope PreInitScope(CGF, S);
4752 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4753 if (!CondConstant)
4754 return;
4755 } else {
4756 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4757 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4758 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4759 CGF.getProfileCount(&S));
4760 CGF.EmitBlock(ThenBlock);
4761 CGF.incrementProfileCounter(&S);
4762 }
4763
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004764 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4765 CGF.EmitOMPSimdInit(S);
4766
Alexey Bataev7292c292016-04-25 12:22:29 +00004767 OMPPrivateScope LoopScope(CGF);
4768 // Emit helper vars inits.
4769 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4770 auto *I = CS->getCapturedDecl()->param_begin();
4771 auto *LBP = std::next(I, LowerBound);
4772 auto *UBP = std::next(I, UpperBound);
4773 auto *STP = std::next(I, Stride);
4774 auto *LIP = std::next(I, LastIter);
4775 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4776 LoopScope);
4777 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4778 LoopScope);
4779 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4780 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4781 LoopScope);
4782 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004783 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004784 (void)LoopScope.Privatize();
4785 // Emit the loop iteration variable.
4786 const Expr *IVExpr = S.getIterationVariable();
4787 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4788 CGF.EmitVarDecl(*IVDecl);
4789 CGF.EmitIgnoredExpr(S.getInit());
4790
4791 // Emit the iterations count variable.
4792 // If it is not a variable, Sema decided to calculate iterations count on
4793 // each iteration (e.g., it is foldable into a constant).
4794 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4795 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4796 // Emit calculation of the iterations count.
4797 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4798 }
4799
4800 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4801 S.getInc(),
4802 [&S](CodeGenFunction &CGF) {
4803 CGF.EmitOMPLoopBody(S, JumpDest());
4804 CGF.EmitStopPoint(&S);
4805 },
4806 [](CodeGenFunction &) {});
4807 // Emit: if (PreCond) - end.
4808 if (ContBlock) {
4809 CGF.EmitBranch(ContBlock);
4810 CGF.EmitBlock(ContBlock, true);
4811 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004812 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4813 if (HasLastprivateClause) {
4814 CGF.EmitOMPLastprivateClauseFinal(
4815 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4816 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4817 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4818 (*LIP)->getType(), S.getLocStart())));
4819 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004820 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004821 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4822 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4823 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004824 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4825 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004826 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4827 OutlinedFn, SharedsTy,
4828 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004829 };
4830 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4831 CodeGen);
4832 };
Alexey Bataev475a7442018-01-12 19:39:11 +00004833 if (Data.Nogroup) {
4834 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
4835 } else {
Alexey Bataev33446032017-07-12 18:09:32 +00004836 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4837 *this,
4838 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4839 PrePostActionTy &Action) {
4840 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00004841 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
4842 Data);
Alexey Bataev33446032017-07-12 18:09:32 +00004843 },
4844 S.getLocStart());
4845 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004846}
4847
Alexey Bataev49f6e782015-12-01 04:18:41 +00004848void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004849 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004850}
4851
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004852void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4853 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004854 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004855}
Samuel Antao686c70c2016-05-26 17:30:50 +00004856
4857// Generate the instructions for '#pragma omp target update' directive.
4858void CodeGenFunction::EmitOMPTargetUpdateDirective(
4859 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00004860 // If we don't have target devices, don't bother emitting the data mapping
4861 // code.
4862 if (CGM.getLangOpts().OMPTargetTriples.empty())
4863 return;
4864
4865 // Check if we have any if clause associated with the directive.
4866 const Expr *IfCond = nullptr;
4867 if (auto *C = S.getSingleClause<OMPIfClause>())
4868 IfCond = C->getCondition();
4869
4870 // Check if we have any device clause associated with the directive.
4871 const Expr *Device = nullptr;
4872 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4873 Device = C->getDevice();
4874
Alexey Bataev475a7442018-01-12 19:39:11 +00004875 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004876 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00004877}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00004878
4879void CodeGenFunction::EmitSimpleOMPExecutableDirective(
4880 const OMPExecutableDirective &D) {
4881 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
4882 return;
4883 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
4884 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
4885 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
4886 } else {
4887 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
4888 for (const auto *E : LD->counters()) {
4889 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
4890 cast<DeclRefExpr>(E)->getDecl())) {
4891 // Emit only those that were not explicitly referenced in clauses.
4892 if (!CGF.LocalDeclMap.count(VD))
4893 CGF.EmitVarDecl(*VD);
4894 }
4895 }
4896 }
Alexey Bataev475a7442018-01-12 19:39:11 +00004897 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00004898 }
4899 };
4900 OMPSimdLexicalScope Scope(*this, D);
4901 CGM.getOpenMPRuntime().emitInlinedDirective(
4902 *this,
4903 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
4904 : D.getDirectiveKind(),
4905 CodeGen);
4906}