blob: d7fb588f36eee289ba9b941b294d801e5c78b89d [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)),
78 VD->getType().getNonReferenceType(), VK_LValue, SourceLocation());
79 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,
199 SourceLocation());
200 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()) {
268 llvm::Value *CV =
269 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal();
270
271 // If the field is not a pointer, we need to save the actual value
272 // and load it as a void pointer.
273 if (!CurField->getType()->isAnyPointerType()) {
274 auto &Ctx = getContext();
275 auto DstAddr = CreateMemTemp(
276 Ctx.getUIntPtrType(),
277 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
278 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
279
280 auto *SrcAddrVal = EmitScalarConversion(
281 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
282 Ctx.getPointerType(CurField->getType()), SourceLocation());
283 LValue SrcLV =
284 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
285
286 // Store the value using the source type pointer.
287 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
288
289 // Load the value using the destination type pointer.
290 CV = EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
291 }
292 CapturedVars.push_back(CV);
293 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000294 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000295 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000296 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000297 }
298}
299
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000300static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
301 StringRef Name, LValue AddrLV,
302 bool isReferenceType = false) {
303 ASTContext &Ctx = CGF.getContext();
304
305 auto *CastedPtr = CGF.EmitScalarConversion(
306 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
307 Ctx.getPointerType(DstType), SourceLocation());
308 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) {
498 ArgLVal = CGF.MakeAddrLValue(castValueFromUintptr(CGF, FD->getType(),
499 Args[Cnt]->getName(),
500 ArgLVal),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000501 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000502 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000503 auto *ExprArg =
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000504 CGF.EmitLoadOfLValue(ArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000505 auto VAT = FD->getCapturedVLAType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000506 VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000507 } else if (I->capturesVariable()) {
508 auto *Var = I->getCapturedVar();
509 QualType VarTy = Var->getType();
510 Address ArgAddr = ArgLVal.getAddress();
511 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000512 if (ArgLVal.getType()->isLValueReferenceType()) {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +0000513 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000514 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000515 assert(ArgLVal.getType()->isPointerType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000516 ArgAddr = CGF.EmitLoadOfPointer(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000517 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
518 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000519 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000520 if (!FO.RegisterCastedArgsOnly) {
521 LocalAddrs.insert(
522 {Args[Cnt],
523 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
524 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000525 } else if (I->capturesVariableByCopy()) {
526 assert(!FD->getType()->isAnyPointerType() &&
527 "Not expecting a captured pointer.");
528 auto *Var = I->getCapturedVar();
529 QualType VarTy = Var->getType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000530 LocalAddrs.insert(
531 {Args[Cnt],
532 {Var,
533 FO.UIntPtrCastRequired
534 ? castValueFromUintptr(CGF, FD->getType(), Args[Cnt]->getName(),
535 ArgLVal, VarTy->isReferenceType())
536 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000537 } else {
538 // If 'this' is captured, load it into CXXThisValue.
539 assert(I->capturesThis());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000540 CXXThisValue = CGF.EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation())
541 .getScalarVal();
542 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000543 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000544 ++Cnt;
545 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000546 }
547
Alexey Bataeve754b182017-08-09 19:38:53 +0000548 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000549}
550
551llvm::Function *
552CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
553 assert(
554 CapturedStmtInfo &&
555 "CapturedStmtInfo should be set when generating the captured function");
556 const CapturedDecl *CD = S.getCapturedDecl();
557 // Build the argument list.
558 bool NeedWrapperFunction =
559 getDebugInfo() &&
560 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
561 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000562 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000563 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000564 SmallString<256> Buffer;
565 llvm::raw_svector_ostream Out(Buffer);
566 Out << CapturedStmtInfo->getHelperName();
567 if (NeedWrapperFunction)
568 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000569 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataeve754b182017-08-09 19:38:53 +0000570 Out.str());
571 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
572 VLASizes, CXXThisValue, FO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000573 for (const auto &LocalAddrPair : LocalAddrs) {
574 if (LocalAddrPair.second.first) {
575 setAddrOfLocalVar(LocalAddrPair.second.first,
576 LocalAddrPair.second.second);
577 }
578 }
579 for (const auto &VLASizePair : VLASizes)
580 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000581 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000582 CapturedStmtInfo->EmitBody(*this, CD->getBody());
583 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000584 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000585 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000586
Alexey Bataevefd884d2017-08-04 21:26:25 +0000587 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000588 /*RegisterCastedArgsOnly=*/true,
589 CapturedStmtInfo->getHelperName());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000590 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000591 Args.clear();
592 LocalAddrs.clear();
593 VLASizes.clear();
594 llvm::Function *WrapperF =
595 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000596 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000597 llvm::SmallVector<llvm::Value *, 4> CallArgs;
598 for (const auto *Arg : Args) {
599 llvm::Value *CallArg;
600 auto I = LocalAddrs.find(Arg);
601 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000602 LValue LV = WrapperCGF.MakeAddrLValue(
603 I->second.second,
604 I->second.first ? I->second.first->getType() : Arg->getType(),
605 AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000606 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
607 } else {
608 auto EI = VLASizes.find(Arg);
609 if (EI != VLASizes.end())
610 CallArg = EI->second.second;
611 else {
612 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000613 Arg->getType(),
614 AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000615 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
616 }
617 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000618 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000619 }
Alexey Bataev3c595a62017-08-14 15:01:03 +0000620 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getLocStart(),
621 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000622 WrapperCGF.FinishFunction();
623 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000624}
625
Alexey Bataev9959db52014-05-06 10:08:46 +0000626//===----------------------------------------------------------------------===//
627// OpenMP Directive Emission
628//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000629void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000630 Address DestAddr, Address SrcAddr, QualType OriginalType,
631 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000632 // Perform element-by-element initialization.
633 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000634
635 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000636 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000637 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
638 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
639
640 auto SrcBegin = SrcAddr.getPointer();
641 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000642 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000643 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
644 // The basic structure here is a while-do loop.
645 auto BodyBB = createBasicBlock("omp.arraycpy.body");
646 auto DoneBB = createBasicBlock("omp.arraycpy.done");
647 auto IsEmpty =
648 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
649 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000650
Alexey Bataev420d45b2015-04-14 05:11:24 +0000651 // Enter the loop body, making that address the current address.
652 auto EntryBB = Builder.GetInsertBlock();
653 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000654
655 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
656
657 llvm::PHINode *SrcElementPHI =
658 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
659 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
660 Address SrcElementCurrent =
661 Address(SrcElementPHI,
662 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
663
664 llvm::PHINode *DestElementPHI =
665 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
666 DestElementPHI->addIncoming(DestBegin, EntryBB);
667 Address DestElementCurrent =
668 Address(DestElementPHI,
669 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000670
Alexey Bataev420d45b2015-04-14 05:11:24 +0000671 // Emit copy.
672 CopyGen(DestElementCurrent, SrcElementCurrent);
673
674 // Shift the address forward by one element.
675 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000676 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000677 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000678 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000679 // Check whether we've reached the end.
680 auto Done =
681 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
682 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000683 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
684 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000685
686 // Done.
687 EmitBlock(DoneBB, /*IsFinished=*/true);
688}
689
John McCall7f416cc2015-09-08 08:05:57 +0000690void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
691 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000692 const VarDecl *SrcVD, const Expr *Copy) {
693 if (OriginalType->isArrayType()) {
694 auto *BO = dyn_cast<BinaryOperator>(Copy);
695 if (BO && BO->getOpcode() == BO_Assign) {
696 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000697 EmitAggregateAssign(DestAddr, SrcAddr, 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());
John McCall7f416cc2015-09-08 08:05:57 +0000770 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000771 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000772 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000773 // Emit VarDecl with copy init for arrays.
774 // Get the address of the original variable captured in current
775 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000776 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000777 auto Emission = EmitAutoVarAlloca(*VD);
778 auto *Init = VD->getInit();
779 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
780 // Perform simple memcpy.
781 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000782 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000783 } else {
784 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000785 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000786 [this, VDInit, Init](Address DestElement,
787 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000788 // Clean up any temporaries needed by the initialization.
789 RunCleanupsScope InitScope(*this);
790 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000791 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000792 EmitAnyExprToMem(Init, DestElement,
793 Init->getType().getQualifiers(),
794 /*IsInitializer*/ false);
795 LocalDeclMap.erase(VDInit);
796 });
797 }
798 EmitAutoVarCleanups(Emission);
799 return Emission.getAllocatedAddress();
800 });
801 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000802 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000803 // Emit private VarDecl with copy init.
804 // Remap temp VDInit variable to the address of the original
805 // variable
806 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000807 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000808 EmitDecl(*VD);
809 LocalDeclMap.erase(VDInit);
810 return GetAddrOfLocalVar(VD);
811 });
812 }
813 assert(IsRegistered &&
814 "firstprivate var already registered as private");
815 // Silence the warning about unused variable.
816 (void)IsRegistered;
817 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000818 ++IRef;
819 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000820 }
821 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000822 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000823}
824
Alexey Bataev03b340a2014-10-21 03:16:40 +0000825void CodeGenFunction::EmitOMPPrivateClause(
826 const OMPExecutableDirective &D,
827 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000828 if (!HaveInsertPoint())
829 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000830 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000831 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000832 auto IRef = C->varlist_begin();
833 for (auto IInit : C->private_copies()) {
834 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000835 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
836 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
837 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000838 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000839 // Emit private VarDecl with copy init.
840 EmitDecl(*VD);
841 return GetAddrOfLocalVar(VD);
842 });
843 assert(IsRegistered && "private var already registered as private");
844 // Silence the warning about unused variable.
845 (void)IsRegistered;
846 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000847 ++IRef;
848 }
849 }
850}
851
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000852bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000853 if (!HaveInsertPoint())
854 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000855 // threadprivate_var1 = master_threadprivate_var1;
856 // operator=(threadprivate_var2, master_threadprivate_var2);
857 // ...
858 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000859 llvm::DenseSet<const VarDecl *> CopiedVars;
860 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000861 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000862 auto IRef = C->varlist_begin();
863 auto ISrcRef = C->source_exprs().begin();
864 auto IDestRef = C->destination_exprs().begin();
865 for (auto *AssignOp : C->assignment_ops()) {
866 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000867 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000868 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000869 // Get the address of the master variable. If we are emitting code with
870 // TLS support, the address is passed from the master as field in the
871 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000872 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000873 if (getLangOpts().OpenMPUseTLS &&
874 getContext().getTargetInfo().isTLSSupported()) {
875 assert(CapturedStmtInfo->lookup(VD) &&
876 "Copyin threadprivates should have been captured!");
877 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
878 VK_LValue, (*IRef)->getExprLoc());
879 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000880 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000881 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000882 MasterAddr =
883 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
884 : CGM.GetAddrOfGlobal(VD),
885 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000886 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000887 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000888 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000889 if (CopiedVars.size() == 1) {
890 // At first check if current thread is a master thread. If it is, no
891 // need to copy data.
892 CopyBegin = createBasicBlock("copyin.not.master");
893 CopyEnd = createBasicBlock("copyin.not.master.end");
894 Builder.CreateCondBr(
895 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000896 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
897 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000898 CopyBegin, CopyEnd);
899 EmitBlock(CopyBegin);
900 }
901 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
902 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000903 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000904 }
905 ++IRef;
906 ++ISrcRef;
907 ++IDestRef;
908 }
909 }
910 if (CopyEnd) {
911 // Exit out of copying procedure for non-master thread.
912 EmitBlock(CopyEnd, /*IsFinished=*/true);
913 return true;
914 }
915 return false;
916}
917
Alexey Bataev38e89532015-04-16 04:54:05 +0000918bool CodeGenFunction::EmitOMPLastprivateClauseInit(
919 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000920 if (!HaveInsertPoint())
921 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000922 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000923 llvm::DenseSet<const VarDecl *> SIMDLCVs;
924 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
925 auto *LoopDirective = cast<OMPLoopDirective>(&D);
926 for (auto *C : LoopDirective->counters()) {
927 SIMDLCVs.insert(
928 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
929 }
930 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000931 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000932 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000933 HasAtLeastOneLastprivate = true;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000934 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
935 !getLangOpts().OpenMPSimd)
Alexey Bataevf93095a2016-05-05 08:46:22 +0000936 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000937 auto IRef = C->varlist_begin();
938 auto IDestRef = C->destination_exprs().begin();
939 for (auto *IInit : C->private_copies()) {
940 // Keep the address of the original variable for future update at the end
941 // of the loop.
942 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000943 // Taskloops do not require additional initialization, it is done in
944 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000945 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
946 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000947 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000948 DeclRefExpr DRE(
949 const_cast<VarDecl *>(OrigVD),
950 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
951 OrigVD) != nullptr,
952 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
953 return EmitLValue(&DRE).getAddress();
954 });
955 // Check if the variable is also a firstprivate: in this case IInit is
956 // not generated. Initialization of this variable will happen in codegen
957 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000958 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000959 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000960 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
961 // Emit private VarDecl with copy init.
962 EmitDecl(*VD);
963 return GetAddrOfLocalVar(VD);
964 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000965 assert(IsRegistered &&
966 "lastprivate var already registered as private");
967 (void)IsRegistered;
968 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000969 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000970 ++IRef;
971 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000972 }
973 }
974 return HasAtLeastOneLastprivate;
975}
976
977void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000978 const OMPExecutableDirective &D, bool NoFinals,
979 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000980 if (!HaveInsertPoint())
981 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000982 // Emit following code:
983 // if (<IsLastIterCond>) {
984 // orig_var1 = private_orig_var1;
985 // ...
986 // orig_varn = private_orig_varn;
987 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000988 llvm::BasicBlock *ThenBB = nullptr;
989 llvm::BasicBlock *DoneBB = nullptr;
990 if (IsLastIterCond) {
991 ThenBB = createBasicBlock(".omp.lastprivate.then");
992 DoneBB = createBasicBlock(".omp.lastprivate.done");
993 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
994 EmitBlock(ThenBB);
995 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000996 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
997 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000998 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000999 auto IC = LoopDirective->counters().begin();
1000 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001001 auto *D =
1002 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1003 if (NoFinals)
1004 AlreadyEmittedVars.insert(D);
1005 else
1006 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001007 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001008 }
1009 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001010 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1011 auto IRef = C->varlist_begin();
1012 auto ISrcRef = C->source_exprs().begin();
1013 auto IDestRef = C->destination_exprs().begin();
1014 for (auto *AssignOp : C->assignment_ops()) {
1015 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1016 QualType Type = PrivateVD->getType();
1017 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
1018 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1019 // If lastprivate variable is a loop control variable for loop-based
1020 // directive, update its value before copyin back to original
1021 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001022 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
1023 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001024 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1025 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1026 // Get the address of the original variable.
1027 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
1028 // Get the address of the private variable.
1029 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
1030 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
1031 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +00001032 Address(Builder.CreateLoad(PrivateAddr),
1033 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001034 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +00001035 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001036 ++IRef;
1037 ++ISrcRef;
1038 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +00001039 }
Alexey Bataev005248a2016-02-25 05:25:57 +00001040 if (auto *PostUpdate = C->getPostUpdateExpr())
1041 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001042 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +00001043 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001044 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +00001045}
1046
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001047void CodeGenFunction::EmitOMPReductionClauseInit(
1048 const OMPExecutableDirective &D,
1049 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001050 if (!HaveInsertPoint())
1051 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001052 SmallVector<const Expr *, 4> Shareds;
1053 SmallVector<const Expr *, 4> Privates;
1054 SmallVector<const Expr *, 4> ReductionOps;
1055 SmallVector<const Expr *, 4> LHSs;
1056 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001057 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001058 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001059 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001060 auto ILHS = C->lhs_exprs().begin();
1061 auto IRHS = C->rhs_exprs().begin();
1062 for (const auto *Ref : C->varlists()) {
1063 Shareds.emplace_back(Ref);
1064 Privates.emplace_back(*IPriv);
1065 ReductionOps.emplace_back(*IRed);
1066 LHSs.emplace_back(*ILHS);
1067 RHSs.emplace_back(*IRHS);
1068 std::advance(IPriv, 1);
1069 std::advance(IRed, 1);
1070 std::advance(ILHS, 1);
1071 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001072 }
1073 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001074 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1075 unsigned Count = 0;
1076 auto ILHS = LHSs.begin();
1077 auto IRHS = RHSs.begin();
1078 auto IPriv = Privates.begin();
1079 for (const auto *IRef : Shareds) {
1080 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
1081 // Emit private VarDecl with reduction init.
1082 RedCG.emitSharedLValue(*this, Count);
1083 RedCG.emitAggregateType(*this, Count);
1084 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1085 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1086 RedCG.getSharedLValue(Count),
1087 [&Emission](CodeGenFunction &CGF) {
1088 CGF.EmitAutoVarInit(Emission);
1089 return true;
1090 });
1091 EmitAutoVarCleanups(Emission);
1092 Address BaseAddr = RedCG.adjustPrivateAddress(
1093 *this, Count, Emission.getAllocatedAddress());
1094 bool IsRegistered = PrivateScope.addPrivate(
1095 RedCG.getBaseDecl(Count), [BaseAddr]() -> Address { return BaseAddr; });
1096 assert(IsRegistered && "private var already registered as private");
1097 // Silence the warning about unused variable.
1098 (void)IsRegistered;
1099
1100 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1101 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001102 QualType Type = PrivateVD->getType();
1103 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1104 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001105 // Store the address of the original variable associated with the LHS
1106 // implicit variable.
1107 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1108 return RedCG.getSharedLValue(Count).getAddress();
1109 });
1110 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1111 return GetAddrOfLocalVar(PrivateVD);
1112 });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001113 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1114 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001115 // Store the address of the original variable associated with the LHS
1116 // implicit variable.
1117 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1118 return RedCG.getSharedLValue(Count).getAddress();
1119 });
1120 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1121 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1122 ConvertTypeForMem(RHSVD->getType()),
1123 "rhs.begin");
1124 });
1125 } else {
1126 QualType Type = PrivateVD->getType();
1127 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1128 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1129 // Store the address of the original variable associated with the LHS
1130 // implicit variable.
1131 if (IsArray) {
1132 OriginalAddr = Builder.CreateElementBitCast(
1133 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1134 }
1135 PrivateScope.addPrivate(
1136 LHSVD, [OriginalAddr]() -> Address { return OriginalAddr; });
1137 PrivateScope.addPrivate(
1138 RHSVD, [this, PrivateVD, RHSVD, IsArray]() -> Address {
1139 return IsArray
1140 ? Builder.CreateElementBitCast(
1141 GetAddrOfLocalVar(PrivateVD),
1142 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1143 : GetAddrOfLocalVar(PrivateVD);
1144 });
1145 }
1146 ++ILHS;
1147 ++IRHS;
1148 ++IPriv;
1149 ++Count;
1150 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001151}
1152
1153void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001154 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001155 if (!HaveInsertPoint())
1156 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001157 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001158 llvm::SmallVector<const Expr *, 8> LHSExprs;
1159 llvm::SmallVector<const Expr *, 8> RHSExprs;
1160 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001161 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001162 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001163 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001164 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001165 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1166 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1167 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1168 }
1169 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001170 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1171 isOpenMPParallelDirective(D.getDirectiveKind()) ||
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001172 ReductionKind == OMPD_simd;
1173 bool SimpleReduction = ReductionKind == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001174 // Emit nowait reduction if nowait clause is present or directive is a
1175 // parallel directive (it always has implicit barrier).
1176 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001177 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001178 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001179 }
1180}
1181
Alexey Bataev61205072016-03-02 04:57:40 +00001182static void emitPostUpdateForReductionClause(
1183 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1184 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1185 if (!CGF.HaveInsertPoint())
1186 return;
1187 llvm::BasicBlock *DoneBB = nullptr;
1188 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1189 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1190 if (!DoneBB) {
1191 if (auto *Cond = CondGen(CGF)) {
1192 // If the first post-update expression is found, emit conditional
1193 // block if it was requested.
1194 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1195 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1196 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1197 CGF.EmitBlock(ThenBB);
1198 }
1199 }
1200 CGF.EmitIgnoredExpr(PostUpdate);
1201 }
1202 }
1203 if (DoneBB)
1204 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1205}
1206
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001207namespace {
1208/// Codegen lambda for appending distribute lower and upper bounds to outlined
1209/// parallel function. This is necessary for combined constructs such as
1210/// 'distribute parallel for'
1211typedef llvm::function_ref<void(CodeGenFunction &,
1212 const OMPExecutableDirective &,
1213 llvm::SmallVectorImpl<llvm::Value *> &)>
1214 CodeGenBoundParametersTy;
1215} // anonymous namespace
1216
1217static void emitCommonOMPParallelDirective(
1218 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1219 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1220 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001221 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1222 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1223 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001224 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001225 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001226 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1227 /*IgnoreResultAssign*/ true);
1228 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1229 CGF, NumThreads, NumThreadsClause->getLocStart());
1230 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001231 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001232 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001233 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1234 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1235 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001236 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001237 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1238 if (C->getNameModifier() == OMPD_unknown ||
1239 C->getNameModifier() == OMPD_parallel) {
1240 IfCond = C->getCondition();
1241 break;
1242 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001243 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001244
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001245 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001246 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001247 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1248 // lower and upper bounds with the pragma 'for' chunking mechanism.
1249 // The following lambda takes care of appending the lower and upper bound
1250 // parameters when necessary
1251 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001252 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001253 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001254 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001255}
1256
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001257static void emitEmptyBoundParameters(CodeGenFunction &,
1258 const OMPExecutableDirective &,
1259 llvm::SmallVectorImpl<llvm::Value *> &) {}
1260
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001261void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001262 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001263 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001264 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001265 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001266 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1267 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001268 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001269 // propagation master's thread values of threadprivate variables to local
1270 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001271 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1272 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1273 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001274 }
1275 CGF.EmitOMPPrivateClause(S, PrivateScope);
1276 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1277 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00001278 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001279 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001280 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001281 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1282 emitEmptyBoundParameters);
Alexey Bataev61205072016-03-02 04:57:40 +00001283 emitPostUpdateForReductionClause(
1284 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001285}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001286
Alexey Bataev0f34da12015-07-02 04:17:07 +00001287void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1288 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001289 RunCleanupsScope BodyScope(*this);
1290 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001291 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001292 EmitIgnoredExpr(I);
1293 }
Alexander Musman3276a272015-03-21 10:12:56 +00001294 // Update the linear variables.
Alexey Bataev617db5f2017-12-04 15:38:33 +00001295 // In distribute directives only loop counters may be marked as linear, no
1296 // need to generate the code for them.
1297 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1298 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1299 for (auto *U : C->updates())
1300 EmitIgnoredExpr(U);
1301 }
Alexander Musman3276a272015-03-21 10:12:56 +00001302 }
1303
Alexander Musmana5f070a2014-10-01 06:03:56 +00001304 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001305 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001306 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001307 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001308 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001309 // The end (updates/cleanups).
1310 EmitBlock(Continue.getBlock());
1311 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001312}
1313
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001314void CodeGenFunction::EmitOMPInnerLoop(
1315 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1316 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001317 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1318 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001319 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001320
1321 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001322 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001323 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001324 const SourceRange &R = S.getSourceRange();
1325 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1326 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001327
1328 // If there are any cleanups between here and the loop-exit scope,
1329 // create a block to stage a loop exit along.
1330 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001331 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001332 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001333
Alexander Musmand196ef22014-10-07 08:57:09 +00001334 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001335
Alexey Bataev2df54a02015-03-12 08:53:29 +00001336 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001337 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001338 if (ExitBlock != LoopExit.getBlock()) {
1339 EmitBlock(ExitBlock);
1340 EmitBranchThroughCleanup(LoopExit);
1341 }
1342
1343 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001344 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001345
1346 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001347 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001348 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1349
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001350 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001351
1352 // Emit "IV = IV + 1" and a back-edge to the condition block.
1353 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001354 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001355 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001356 BreakContinueStack.pop_back();
1357 EmitBranch(CondBlock);
1358 LoopStack.pop();
1359 // Emit the fall-through block.
1360 EmitBlock(LoopExit.getBlock());
1361}
1362
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001363bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001364 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001365 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001366 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001367 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001368 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001369 for (auto *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001370 HasLinears = true;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001371 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001372 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1373 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1374 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1375 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1376 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1377 VD->getInit()->getType(), VK_LValue,
1378 VD->getInit()->getExprLoc());
1379 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1380 VD->getType()),
1381 /*capturedByInit=*/false);
1382 EmitAutoVarCleanups(Emission);
1383 } else
1384 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001385 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001386 // Emit the linear steps for the linear clauses.
1387 // If a step is not constant, it is pre-calculated before the loop.
1388 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1389 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001390 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001391 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001392 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001393 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001394 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001395 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001396}
1397
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001398void CodeGenFunction::EmitOMPLinearClauseFinal(
1399 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001400 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001401 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001402 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001403 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001404 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001405 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001406 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001407 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001408 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001409 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001410 // If the first post-update expression is found, emit conditional
1411 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001412 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1413 DoneBB = createBasicBlock(".omp.linear.pu.done");
1414 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1415 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001416 }
1417 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001418 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1419 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001420 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001421 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001422 Address OrigAddr = EmitLValue(&DRE).getAddress();
1423 CodeGenFunction::OMPPrivateScope VarScope(*this);
1424 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001425 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001426 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001427 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001428 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001429 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001430 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001431 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001432 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001433 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001434}
1435
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001436static void emitAlignedClause(CodeGenFunction &CGF,
1437 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001438 if (!CGF.HaveInsertPoint())
1439 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001440 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001441 unsigned ClauseAlignment = 0;
1442 if (auto AlignmentExpr = Clause->getAlignment()) {
1443 auto AlignmentCI =
1444 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1445 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001446 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001447 for (auto E : Clause->varlists()) {
1448 unsigned Alignment = ClauseAlignment;
1449 if (Alignment == 0) {
1450 // OpenMP [2.8.1, Description]
1451 // If no optional parameter is specified, implementation-defined default
1452 // alignments for SIMD instructions on the target platforms are assumed.
1453 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001454 CGF.getContext()
1455 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1456 E->getType()->getPointeeType()))
1457 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001458 }
1459 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1460 "alignment is not power of 2");
1461 if (Alignment != 0) {
1462 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1463 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1464 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001465 }
1466 }
1467}
1468
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001469void CodeGenFunction::EmitOMPPrivateLoopCounters(
1470 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1471 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001472 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001473 auto I = S.private_counters().begin();
1474 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001475 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1476 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001477 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001478 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001479 if (!LocalDeclMap.count(PrivateVD)) {
1480 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1481 EmitAutoVarCleanups(VarEmission);
1482 }
1483 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1484 /*RefersToEnclosingVariableOrCapture=*/false,
1485 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1486 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001487 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001488 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1489 VD->hasGlobalStorage()) {
1490 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1491 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1492 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1493 E->getType(), VK_LValue, E->getExprLoc());
1494 return EmitLValue(&DRE).getAddress();
1495 });
1496 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001497 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001498 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001499}
1500
Alexey Bataev62dbb972015-04-22 11:59:37 +00001501static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1502 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1503 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001504 if (!CGF.HaveInsertPoint())
1505 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001506 {
1507 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001508 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001509 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001510 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001511 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001512 CGF.EmitIgnoredExpr(I);
1513 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001514 }
1515 // Check that loop is executed at least one time.
1516 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1517}
1518
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001519void CodeGenFunction::EmitOMPLinearClause(
1520 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1521 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001522 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001523 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1524 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1525 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1526 for (auto *C : LoopDirective->counters()) {
1527 SIMDLCVs.insert(
1528 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1529 }
1530 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001531 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001532 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001533 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001534 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1535 auto *PrivateVD =
1536 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001537 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1538 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1539 // Emit private VarDecl with copy init.
1540 EmitVarDecl(*PrivateVD);
1541 return GetAddrOfLocalVar(PrivateVD);
1542 });
1543 assert(IsRegistered && "linear var already registered as private");
1544 // Silence the warning about unused variable.
1545 (void)IsRegistered;
1546 } else
1547 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001548 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001549 }
1550 }
1551}
1552
Alexey Bataev45bfad52015-08-21 12:19:04 +00001553static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001554 const OMPExecutableDirective &D,
1555 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001556 if (!CGF.HaveInsertPoint())
1557 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001558 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001559 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1560 /*ignoreResult=*/true);
1561 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1562 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1563 // In presence of finite 'safelen', it may be unsafe to mark all
1564 // the memory instructions parallel, because loop-carried
1565 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001566 if (!IsMonotonic)
1567 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001568 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001569 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1570 /*ignoreResult=*/true);
1571 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001572 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001573 // In presence of finite 'safelen', it may be unsafe to mark all
1574 // the memory instructions parallel, because loop-carried
1575 // dependences of 'safelen' iterations are possible.
1576 CGF.LoopStack.setParallel(false);
1577 }
1578}
1579
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001580void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1581 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001582 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001583 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001584 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001585 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001586}
1587
Alexey Bataevef549a82016-03-09 09:49:09 +00001588void CodeGenFunction::EmitOMPSimdFinal(
1589 const OMPLoopDirective &D,
1590 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001591 if (!HaveInsertPoint())
1592 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001593 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001594 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001595 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001596 for (auto F : D.finals()) {
1597 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001598 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1599 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1600 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1601 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001602 if (!DoneBB) {
1603 if (auto *Cond = CondGen(*this)) {
1604 // If the first post-update expression is found, emit conditional
1605 // block if it was requested.
1606 auto *ThenBB = createBasicBlock(".omp.final.then");
1607 DoneBB = createBasicBlock(".omp.final.done");
1608 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1609 EmitBlock(ThenBB);
1610 }
1611 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001612 Address OrigAddr = Address::invalid();
1613 if (CED)
1614 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1615 else {
1616 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1617 /*RefersToEnclosingVariableOrCapture=*/false,
1618 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1619 OrigAddr = EmitLValue(&DRE).getAddress();
1620 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001621 OMPPrivateScope VarScope(*this);
1622 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001623 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001624 (void)VarScope.Privatize();
1625 EmitIgnoredExpr(F);
1626 }
1627 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001628 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001629 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001630 if (DoneBB)
1631 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001632}
1633
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001634static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1635 const OMPLoopDirective &S,
1636 CodeGenFunction::JumpDest LoopExit) {
1637 CGF.EmitOMPLoopBody(S, LoopExit);
1638 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001639}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001640
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001641/// Emit a helper variable and return corresponding lvalue.
1642static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1643 const DeclRefExpr *Helper) {
1644 auto VDecl = cast<VarDecl>(Helper->getDecl());
1645 CGF.EmitVarDecl(*VDecl);
1646 return CGF.EmitLValue(Helper);
1647}
1648
Alexey Bataevf8365372017-11-17 17:57:25 +00001649static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1650 PrePostActionTy &Action) {
1651 Action.Enter(CGF);
1652 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1653 "Expected simd directive");
1654 OMPLoopScope PreInitScope(CGF, S);
1655 // if (PreCond) {
1656 // for (IV in 0..LastIteration) BODY;
1657 // <Final counter/linear vars updates>;
1658 // }
1659 //
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00001660 if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
1661 isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
1662 isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
1663 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1664 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1665 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001666
Alexey Bataevf8365372017-11-17 17:57:25 +00001667 // Emit: if (PreCond) - begin.
1668 // If the condition constant folds and can be elided, avoid emitting the
1669 // whole loop.
1670 bool CondConstant;
1671 llvm::BasicBlock *ContBlock = nullptr;
1672 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1673 if (!CondConstant)
1674 return;
1675 } else {
1676 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1677 ContBlock = CGF.createBasicBlock("simd.if.end");
1678 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1679 CGF.getProfileCount(&S));
1680 CGF.EmitBlock(ThenBlock);
1681 CGF.incrementProfileCounter(&S);
1682 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001683
Alexey Bataevf8365372017-11-17 17:57:25 +00001684 // Emit the loop iteration variable.
1685 const Expr *IVExpr = S.getIterationVariable();
1686 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1687 CGF.EmitVarDecl(*IVDecl);
1688 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001689
Alexey Bataevf8365372017-11-17 17:57:25 +00001690 // Emit the iterations count variable.
1691 // If it is not a variable, Sema decided to calculate iterations count on
1692 // each iteration (e.g., it is foldable into a constant).
1693 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1694 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1695 // Emit calculation of the iterations count.
1696 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1697 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001698
Alexey Bataevf8365372017-11-17 17:57:25 +00001699 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001700
Alexey Bataevf8365372017-11-17 17:57:25 +00001701 emitAlignedClause(CGF, S);
1702 (void)CGF.EmitOMPLinearClauseInit(S);
1703 {
1704 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1705 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1706 CGF.EmitOMPLinearClause(S, LoopScope);
1707 CGF.EmitOMPPrivateClause(S, LoopScope);
1708 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1709 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1710 (void)LoopScope.Privatize();
1711 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1712 S.getInc(),
1713 [&S](CodeGenFunction &CGF) {
1714 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1715 CGF.EmitStopPoint(&S);
1716 },
1717 [](CodeGenFunction &) {});
1718 CGF.EmitOMPSimdFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001719 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001720 // Emit final copy of the lastprivate variables at the end of loops.
1721 if (HasLastprivateClause)
1722 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1723 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
1724 emitPostUpdateForReductionClause(
1725 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1726 }
1727 CGF.EmitOMPLinearClauseFinal(
1728 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1729 // Emit: if (PreCond) - end.
1730 if (ContBlock) {
1731 CGF.EmitBranch(ContBlock);
1732 CGF.EmitBlock(ContBlock, true);
1733 }
1734}
1735
1736void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1737 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1738 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001739 };
Alexey Bataev475a7442018-01-12 19:39:11 +00001740 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001741 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001742}
1743
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001744void CodeGenFunction::EmitOMPOuterLoop(
1745 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1746 CodeGenFunction::OMPPrivateScope &LoopScope,
1747 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1748 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1749 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001750 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001751
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001752 const Expr *IVExpr = S.getIterationVariable();
1753 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1754 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1755
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001756 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1757
1758 // Start the loop with a block that tests the condition.
1759 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1760 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001761 const SourceRange &R = S.getSourceRange();
1762 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1763 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001764
1765 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001766 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001767 // UB = min(UB, GlobalUB) or
1768 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1769 // 'distribute parallel for')
1770 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001771 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001772 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001773 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001774 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001775 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001776 BoolCondVal =
1777 RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1778 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001779 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001780
1781 // If there are any cleanups between here and the loop-exit scope,
1782 // create a block to stage a loop exit along.
1783 auto ExitBlock = LoopExit.getBlock();
1784 if (LoopScope.requiresCleanups())
1785 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1786
1787 auto LoopBody = createBasicBlock("omp.dispatch.body");
1788 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1789 if (ExitBlock != LoopExit.getBlock()) {
1790 EmitBlock(ExitBlock);
1791 EmitBranchThroughCleanup(LoopExit);
1792 }
1793 EmitBlock(LoopBody);
1794
Alexander Musman92bdaab2015-03-12 13:37:50 +00001795 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1796 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001797 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001798 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001799
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001800 // Create a block for the increment.
1801 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1802 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1803
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001804 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1805 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001806 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1807 LoopStack.setParallel(!IsMonotonic);
1808 else
1809 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001810
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001811 SourceLocation Loc = S.getLocStart();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001812
1813 // when 'distribute' is not combined with a 'for':
1814 // while (idx <= UB) { BODY; ++idx; }
1815 // when 'distribute' is combined with a 'for'
1816 // (e.g. 'distribute parallel for')
1817 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1818 EmitOMPInnerLoop(
1819 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1820 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1821 CodeGenLoop(CGF, S, LoopExit);
1822 },
1823 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1824 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1825 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001826
1827 EmitBlock(Continue.getBlock());
1828 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001829 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001830 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001831 EmitIgnoredExpr(LoopArgs.NextLB);
1832 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001833 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001834
1835 EmitBranch(CondBlock);
1836 LoopStack.pop();
1837 // Emit the fall-through block.
1838 EmitBlock(LoopExit.getBlock());
1839
1840 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001841 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1842 if (!DynamicOrOrdered)
Alexey Bataevf43f7142017-09-06 16:17:35 +00001843 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
1844 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00001845 };
1846 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001847}
1848
1849void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001850 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001851 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001852 const OMPLoopArguments &LoopArgs,
1853 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001854 auto &RT = CGM.getOpenMPRuntime();
1855
1856 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001857 const bool DynamicOrOrdered =
1858 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001859
1860 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001861 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001862 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001863 "static non-chunked schedule does not need outer loop");
1864
1865 // Emit outer loop.
1866 //
1867 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1868 // When schedule(dynamic,chunk_size) is specified, the iterations are
1869 // distributed to threads in the team in chunks as the threads request them.
1870 // Each thread executes a chunk of iterations, then requests another chunk,
1871 // until no chunks remain to be distributed. Each chunk contains chunk_size
1872 // iterations, except for the last chunk to be distributed, which may have
1873 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1874 //
1875 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1876 // to threads in the team in chunks as the executing threads request them.
1877 // Each thread executes a chunk of iterations, then requests another chunk,
1878 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1879 // each chunk is proportional to the number of unassigned iterations divided
1880 // by the number of threads in the team, decreasing to 1. For a chunk_size
1881 // with value k (greater than 1), the size of each chunk is determined in the
1882 // same way, with the restriction that the chunks do not contain fewer than k
1883 // iterations (except for the last chunk to be assigned, which may have fewer
1884 // than k iterations).
1885 //
1886 // When schedule(auto) is specified, the decision regarding scheduling is
1887 // delegated to the compiler and/or runtime system. The programmer gives the
1888 // implementation the freedom to choose any possible mapping of iterations to
1889 // threads in the team.
1890 //
1891 // When schedule(runtime) is specified, the decision regarding scheduling is
1892 // deferred until run time, and the schedule and chunk size are taken from the
1893 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1894 // implementation defined
1895 //
1896 // while(__kmpc_dispatch_next(&LB, &UB)) {
1897 // idx = LB;
1898 // while (idx <= UB) { BODY; ++idx;
1899 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1900 // } // inner loop
1901 // }
1902 //
1903 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1904 // When schedule(static, chunk_size) is specified, iterations are divided into
1905 // chunks of size chunk_size, and the chunks are assigned to the threads in
1906 // the team in a round-robin fashion in the order of the thread number.
1907 //
1908 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1909 // while (idx <= UB) { BODY; ++idx; } // inner loop
1910 // LB = LB + ST;
1911 // UB = UB + ST;
1912 // }
1913 //
1914
1915 const Expr *IVExpr = S.getIterationVariable();
1916 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1917 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1918
1919 if (DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001920 auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1921 llvm::Value *LBVal = DispatchBounds.first;
1922 llvm::Value *UBVal = DispatchBounds.second;
1923 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1924 LoopArgs.Chunk};
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001925 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001926 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001927 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001928 CGOpenMPRuntime::StaticRTInput StaticInit(
1929 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1930 LoopArgs.ST, LoopArgs.Chunk);
1931 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
1932 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001933 }
1934
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001935 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1936 const unsigned IVSize,
1937 const bool IVSigned) {
1938 if (Ordered) {
1939 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1940 IVSigned);
1941 }
1942 };
1943
1944 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1945 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1946 OuterLoopArgs.IncExpr = S.getInc();
1947 OuterLoopArgs.Init = S.getInit();
1948 OuterLoopArgs.Cond = S.getCond();
1949 OuterLoopArgs.NextLB = S.getNextLowerBound();
1950 OuterLoopArgs.NextUB = S.getNextUpperBound();
1951 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1952 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001953}
1954
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001955static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1956 const unsigned IVSize, const bool IVSigned) {}
1957
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001958void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001959 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1960 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1961 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001962
1963 auto &RT = CGM.getOpenMPRuntime();
1964
1965 // Emit outer loop.
1966 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1967 // dynamic
1968 //
1969
1970 const Expr *IVExpr = S.getIterationVariable();
1971 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1972 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1973
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001974 CGOpenMPRuntime::StaticRTInput StaticInit(
1975 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
1976 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
1977 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001978
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001979 // for combined 'distribute' and 'for' the increment expression of distribute
1980 // is store in DistInc. For 'distribute' alone, it is in Inc.
1981 Expr *IncExpr;
1982 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1983 IncExpr = S.getDistInc();
1984 else
1985 IncExpr = S.getInc();
1986
1987 // this routine is shared by 'omp distribute parallel for' and
1988 // 'omp distribute': select the right EUB expression depending on the
1989 // directive
1990 OMPLoopArguments OuterLoopArgs;
1991 OuterLoopArgs.LB = LoopArgs.LB;
1992 OuterLoopArgs.UB = LoopArgs.UB;
1993 OuterLoopArgs.ST = LoopArgs.ST;
1994 OuterLoopArgs.IL = LoopArgs.IL;
1995 OuterLoopArgs.Chunk = LoopArgs.Chunk;
1996 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1997 ? S.getCombinedEnsureUpperBound()
1998 : S.getEnsureUpperBound();
1999 OuterLoopArgs.IncExpr = IncExpr;
2000 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2001 ? S.getCombinedInit()
2002 : S.getInit();
2003 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2004 ? S.getCombinedCond()
2005 : S.getCond();
2006 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2007 ? S.getCombinedNextLowerBound()
2008 : S.getNextLowerBound();
2009 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2010 ? S.getCombinedNextUpperBound()
2011 : S.getNextUpperBound();
2012
2013 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
2014 LoopScope, OuterLoopArgs, CodeGenLoopContent,
2015 emitEmptyOrdered);
2016}
2017
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002018static std::pair<LValue, LValue>
2019emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
2020 const OMPExecutableDirective &S) {
2021 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2022 LValue LB =
2023 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2024 LValue UB =
2025 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2026
2027 // When composing 'distribute' with 'for' (e.g. as in 'distribute
2028 // parallel for') we need to use the 'distribute'
2029 // chunk lower and upper bounds rather than the whole loop iteration
2030 // space. These are parameters to the outlined function for 'parallel'
2031 // and we copy the bounds of the previous schedule into the
2032 // the current ones.
2033 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
2034 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
2035 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(PrevLB, SourceLocation());
2036 PrevLBVal = CGF.EmitScalarConversion(
2037 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
2038 LS.getIterationVariable()->getType(), SourceLocation());
2039 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(PrevUB, SourceLocation());
2040 PrevUBVal = CGF.EmitScalarConversion(
2041 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
2042 LS.getIterationVariable()->getType(), SourceLocation());
2043
2044 CGF.EmitStoreOfScalar(PrevLBVal, LB);
2045 CGF.EmitStoreOfScalar(PrevUBVal, UB);
2046
2047 return {LB, UB};
2048}
2049
2050/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
2051/// we need to use the LB and UB expressions generated by the worksharing
2052/// code generation support, whereas in non combined situations we would
2053/// just emit 0 and the LastIteration expression
2054/// This function is necessary due to the difference of the LB and UB
2055/// types for the RT emission routines for 'for_static_init' and
2056/// 'for_dispatch_init'
2057static std::pair<llvm::Value *, llvm::Value *>
2058emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
2059 const OMPExecutableDirective &S,
2060 Address LB, Address UB) {
2061 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2062 const Expr *IVExpr = LS.getIterationVariable();
2063 // when implementing a dynamic schedule for a 'for' combined with a
2064 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
2065 // is not normalized as each team only executes its own assigned
2066 // distribute chunk
2067 QualType IteratorTy = IVExpr->getType();
2068 llvm::Value *LBVal = CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy,
2069 SourceLocation());
2070 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy,
2071 SourceLocation());
2072 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00002073}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002074
2075static void emitDistributeParallelForDistributeInnerBoundParams(
2076 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2077 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2078 const auto &Dir = cast<OMPLoopDirective>(S);
2079 LValue LB =
2080 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
2081 auto LBCast = CGF.Builder.CreateIntCast(
2082 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2083 CapturedVars.push_back(LBCast);
2084 LValue UB =
2085 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2086
2087 auto UBCast = CGF.Builder.CreateIntCast(
2088 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2089 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00002090}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002091
2092static void
2093emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2094 const OMPLoopDirective &S,
2095 CodeGenFunction::JumpDest LoopExit) {
2096 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
2097 PrePostActionTy &) {
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002098 bool HasCancel = false;
2099 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2100 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2101 HasCancel = D->hasCancel();
2102 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2103 HasCancel = D->hasCancel();
Alexey Bataev16e79882017-11-22 21:12:03 +00002104 else if (const auto *D =
2105 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2106 HasCancel = D->hasCancel();
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002107 }
2108 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2109 HasCancel);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002110 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2111 emitDistributeParallelForInnerBounds,
2112 emitDistributeParallelForDispatchBounds);
2113 };
2114
2115 emitCommonOMPParallelDirective(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002116 CGF, S,
2117 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2118 CGInlinedWorksharingLoop,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002119 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002120}
2121
Carlo Bertolli9925f152016-06-27 14:55:37 +00002122void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2123 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002124 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2125 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2126 S.getDistInc());
2127 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002128 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev10a54312017-11-27 16:54:08 +00002129 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002130}
2131
Kelvin Li4a39add2016-07-05 05:00:15 +00002132void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2133 const OMPDistributeParallelForSimdDirective &S) {
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002134 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2135 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2136 S.getDistInc());
2137 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002138 OMPLexicalScope Scope(*this, S, OMPD_parallel);
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002139 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Kelvin Li4a39add2016-07-05 05:00:15 +00002140}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002141
2142void CodeGenFunction::EmitOMPDistributeSimdDirective(
2143 const OMPDistributeSimdDirective &S) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00002144 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2145 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2146 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002147 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev617db5f2017-12-04 15:38:33 +00002148 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002149}
2150
Alexey Bataevf8365372017-11-17 17:57:25 +00002151void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2152 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2153 // Emit SPMD target parallel for region as a standalone region.
2154 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2155 emitOMPSimdRegion(CGF, S, Action);
2156 };
2157 llvm::Function *Fn;
2158 llvm::Constant *Addr;
2159 // Emit target region as a standalone region.
2160 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2161 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2162 assert(Fn && Addr && "Target device function emission failed.");
2163}
2164
Kelvin Li986330c2016-07-20 22:57:10 +00002165void CodeGenFunction::EmitOMPTargetSimdDirective(
2166 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002167 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2168 emitOMPSimdRegion(CGF, S, Action);
2169 };
2170 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002171}
2172
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002173namespace {
2174 struct ScheduleKindModifiersTy {
2175 OpenMPScheduleClauseKind Kind;
2176 OpenMPScheduleClauseModifier M1;
2177 OpenMPScheduleClauseModifier M2;
2178 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2179 OpenMPScheduleClauseModifier M1,
2180 OpenMPScheduleClauseModifier M2)
2181 : Kind(Kind), M1(M1), M2(M2) {}
2182 };
2183} // namespace
2184
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002185bool CodeGenFunction::EmitOMPWorksharingLoop(
2186 const OMPLoopDirective &S, Expr *EUB,
2187 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2188 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002189 // Emit the loop iteration variable.
2190 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2191 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2192 EmitVarDecl(*IVDecl);
2193
2194 // Emit the iterations count variable.
2195 // If it is not a variable, Sema decided to calculate iterations count on each
2196 // iteration (e.g., it is foldable into a constant).
2197 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2198 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2199 // Emit calculation of the iterations count.
2200 EmitIgnoredExpr(S.getCalcLastIteration());
2201 }
2202
2203 auto &RT = CGM.getOpenMPRuntime();
2204
Alexey Bataev38e89532015-04-16 04:54:05 +00002205 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002206 // Check pre-condition.
2207 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002208 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002209 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002210 // If the condition constant folds and can be elided, avoid emitting the
2211 // whole loop.
2212 bool CondConstant;
2213 llvm::BasicBlock *ContBlock = nullptr;
2214 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2215 if (!CondConstant)
2216 return false;
2217 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002218 auto *ThenBlock = createBasicBlock("omp.precond.then");
2219 ContBlock = createBasicBlock("omp.precond.end");
2220 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002221 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002222 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002223 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002224 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002225
Alexey Bataev8b427062016-05-25 12:36:08 +00002226 bool Ordered = false;
2227 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2228 if (OrderedClause->getNumForLoops())
2229 RT.emitDoacrossInit(*this, S);
2230 else
2231 Ordered = true;
2232 }
2233
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002234 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002235 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002236 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002237 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002238
2239 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2240 LValue LB = Bounds.first;
2241 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002242 LValue ST =
2243 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2244 LValue IL =
2245 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2246
Alexander Musmanc6388682014-12-15 07:07:06 +00002247 // Emit 'then' code.
2248 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002249 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002250 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002251 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002252 // initialization of firstprivate variables and post-update of
2253 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002254 CGM.getOpenMPRuntime().emitBarrierCall(
2255 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2256 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002257 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002258 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002259 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002260 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002261 EmitOMPPrivateLoopCounters(S, LoopScope);
2262 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002263 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002264
2265 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002266 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002267 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002268 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002269 ScheduleKind.Schedule = C->getScheduleKind();
2270 ScheduleKind.M1 = C->getFirstScheduleModifier();
2271 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002272 if (const auto *Ch = C->getChunkSize()) {
2273 Chunk = EmitScalarExpr(Ch);
2274 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2275 S.getIterationVariable()->getType(),
2276 S.getLocStart());
2277 }
2278 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002279 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2280 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002281 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2282 // If the static schedule kind is specified or if the ordered clause is
2283 // specified, and if no monotonic modifier is specified, the effect will
2284 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002285 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002286 /* Chunked */ Chunk != nullptr) &&
2287 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002288 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2289 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002290 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2291 // When no chunk_size is specified, the iteration space is divided into
2292 // chunks that are approximately equal in size, and at most one chunk is
2293 // distributed to each thread. Note that the size of the chunks is
2294 // unspecified in this case.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002295 CGOpenMPRuntime::StaticRTInput StaticInit(
2296 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
2297 UB.getAddress(), ST.getAddress());
2298 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
2299 ScheduleKind, StaticInit);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002300 auto LoopExit =
2301 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002302 // UB = min(UB, GlobalUB);
2303 EmitIgnoredExpr(S.getEnsureUpperBound());
2304 // IV = LB;
2305 EmitIgnoredExpr(S.getInit());
2306 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002307 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2308 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002309 [&S, LoopExit](CodeGenFunction &CGF) {
2310 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002311 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002312 },
2313 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002314 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002315 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002316 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002317 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2318 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002319 };
2320 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002321 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002322 const bool IsMonotonic =
2323 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2324 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2325 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2326 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002327 // Emit the outer loop, which requests its work chunk [LB..UB] from
2328 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002329 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2330 ST.getAddress(), IL.getAddress(),
2331 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002332 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002333 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002334 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002335 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2336 EmitOMPSimdFinal(S,
2337 [&](CodeGenFunction &CGF) -> llvm::Value * {
2338 return CGF.Builder.CreateIsNotNull(
2339 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2340 });
2341 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002342 EmitOMPReductionClauseFinal(
2343 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2344 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2345 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002346 // Emit post-update of the reduction variables if IsLastIter != 0.
2347 emitPostUpdateForReductionClause(
2348 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2349 return CGF.Builder.CreateIsNotNull(
2350 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2351 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002352 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2353 if (HasLastprivateClause)
2354 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002355 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2356 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002357 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002358 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002359 return CGF.Builder.CreateIsNotNull(
2360 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2361 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002362 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002363 if (ContBlock) {
2364 EmitBranch(ContBlock);
2365 EmitBlock(ContBlock, true);
2366 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002367 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002368 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002369}
2370
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002371/// The following two functions generate expressions for the loop lower
2372/// and upper bounds in case of static and dynamic (dispatch) schedule
2373/// of the associated 'for' or 'distribute' loop.
2374static std::pair<LValue, LValue>
2375emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2376 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2377 LValue LB =
2378 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2379 LValue UB =
2380 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2381 return {LB, UB};
2382}
2383
2384/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2385/// consider the lower and upper bound expressions generated by the
2386/// worksharing loop support, but we use 0 and the iteration space size as
2387/// constants
2388static std::pair<llvm::Value *, llvm::Value *>
2389emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2390 Address LB, Address UB) {
2391 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2392 const Expr *IVExpr = LS.getIterationVariable();
2393 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2394 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2395 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2396 return {LBVal, UBVal};
2397}
2398
Alexander Musmanc6388682014-12-15 07:07:06 +00002399void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002400 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002401 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2402 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002403 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002404 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2405 emitForLoopBounds,
2406 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002407 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002408 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002409 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002410 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2411 S.hasCancel());
2412 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002413
2414 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002415 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002416 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2417 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002418}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002419
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002420void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002421 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002422 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2423 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002424 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2425 emitForLoopBounds,
2426 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002427 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002428 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002429 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002430 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2431 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002432
2433 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002434 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002435 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2436 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002437}
2438
Alexey Bataev2df54a02015-03-12 08:53:29 +00002439static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2440 const Twine &Name,
2441 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002442 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002443 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002444 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002445 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002446}
2447
Alexey Bataev3392d762016-02-16 11:18:12 +00002448void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002449 const Stmt *Stmt = S.getInnermostCapturedStmt()->getCapturedStmt();
2450 const auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002451 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002452 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2453 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002454 auto &C = CGF.CGM.getContext();
2455 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2456 // Emit helper vars inits.
2457 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2458 CGF.Builder.getInt32(0));
2459 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2460 : CGF.Builder.getInt32(0);
2461 LValue UB =
2462 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2463 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2464 CGF.Builder.getInt32(1));
2465 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2466 CGF.Builder.getInt32(0));
2467 // Loop counter.
2468 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2469 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2470 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2471 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2472 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2473 // Generate condition for loop.
2474 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002475 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002476 // Increment for loop counter.
2477 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00002478 S.getLocStart(), true);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002479 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2480 // Iterate through all sections and emit a switch construct:
2481 // switch (IV) {
2482 // case 0:
2483 // <SectionStmt[0]>;
2484 // break;
2485 // ...
2486 // case <NumSection> - 1:
2487 // <SectionStmt[<NumSection> - 1]>;
2488 // break;
2489 // }
2490 // .omp.sections.exit:
2491 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2492 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2493 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2494 CS == nullptr ? 1 : CS->size());
2495 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002496 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002497 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002498 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2499 CGF.EmitBlock(CaseBB);
2500 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002501 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002502 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002503 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002504 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002505 } else {
2506 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2507 CGF.EmitBlock(CaseBB);
2508 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2509 CGF.EmitStmt(Stmt);
2510 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002511 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002512 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002513 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002514
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002515 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2516 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002517 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002518 // initialization of firstprivate variables and post-update of lastprivate
2519 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002520 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2521 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2522 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002523 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002524 CGF.EmitOMPPrivateClause(S, LoopScope);
2525 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2526 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2527 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002528
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002529 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002530 OpenMPScheduleTy ScheduleKind;
2531 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002532 CGOpenMPRuntime::StaticRTInput StaticInit(
2533 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2534 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002535 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002536 CGF, S.getLocStart(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002537 // UB = min(UB, GlobalUB);
2538 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2539 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2540 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2541 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2542 // IV = LB;
2543 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2544 // while (idx <= UB) { BODY; ++idx; }
2545 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2546 [](CodeGenFunction &) {});
2547 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002548 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002549 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2550 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002551 };
2552 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002553 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002554 // Emit post-update of the reduction variables if IsLastIter != 0.
2555 emitPostUpdateForReductionClause(
2556 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2557 return CGF.Builder.CreateIsNotNull(
2558 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2559 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002560
2561 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2562 if (HasLastprivates)
2563 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002564 S, /*NoFinals=*/false,
2565 CGF.Builder.CreateIsNotNull(
2566 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002567 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002568
2569 bool HasCancel = false;
2570 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2571 HasCancel = OSD->hasCancel();
2572 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2573 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002574 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002575 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2576 HasCancel);
2577 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2578 // clause. Otherwise the barrier will be generated by the codegen for the
2579 // directive.
2580 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002581 // Emit implicit barrier to synchronize threads and avoid data races on
2582 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002583 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2584 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002585 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002586}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002587
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002588void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002589 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002590 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002591 EmitSections(S);
2592 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002593 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002594 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002595 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2596 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002597 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002598}
2599
2600void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002601 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002602 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002603 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002604 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002605 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2606 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002607}
2608
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002609void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002610 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002611 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002612 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002613 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002614 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002615 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002616 // Build a list of copyprivate variables along with helper expressions
2617 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002618 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002619 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002620 DestExprs.append(C->destination_exprs().begin(),
2621 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002622 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002623 AssignmentOps.append(C->assignment_ops().begin(),
2624 C->assignment_ops().end());
2625 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002626 // Emit code for 'single' region along with 'copyprivate' clauses
2627 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2628 Action.Enter(CGF);
2629 OMPPrivateScope SingleScope(CGF);
2630 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2631 CGF.EmitOMPPrivateClause(S, SingleScope);
2632 (void)SingleScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00002633 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002634 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002635 {
Alexey Bataev475a7442018-01-12 19:39:11 +00002636 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev3392d762016-02-16 11:18:12 +00002637 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2638 CopyprivateVars, DestExprs,
2639 SrcExprs, AssignmentOps);
2640 }
2641 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2642 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002643 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002644 CGM.getOpenMPRuntime().emitBarrierCall(
2645 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002646 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002647 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002648}
2649
Alexey Bataev8d690652014-12-04 07:23:53 +00002650void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002651 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2652 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002653 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002654 };
Alexey Bataev475a7442018-01-12 19:39:11 +00002655 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002656 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002657}
2658
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002659void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002660 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2661 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00002662 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002663 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002664 Expr *Hint = nullptr;
2665 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2666 Hint = HintClause->getHint();
Alexey Bataev475a7442018-01-12 19:39:11 +00002667 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002668 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2669 S.getDirectiveName().getAsString(),
2670 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002671}
2672
Alexey Bataev671605e2015-04-13 05:28:11 +00002673void CodeGenFunction::EmitOMPParallelForDirective(
2674 const OMPParallelForDirective &S) {
2675 // Emit directive as a combined directive that consists of two implicit
2676 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002677 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002678 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002679 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2680 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002681 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002682 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2683 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002684}
2685
Alexander Musmane4e893b2014-09-23 09:33:00 +00002686void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002687 const OMPParallelForSimdDirective &S) {
2688 // Emit directive as a combined directive that consists of two implicit
2689 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002690 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002691 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2692 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002693 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002694 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2695 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002696}
2697
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002698void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002699 const OMPParallelSectionsDirective &S) {
2700 // Emit directive as a combined directive that consists of two implicit
2701 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002702 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2703 CGF.EmitSections(S);
2704 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002705 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2706 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002707}
2708
Alexey Bataev475a7442018-01-12 19:39:11 +00002709void CodeGenFunction::EmitOMPTaskBasedDirective(
2710 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
2711 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
2712 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002713 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00002714 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002715 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002716 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002717 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002718 // Check if the task is final
2719 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2720 // If the condition constant folds and can be elided, try to avoid emitting
2721 // the condition and the dead arm of the if/else.
2722 auto *Cond = Clause->getCondition();
2723 bool CondConstant;
2724 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2725 Data.Final.setInt(CondConstant);
2726 else
2727 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2728 } else {
2729 // By default the task is not final.
2730 Data.Final.setInt(/*IntVal=*/false);
2731 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002732 // Check if the task has 'priority' clause.
2733 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002734 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002735 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002736 Data.Priority.setPointer(EmitScalarConversion(
2737 EmitScalarExpr(Prio), Prio->getType(),
2738 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2739 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002740 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002741 // The first function argument for tasks is a thread id, the second one is a
2742 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002743 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2744 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002745 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002746 auto IRef = C->varlist_begin();
2747 for (auto *IInit : C->private_copies()) {
2748 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2749 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002750 Data.PrivateVars.push_back(*IRef);
2751 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002752 }
2753 ++IRef;
2754 }
2755 }
2756 EmittedAsPrivate.clear();
2757 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002758 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002759 auto IRef = C->varlist_begin();
2760 auto IElemInitRef = C->inits().begin();
2761 for (auto *IInit : C->private_copies()) {
2762 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2763 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002764 Data.FirstprivateVars.push_back(*IRef);
2765 Data.FirstprivateCopies.push_back(IInit);
2766 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002767 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002768 ++IRef;
2769 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002770 }
2771 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002772 // Get list of lastprivate variables (for taskloops).
2773 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2774 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2775 auto IRef = C->varlist_begin();
2776 auto ID = C->destination_exprs().begin();
2777 for (auto *IInit : C->private_copies()) {
2778 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2779 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2780 Data.LastprivateVars.push_back(*IRef);
2781 Data.LastprivateCopies.push_back(IInit);
2782 }
2783 LastprivateDstsOrigs.insert(
2784 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2785 cast<DeclRefExpr>(*IRef)});
2786 ++IRef;
2787 ++ID;
2788 }
2789 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002790 SmallVector<const Expr *, 4> LHSs;
2791 SmallVector<const Expr *, 4> RHSs;
2792 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2793 auto IPriv = C->privates().begin();
2794 auto IRed = C->reduction_ops().begin();
2795 auto ILHS = C->lhs_exprs().begin();
2796 auto IRHS = C->rhs_exprs().begin();
2797 for (const auto *Ref : C->varlists()) {
2798 Data.ReductionVars.emplace_back(Ref);
2799 Data.ReductionCopies.emplace_back(*IPriv);
2800 Data.ReductionOps.emplace_back(*IRed);
2801 LHSs.emplace_back(*ILHS);
2802 RHSs.emplace_back(*IRHS);
2803 std::advance(IPriv, 1);
2804 std::advance(IRed, 1);
2805 std::advance(ILHS, 1);
2806 std::advance(IRHS, 1);
2807 }
2808 }
2809 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2810 *this, S.getLocStart(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002811 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002812 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2813 for (auto *IRef : C->varlists())
2814 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataev475a7442018-01-12 19:39:11 +00002815 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
2816 CapturedRegion](CodeGenFunction &CGF,
2817 PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002818 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002819 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002820 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2821 !Data.LastprivateVars.empty()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00002822 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataev48591dd2016-04-20 04:01:36 +00002823 auto *CopyFn = CGF.Builder.CreateLoad(
2824 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2825 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2826 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2827 // Map privates.
2828 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2829 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2830 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002831 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002832 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2833 Address PrivatePtr = CGF.CreateMemTemp(
2834 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2835 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2836 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002837 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002838 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002839 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2840 Address PrivatePtr =
2841 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2842 ".firstpriv.ptr.addr");
2843 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2844 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002845 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002846 for (auto *E : Data.LastprivateVars) {
2847 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2848 Address PrivatePtr =
2849 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2850 ".lastpriv.ptr.addr");
2851 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2852 CallArgs.push_back(PrivatePtr.getPointer());
2853 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00002854 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
2855 CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002856 for (auto &&Pair : LastprivateDstsOrigs) {
2857 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2858 DeclRefExpr DRE(
2859 const_cast<VarDecl *>(OrigVD),
2860 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2861 OrigVD) != nullptr,
2862 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2863 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2864 return CGF.EmitLValue(&DRE).getAddress();
2865 });
2866 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002867 for (auto &&Pair : PrivatePtrs) {
2868 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2869 CGF.getContext().getDeclAlign(Pair.first));
2870 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2871 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002872 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002873 if (Data.Reductions) {
Alexey Bataev475a7442018-01-12 19:39:11 +00002874 OMPLexicalScope LexScope(CGF, S, CapturedRegion);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002875 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2876 Data.ReductionOps);
2877 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2878 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2879 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2880 RedCG.emitSharedLValue(CGF, Cnt);
2881 RedCG.emitAggregateType(CGF, Cnt);
2882 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2883 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2884 Replacement =
2885 Address(CGF.EmitScalarConversion(
2886 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2887 CGF.getContext().getPointerType(
2888 Data.ReductionCopies[Cnt]->getType()),
2889 SourceLocation()),
2890 Replacement.getAlignment());
2891 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2892 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2893 [Replacement]() { return Replacement; });
2894 // FIXME: This must removed once the runtime library is fixed.
2895 // Emit required threadprivate variables for
2896 // initilizer/combiner/finalizer.
2897 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2898 RedCG, Cnt);
2899 }
2900 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002901 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002902 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002903 SmallVector<const Expr *, 4> InRedVars;
2904 SmallVector<const Expr *, 4> InRedPrivs;
2905 SmallVector<const Expr *, 4> InRedOps;
2906 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2907 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2908 auto IPriv = C->privates().begin();
2909 auto IRed = C->reduction_ops().begin();
2910 auto ITD = C->taskgroup_descriptors().begin();
2911 for (const auto *Ref : C->varlists()) {
2912 InRedVars.emplace_back(Ref);
2913 InRedPrivs.emplace_back(*IPriv);
2914 InRedOps.emplace_back(*IRed);
2915 TaskgroupDescriptors.emplace_back(*ITD);
2916 std::advance(IPriv, 1);
2917 std::advance(IRed, 1);
2918 std::advance(ITD, 1);
2919 }
2920 }
2921 // Privatize in_reduction items here, because taskgroup descriptors must be
2922 // privatized earlier.
2923 OMPPrivateScope InRedScope(CGF);
2924 if (!InRedVars.empty()) {
2925 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2926 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2927 RedCG.emitSharedLValue(CGF, Cnt);
2928 RedCG.emitAggregateType(CGF, Cnt);
2929 // The taskgroup descriptor variable is always implicit firstprivate and
2930 // privatized already during procoessing of the firstprivates.
2931 llvm::Value *ReductionsPtr = CGF.EmitLoadOfScalar(
2932 CGF.EmitLValue(TaskgroupDescriptors[Cnt]), SourceLocation());
2933 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2934 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2935 Replacement = Address(
2936 CGF.EmitScalarConversion(
2937 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2938 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
2939 SourceLocation()),
2940 Replacement.getAlignment());
2941 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2942 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2943 [Replacement]() { return Replacement; });
2944 // FIXME: This must removed once the runtime library is fixed.
2945 // Emit required threadprivate variables for
2946 // initilizer/combiner/finalizer.
2947 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2948 RedCG, Cnt);
2949 }
2950 }
2951 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00002952
2953 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002954 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002955 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002956 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2957 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2958 Data.NumberOfParts);
2959 OMPLexicalScope Scope(*this, S);
2960 TaskGen(*this, OutlinedFn, Data);
2961}
2962
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002963static ImplicitParamDecl *
2964createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
2965 QualType Ty, CapturedDecl *CD) {
2966 auto *OrigVD = ImplicitParamDecl::Create(
2967 C, CD, SourceLocation(), /*Id=*/nullptr, Ty, ImplicitParamDecl::Other);
2968 auto *OrigRef =
2969 DeclRefExpr::Create(C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
2970 /*RefersToEnclosingVariableOrCapture=*/false,
2971 SourceLocation(), Ty, VK_LValue);
2972 auto *PrivateVD = ImplicitParamDecl::Create(
2973 C, CD, SourceLocation(), /*Id=*/nullptr, Ty, ImplicitParamDecl::Other);
2974 auto *PrivateRef = DeclRefExpr::Create(
2975 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
2976 /*RefersToEnclosingVariableOrCapture=*/false, SourceLocation(), Ty,
2977 VK_LValue);
2978 QualType ElemType = C.getBaseElementType(Ty);
2979 auto *InitVD =
2980 ImplicitParamDecl::Create(C, CD, SourceLocation(), /*Id=*/nullptr,
2981 ElemType, ImplicitParamDecl::Other);
2982 auto *InitRef =
2983 DeclRefExpr::Create(C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
2984 /*RefersToEnclosingVariableOrCapture=*/false,
2985 SourceLocation(), ElemType, VK_LValue);
2986 PrivateVD->setInitStyle(VarDecl::CInit);
2987 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
2988 InitRef, /*BasePath=*/nullptr,
2989 VK_RValue));
2990 Data.FirstprivateVars.emplace_back(OrigRef);
2991 Data.FirstprivateCopies.emplace_back(PrivateRef);
2992 Data.FirstprivateInits.emplace_back(InitRef);
2993 return OrigVD;
2994}
2995
2996void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
2997 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
2998 OMPTargetDataInfo &InputInfo) {
2999 // Emit outlined function for task construct.
3000 auto CS = S.getCapturedStmt(OMPD_task);
3001 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
3002 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3003 auto *I = CS->getCapturedDecl()->param_begin();
3004 auto *PartId = std::next(I);
3005 auto *TaskT = std::next(I, 4);
3006 OMPTaskDataTy Data;
3007 // The task is not final.
3008 Data.Final.setInt(/*IntVal=*/false);
3009 // Get list of firstprivate variables.
3010 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3011 auto IRef = C->varlist_begin();
3012 auto IElemInitRef = C->inits().begin();
3013 for (auto *IInit : C->private_copies()) {
3014 Data.FirstprivateVars.push_back(*IRef);
3015 Data.FirstprivateCopies.push_back(IInit);
3016 Data.FirstprivateInits.push_back(*IElemInitRef);
3017 ++IRef;
3018 ++IElemInitRef;
3019 }
3020 }
3021 OMPPrivateScope TargetScope(*this);
3022 VarDecl *BPVD = nullptr;
3023 VarDecl *PVD = nullptr;
3024 VarDecl *SVD = nullptr;
3025 if (InputInfo.NumberOfTargetItems > 0) {
3026 auto *CD = CapturedDecl::Create(
3027 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
3028 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
3029 QualType BaseAndPointersType = getContext().getConstantArrayType(
3030 getContext().VoidPtrTy, ArrSize, ArrayType::Normal,
3031 /*IndexTypeQuals=*/0);
3032 BPVD = createImplicitFirstprivateForType(getContext(), Data,
3033 BaseAndPointersType, CD);
3034 PVD = createImplicitFirstprivateForType(getContext(), Data,
3035 BaseAndPointersType, CD);
3036 QualType SizesType = getContext().getConstantArrayType(
3037 getContext().getSizeType(), ArrSize, ArrayType::Normal,
3038 /*IndexTypeQuals=*/0);
3039 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD);
3040 TargetScope.addPrivate(
3041 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
3042 TargetScope.addPrivate(PVD,
3043 [&InputInfo]() { return InputInfo.PointersArray; });
3044 TargetScope.addPrivate(SVD,
3045 [&InputInfo]() { return InputInfo.SizesArray; });
3046 }
3047 (void)TargetScope.Privatize();
3048 // Build list of dependences.
3049 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
3050 for (auto *IRef : C->varlists())
3051 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
3052 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3053 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3054 // Set proper addresses for generated private copies.
3055 OMPPrivateScope Scope(CGF);
3056 if (!Data.FirstprivateVars.empty()) {
3057 enum { PrivatesParam = 2, CopyFnParam = 3 };
3058 auto *CopyFn = CGF.Builder.CreateLoad(
3059 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
3060 auto *PrivatesPtr = CGF.Builder.CreateLoad(
3061 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
3062 // Map privates.
3063 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3064 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3065 CallArgs.push_back(PrivatesPtr);
3066 for (auto *E : Data.FirstprivateVars) {
3067 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3068 Address PrivatePtr =
3069 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3070 ".firstpriv.ptr.addr");
3071 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
3072 CallArgs.push_back(PrivatePtr.getPointer());
3073 }
3074 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3075 CopyFn, CallArgs);
3076 for (auto &&Pair : PrivatePtrs) {
3077 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3078 CGF.getContext().getDeclAlign(Pair.first));
3079 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3080 }
3081 }
3082 // Privatize all private variables except for in_reduction items.
3083 (void)Scope.Privatize();
Alexey Bataev8451efa2018-01-15 19:06:12 +00003084 if (InputInfo.NumberOfTargetItems > 0) {
3085 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
3086 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0, CGF.getPointerSize());
3087 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
3088 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0, CGF.getPointerSize());
3089 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
3090 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0, CGF.getSizeSize());
3091 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003092
3093 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003094 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00003095 BodyGen(CGF);
3096 };
3097 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
3098 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3099 Data.NumberOfParts);
3100 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3101 IntegerLiteral IfCond(getContext(), TrueOrFalse,
3102 getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3103 SourceLocation());
3104
3105 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getLocStart(), S, OutlinedFn,
3106 SharedsTy, CapturedStruct, &IfCond, Data);
3107}
3108
Alexey Bataev7292c292016-04-25 12:22:29 +00003109void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3110 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00003111 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
Alexey Bataev7292c292016-04-25 12:22:29 +00003112 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003113 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00003114 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00003115 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3116 if (C->getNameModifier() == OMPD_unknown ||
3117 C->getNameModifier() == OMPD_task) {
3118 IfCond = C->getCondition();
3119 break;
3120 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003121 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003122
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003123 OMPTaskDataTy Data;
3124 // Check if we should emit tied or untied task.
3125 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003126 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3127 CGF.EmitStmt(CS->getCapturedStmt());
3128 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003129 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00003130 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003131 const OMPTaskDataTy &Data) {
3132 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
3133 SharedsTy, CapturedStruct, IfCond,
3134 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003135 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003136 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003137}
3138
Alexey Bataev9f797f32015-02-05 05:57:51 +00003139void CodeGenFunction::EmitOMPTaskyieldDirective(
3140 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003141 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00003142}
3143
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003144void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00003145 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003146}
3147
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003148void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
3149 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00003150}
3151
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003152void CodeGenFunction::EmitOMPTaskgroupDirective(
3153 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003154 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3155 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003156 if (const Expr *E = S.getReductionRef()) {
3157 SmallVector<const Expr *, 4> LHSs;
3158 SmallVector<const Expr *, 4> RHSs;
3159 OMPTaskDataTy Data;
3160 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3161 auto IPriv = C->privates().begin();
3162 auto IRed = C->reduction_ops().begin();
3163 auto ILHS = C->lhs_exprs().begin();
3164 auto IRHS = C->rhs_exprs().begin();
3165 for (const auto *Ref : C->varlists()) {
3166 Data.ReductionVars.emplace_back(Ref);
3167 Data.ReductionCopies.emplace_back(*IPriv);
3168 Data.ReductionOps.emplace_back(*IRed);
3169 LHSs.emplace_back(*ILHS);
3170 RHSs.emplace_back(*IRHS);
3171 std::advance(IPriv, 1);
3172 std::advance(IRed, 1);
3173 std::advance(ILHS, 1);
3174 std::advance(IRHS, 1);
3175 }
3176 }
3177 llvm::Value *ReductionDesc =
3178 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getLocStart(),
3179 LHSs, RHSs, Data);
3180 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3181 CGF.EmitVarDecl(*VD);
3182 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3183 /*Volatile=*/false, E->getType());
3184 }
Alexey Bataev475a7442018-01-12 19:39:11 +00003185 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003186 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003187 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003188 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
3189}
3190
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003191void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003192 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003193 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003194 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3195 FlushClause->varlist_end());
3196 }
3197 return llvm::None;
3198 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00003199}
3200
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003201void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3202 const CodeGenLoopTy &CodeGenLoop,
3203 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003204 // Emit the loop iteration variable.
3205 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3206 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
3207 EmitVarDecl(*IVDecl);
3208
3209 // Emit the iterations count variable.
3210 // If it is not a variable, Sema decided to calculate iterations count on each
3211 // iteration (e.g., it is foldable into a constant).
3212 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3213 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3214 // Emit calculation of the iterations count.
3215 EmitIgnoredExpr(S.getCalcLastIteration());
3216 }
3217
3218 auto &RT = CGM.getOpenMPRuntime();
3219
Carlo Bertolli962bb802017-01-03 18:24:42 +00003220 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003221 // Check pre-condition.
3222 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003223 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003224 // Skip the entire loop if we don't meet the precondition.
3225 // If the condition constant folds and can be elided, avoid emitting the
3226 // whole loop.
3227 bool CondConstant;
3228 llvm::BasicBlock *ContBlock = nullptr;
3229 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3230 if (!CondConstant)
3231 return;
3232 } else {
3233 auto *ThenBlock = createBasicBlock("omp.precond.then");
3234 ContBlock = createBasicBlock("omp.precond.end");
3235 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3236 getProfileCount(&S));
3237 EmitBlock(ThenBlock);
3238 incrementProfileCounter(&S);
3239 }
3240
Alexey Bataev617db5f2017-12-04 15:38:33 +00003241 emitAlignedClause(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003242 // Emit 'then' code.
3243 {
3244 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003245
3246 LValue LB = EmitOMPHelperVar(
3247 *this, cast<DeclRefExpr>(
3248 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3249 ? S.getCombinedLowerBoundVariable()
3250 : S.getLowerBoundVariable())));
3251 LValue UB = EmitOMPHelperVar(
3252 *this, cast<DeclRefExpr>(
3253 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3254 ? S.getCombinedUpperBoundVariable()
3255 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003256 LValue ST =
3257 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3258 LValue IL =
3259 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3260
3261 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003262 if (EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003263 // Emit implicit barrier to synchronize threads and avoid data races
3264 // on initialization of firstprivate variables and post-update of
Carlo Bertolli962bb802017-01-03 18:24:42 +00003265 // lastprivate variables.
3266 CGM.getOpenMPRuntime().emitBarrierCall(
Alexey Bataev617db5f2017-12-04 15:38:33 +00003267 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3268 /*ForceSimpleCall=*/true);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003269 }
3270 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev617db5f2017-12-04 15:38:33 +00003271 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
Alexey Bataev999277a2017-12-06 14:31:09 +00003272 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3273 !isOpenMPTeamsDirective(S.getDirectiveKind()))
Alexey Bataev617db5f2017-12-04 15:38:33 +00003274 EmitOMPReductionClauseInit(S, LoopScope);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003275 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003276 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003277 (void)LoopScope.Privatize();
3278
3279 // Detect the distribute schedule kind and chunk.
3280 llvm::Value *Chunk = nullptr;
3281 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3282 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3283 ScheduleKind = C->getDistScheduleKind();
3284 if (const auto *Ch = C->getChunkSize()) {
3285 Chunk = EmitScalarExpr(Ch);
3286 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
Alexey Bataev617db5f2017-12-04 15:38:33 +00003287 S.getIterationVariable()->getType(),
3288 S.getLocStart());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003289 }
3290 }
3291 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3292 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3293
3294 // OpenMP [2.10.8, distribute Construct, Description]
3295 // If dist_schedule is specified, kind must be static. If specified,
3296 // iterations are divided into chunks of size chunk_size, chunks are
3297 // assigned to the teams of the league in a round-robin fashion in the
3298 // order of the team number. When no chunk_size is specified, the
3299 // iteration space is divided into chunks that are approximately equal
3300 // in size, and at most one chunk is distributed to each team of the
3301 // league. The size of the chunks is unspecified in this case.
3302 if (RT.isStaticNonchunked(ScheduleKind,
3303 /* Chunked */ Chunk != nullptr)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003304 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3305 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003306 CGOpenMPRuntime::StaticRTInput StaticInit(
3307 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3308 LB.getAddress(), UB.getAddress(), ST.getAddress());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003309 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003310 StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003311 auto LoopExit =
3312 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3313 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003314 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3315 ? S.getCombinedEnsureUpperBound()
3316 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003317 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003318 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3319 ? S.getCombinedInit()
3320 : S.getInit());
3321
3322 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3323 ? S.getCombinedCond()
3324 : S.getCond();
3325
3326 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003327 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003328 // when combined with 'for' (e.g. as in 'distribute parallel for')
3329 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3330 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3331 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3332 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003333 },
3334 [](CodeGenFunction &) {});
3335 EmitBlock(LoopExit.getBlock());
3336 // Tell the runtime we are done.
Alexey Bataevf43f7142017-09-06 16:17:35 +00003337 RT.emitForStaticFinish(*this, S.getLocStart(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003338 } else {
3339 // Emit the outer loop, which requests its work chunk [LB..UB] from
3340 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003341 const OMPLoopArguments LoopArguments = {
3342 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3343 Chunk};
3344 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3345 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003346 }
Alexey Bataev617db5f2017-12-04 15:38:33 +00003347 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3348 EmitOMPSimdFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3349 return CGF.Builder.CreateIsNotNull(
3350 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3351 });
3352 }
3353 OpenMPDirectiveKind ReductionKind = OMPD_unknown;
3354 if (isOpenMPParallelDirective(S.getDirectiveKind()) &&
3355 isOpenMPSimdDirective(S.getDirectiveKind())) {
3356 ReductionKind = OMPD_parallel_for_simd;
3357 } else if (isOpenMPParallelDirective(S.getDirectiveKind())) {
3358 ReductionKind = OMPD_parallel_for;
3359 } else if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3360 ReductionKind = OMPD_simd;
3361 } else if (!isOpenMPTeamsDirective(S.getDirectiveKind()) &&
3362 S.hasClausesOfKind<OMPReductionClause>()) {
3363 llvm_unreachable(
3364 "No reduction clauses is allowed in distribute directive.");
3365 }
3366 EmitOMPReductionClauseFinal(S, ReductionKind);
3367 // Emit post-update of the reduction variables if IsLastIter != 0.
3368 emitPostUpdateForReductionClause(
3369 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3370 return CGF.Builder.CreateIsNotNull(
3371 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3372 });
Carlo Bertolli962bb802017-01-03 18:24:42 +00003373 // Emit final copy of the lastprivate variables if IsLastIter != 0.
Alexey Bataev617db5f2017-12-04 15:38:33 +00003374 if (HasLastprivateClause) {
Carlo Bertolli962bb802017-01-03 18:24:42 +00003375 EmitOMPLastprivateClauseFinal(
3376 S, /*NoFinals=*/false,
Alexey Bataev617db5f2017-12-04 15:38:33 +00003377 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
3378 }
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003379 }
3380
3381 // We're now done with the loop, so jump to the continuation block.
3382 if (ContBlock) {
3383 EmitBranch(ContBlock);
3384 EmitBlock(ContBlock, true);
3385 }
3386 }
3387}
3388
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003389void CodeGenFunction::EmitOMPDistributeDirective(
3390 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003391 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003392
3393 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003394 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003395 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev10a54312017-11-27 16:54:08 +00003396 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003397}
3398
Alexey Bataev5f600d62015-09-29 03:48:57 +00003399static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3400 const CapturedStmt *S) {
3401 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3402 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3403 CGF.CapturedStmtInfo = &CapStmtInfo;
3404 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3405 Fn->addFnAttr(llvm::Attribute::NoInline);
3406 return Fn;
3407}
3408
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003409void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003410 if (S.hasClausesOfKind<OMPDependClause>()) {
3411 assert(!S.getAssociatedStmt() &&
3412 "No associated statement must be in ordered depend construct.");
Alexey Bataev8b427062016-05-25 12:36:08 +00003413 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3414 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003415 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003416 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003417 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003418 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3419 PrePostActionTy &Action) {
Alexey Bataev475a7442018-01-12 19:39:11 +00003420 const CapturedStmt *CS = S.getInnermostCapturedStmt();
Alexey Bataev5f600d62015-09-29 03:48:57 +00003421 if (C) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003422 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3423 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3424 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Alexey Bataev3c595a62017-08-14 15:01:03 +00003425 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3426 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003427 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003428 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003429 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev5f600d62015-09-29 03:48:57 +00003430 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003431 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003432 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003433 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003434}
3435
Alexey Bataevb57056f2015-01-22 06:17:56 +00003436static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003437 QualType SrcType, QualType DestType,
3438 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003439 assert(CGF.hasScalarEvaluationKind(DestType) &&
3440 "DestType must have scalar evaluation kind.");
3441 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3442 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003443 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3444 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00003445 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003446 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003447}
3448
3449static CodeGenFunction::ComplexPairTy
3450convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003451 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003452 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3453 "DestType must have complex evaluation kind.");
3454 CodeGenFunction::ComplexPairTy ComplexVal;
3455 if (Val.isScalar()) {
3456 // Convert the input element to the element type of the complex.
3457 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003458 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3459 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003460 ComplexVal = CodeGenFunction::ComplexPairTy(
3461 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3462 } else {
3463 assert(Val.isComplex() && "Must be a scalar or complex.");
3464 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3465 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3466 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003467 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003468 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003469 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003470 }
3471 return ComplexVal;
3472}
3473
Alexey Bataev5e018f92015-04-23 06:35:10 +00003474static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3475 LValue LVal, RValue RVal) {
3476 if (LVal.isGlobalReg()) {
3477 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3478 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003479 CGF.EmitAtomicStore(RVal, LVal,
3480 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3481 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003482 LVal.isVolatile(), /*IsInit=*/false);
3483 }
3484}
3485
Alexey Bataev8524d152016-01-21 12:35:58 +00003486void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3487 QualType RValTy, SourceLocation Loc) {
3488 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003489 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003490 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3491 *this, RVal, RValTy, LVal.getType(), Loc)),
3492 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003493 break;
3494 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003495 EmitStoreOfComplex(
3496 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003497 /*isInit=*/false);
3498 break;
3499 case TEK_Aggregate:
3500 llvm_unreachable("Must be a scalar or complex.");
3501 }
3502}
3503
Alexey Bataevb57056f2015-01-22 06:17:56 +00003504static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3505 const Expr *X, const Expr *V,
3506 SourceLocation Loc) {
3507 // v = x;
3508 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3509 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3510 LValue XLValue = CGF.EmitLValue(X);
3511 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003512 RValue Res = XLValue.isGlobalReg()
3513 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003514 : CGF.EmitAtomicLoad(
3515 XLValue, Loc,
3516 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3517 : llvm::AtomicOrdering::Monotonic,
3518 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003519 // OpenMP, 2.12.6, atomic Construct
3520 // Any atomic construct with a seq_cst clause forces the atomically
3521 // performed operation to include an implicit flush operation without a
3522 // list.
3523 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003524 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003525 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003526}
3527
Alexey Bataevb8329262015-02-27 06:33:30 +00003528static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3529 const Expr *X, const Expr *E,
3530 SourceLocation Loc) {
3531 // x = expr;
3532 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003533 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003534 // OpenMP, 2.12.6, atomic Construct
3535 // Any atomic construct with a seq_cst clause forces the atomically
3536 // performed operation to include an implicit flush operation without a
3537 // list.
3538 if (IsSeqCst)
3539 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3540}
3541
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003542static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3543 RValue Update,
3544 BinaryOperatorKind BO,
3545 llvm::AtomicOrdering AO,
3546 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003547 auto &Context = CGF.CGM.getContext();
3548 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003549 // expression is simple and atomic is allowed for the given type for the
3550 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003551 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003552 !Update.getScalarVal()->getType()->isIntegerTy() ||
3553 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3554 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003555 X.getAddress().getElementType())) ||
3556 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003557 !Context.getTargetInfo().hasBuiltinAtomic(
3558 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003559 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003560
3561 llvm::AtomicRMWInst::BinOp RMWOp;
3562 switch (BO) {
3563 case BO_Add:
3564 RMWOp = llvm::AtomicRMWInst::Add;
3565 break;
3566 case BO_Sub:
3567 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003568 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003569 RMWOp = llvm::AtomicRMWInst::Sub;
3570 break;
3571 case BO_And:
3572 RMWOp = llvm::AtomicRMWInst::And;
3573 break;
3574 case BO_Or:
3575 RMWOp = llvm::AtomicRMWInst::Or;
3576 break;
3577 case BO_Xor:
3578 RMWOp = llvm::AtomicRMWInst::Xor;
3579 break;
3580 case BO_LT:
3581 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3582 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3583 : llvm::AtomicRMWInst::Max)
3584 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3585 : llvm::AtomicRMWInst::UMax);
3586 break;
3587 case BO_GT:
3588 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3589 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3590 : llvm::AtomicRMWInst::Min)
3591 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3592 : llvm::AtomicRMWInst::UMin);
3593 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003594 case BO_Assign:
3595 RMWOp = llvm::AtomicRMWInst::Xchg;
3596 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003597 case BO_Mul:
3598 case BO_Div:
3599 case BO_Rem:
3600 case BO_Shl:
3601 case BO_Shr:
3602 case BO_LAnd:
3603 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003604 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003605 case BO_PtrMemD:
3606 case BO_PtrMemI:
3607 case BO_LE:
3608 case BO_GE:
3609 case BO_EQ:
3610 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00003611 case BO_Cmp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003612 case BO_AddAssign:
3613 case BO_SubAssign:
3614 case BO_AndAssign:
3615 case BO_OrAssign:
3616 case BO_XorAssign:
3617 case BO_MulAssign:
3618 case BO_DivAssign:
3619 case BO_RemAssign:
3620 case BO_ShlAssign:
3621 case BO_ShrAssign:
3622 case BO_Comma:
3623 llvm_unreachable("Unsupported atomic update operation");
3624 }
3625 auto *UpdateVal = Update.getScalarVal();
3626 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3627 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003628 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003629 X.getType()->hasSignedIntegerRepresentation());
3630 }
John McCall7f416cc2015-09-08 08:05:57 +00003631 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003632 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003633}
3634
Alexey Bataev5e018f92015-04-23 06:35:10 +00003635std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003636 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3637 llvm::AtomicOrdering AO, SourceLocation Loc,
3638 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3639 // Update expressions are allowed to have the following forms:
3640 // x binop= expr; -> xrval + expr;
3641 // x++, ++x -> xrval + 1;
3642 // x--, --x -> xrval - 1;
3643 // x = x binop expr; -> xrval binop expr
3644 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003645 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3646 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003647 if (X.isGlobalReg()) {
3648 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3649 // 'xrval'.
3650 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3651 } else {
3652 // Perform compare-and-swap procedure.
3653 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003654 }
3655 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003656 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003657}
3658
3659static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3660 const Expr *X, const Expr *E,
3661 const Expr *UE, bool IsXLHSInRHSPart,
3662 SourceLocation Loc) {
3663 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3664 "Update expr in 'atomic update' must be a binary operator.");
3665 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3666 // Update expressions are allowed to have the following forms:
3667 // x binop= expr; -> xrval + expr;
3668 // x++, ++x -> xrval + 1;
3669 // x--, --x -> xrval - 1;
3670 // x = x binop expr; -> xrval binop expr
3671 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003672 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003673 LValue XLValue = CGF.EmitLValue(X);
3674 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003675 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3676 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003677 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3678 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3679 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3680 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3681 auto Gen =
3682 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3683 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3684 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3685 return CGF.EmitAnyExpr(UE);
3686 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003687 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3688 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3689 // OpenMP, 2.12.6, atomic Construct
3690 // Any atomic construct with a seq_cst clause forces the atomically
3691 // performed operation to include an implicit flush operation without a
3692 // list.
3693 if (IsSeqCst)
3694 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3695}
3696
3697static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003698 QualType SourceType, QualType ResType,
3699 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003700 switch (CGF.getEvaluationKind(ResType)) {
3701 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003702 return RValue::get(
3703 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003704 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003705 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003706 return RValue::getComplex(Res.first, Res.second);
3707 }
3708 case TEK_Aggregate:
3709 break;
3710 }
3711 llvm_unreachable("Must be a scalar or complex.");
3712}
3713
3714static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3715 bool IsPostfixUpdate, const Expr *V,
3716 const Expr *X, const Expr *E,
3717 const Expr *UE, bool IsXLHSInRHSPart,
3718 SourceLocation Loc) {
3719 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3720 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3721 RValue NewVVal;
3722 LValue VLValue = CGF.EmitLValue(V);
3723 LValue XLValue = CGF.EmitLValue(X);
3724 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003725 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3726 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003727 QualType NewVValType;
3728 if (UE) {
3729 // 'x' is updated with some additional value.
3730 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3731 "Update expr in 'atomic capture' must be a binary operator.");
3732 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3733 // Update expressions are allowed to have the following forms:
3734 // x binop= expr; -> xrval + expr;
3735 // x++, ++x -> xrval + 1;
3736 // x--, --x -> xrval - 1;
3737 // x = x binop expr; -> xrval binop expr
3738 // x = expr Op x; - > expr binop xrval;
3739 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3740 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3741 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3742 NewVValType = XRValExpr->getType();
3743 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3744 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003745 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003746 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3747 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3748 RValue Res = CGF.EmitAnyExpr(UE);
3749 NewVVal = IsPostfixUpdate ? XRValue : Res;
3750 return Res;
3751 };
3752 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3753 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3754 if (Res.first) {
3755 // 'atomicrmw' instruction was generated.
3756 if (IsPostfixUpdate) {
3757 // Use old value from 'atomicrmw'.
3758 NewVVal = Res.second;
3759 } else {
3760 // 'atomicrmw' does not provide new value, so evaluate it using old
3761 // value of 'x'.
3762 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3763 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3764 NewVVal = CGF.EmitAnyExpr(UE);
3765 }
3766 }
3767 } else {
3768 // 'x' is simply rewritten with some 'expr'.
3769 NewVValType = X->getType().getNonReferenceType();
3770 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003771 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003772 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003773 NewVVal = XRValue;
3774 return ExprRValue;
3775 };
3776 // Try to perform atomicrmw xchg, otherwise simple exchange.
3777 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3778 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3779 Loc, Gen);
3780 if (Res.first) {
3781 // 'atomicrmw' instruction was generated.
3782 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3783 }
3784 }
3785 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003786 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003787 // OpenMP, 2.12.6, atomic Construct
3788 // Any atomic construct with a seq_cst clause forces the atomically
3789 // performed operation to include an implicit flush operation without a
3790 // list.
3791 if (IsSeqCst)
3792 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3793}
3794
Alexey Bataevb57056f2015-01-22 06:17:56 +00003795static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003796 bool IsSeqCst, bool IsPostfixUpdate,
3797 const Expr *X, const Expr *V, const Expr *E,
3798 const Expr *UE, bool IsXLHSInRHSPart,
3799 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003800 switch (Kind) {
3801 case OMPC_read:
3802 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3803 break;
3804 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003805 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3806 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003807 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003808 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003809 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3810 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003811 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003812 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3813 IsXLHSInRHSPart, Loc);
3814 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003815 case OMPC_if:
3816 case OMPC_final:
3817 case OMPC_num_threads:
3818 case OMPC_private:
3819 case OMPC_firstprivate:
3820 case OMPC_lastprivate:
3821 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003822 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003823 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003824 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003825 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003826 case OMPC_collapse:
3827 case OMPC_default:
3828 case OMPC_seq_cst:
3829 case OMPC_shared:
3830 case OMPC_linear:
3831 case OMPC_aligned:
3832 case OMPC_copyin:
3833 case OMPC_copyprivate:
3834 case OMPC_flush:
3835 case OMPC_proc_bind:
3836 case OMPC_schedule:
3837 case OMPC_ordered:
3838 case OMPC_nowait:
3839 case OMPC_untied:
3840 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003841 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003842 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003843 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003844 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003845 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003846 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003847 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003848 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003849 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003850 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003851 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003852 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003853 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003854 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003855 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003856 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003857 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003858 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003859 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003860 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003861 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3862 }
3863}
3864
3865void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003866 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003867 OpenMPClauseKind Kind = OMPC_unknown;
3868 for (auto *C : S.clauses()) {
3869 // Find first clause (skip seq_cst clause, if it is first).
3870 if (C->getClauseKind() != OMPC_seq_cst) {
3871 Kind = C->getClauseKind();
3872 break;
3873 }
3874 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003875
Alexey Bataev475a7442018-01-12 19:39:11 +00003876 const auto *CS = S.getInnermostCapturedStmt()->IgnoreContainers();
Alexey Bataev5e018f92015-04-23 06:35:10 +00003877 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003878 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003879 }
3880 // Processing for statements under 'atomic capture'.
3881 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3882 for (const auto *C : Compound->body()) {
3883 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3884 enterFullExpression(EWC);
3885 }
3886 }
3887 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003888
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003889 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3890 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003891 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003892 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3893 S.getV(), S.getExpr(), S.getUpdateExpr(),
3894 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003895 };
Alexey Bataev475a7442018-01-12 19:39:11 +00003896 OMPLexicalScope Scope(*this, S, OMPD_unknown);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003897 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003898}
3899
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003900static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3901 const OMPExecutableDirective &S,
3902 const RegionCodeGenTy &CodeGen) {
3903 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3904 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00003905
Samuel Antaoee8fb302016-01-06 13:42:12 +00003906 llvm::Function *Fn = nullptr;
3907 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003908
Samuel Antaobed3c462015-10-02 16:14:20 +00003909 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003910 // Check for the at most one if clause associated with the target region.
3911 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3912 if (C->getNameModifier() == OMPD_unknown ||
3913 C->getNameModifier() == OMPD_target) {
3914 IfCond = C->getCondition();
3915 break;
3916 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003917 }
3918
3919 // Check if we have any device clause associated with the directive.
3920 const Expr *Device = nullptr;
3921 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3922 Device = C->getDevice();
3923 }
3924
Samuel Antaoee8fb302016-01-06 13:42:12 +00003925 // Check if we have an if clause whose conditional always evaluates to false
3926 // or if we do not have any targets specified. If so the target region is not
3927 // an offload entry point.
3928 bool IsOffloadEntry = true;
3929 if (IfCond) {
3930 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003931 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003932 IsOffloadEntry = false;
3933 }
3934 if (CGM.getLangOpts().OMPTargetTriples.empty())
3935 IsOffloadEntry = false;
3936
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003937 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003938 StringRef ParentName;
3939 // In case we have Ctors/Dtors we use the complete type variant to produce
3940 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003941 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003942 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003943 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003944 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3945 else
3946 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003947 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003948
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003949 // Emit target region as a standalone region.
3950 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3951 IsOffloadEntry, CodeGen);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003952 OMPLexicalScope Scope(CGF, S, OMPD_task);
3953 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003954}
3955
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003956static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3957 PrePostActionTy &Action) {
3958 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3959 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3960 CGF.EmitOMPPrivateClause(S, PrivateScope);
3961 (void)PrivateScope.Privatize();
3962
3963 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00003964 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003965}
3966
3967void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3968 StringRef ParentName,
3969 const OMPTargetDirective &S) {
3970 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3971 emitTargetRegion(CGF, S, Action);
3972 };
3973 llvm::Function *Fn;
3974 llvm::Constant *Addr;
3975 // Emit target region as a standalone region.
3976 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3977 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3978 assert(Fn && Addr && "Target device function emission failed.");
3979}
3980
3981void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3982 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3983 emitTargetRegion(CGF, S, Action);
3984 };
3985 emitCommonOMPTargetDirective(*this, S, CodeGen);
3986}
3987
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003988static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3989 const OMPExecutableDirective &S,
3990 OpenMPDirectiveKind InnermostKind,
3991 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003992 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
3993 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
3994 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003995
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003996 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
3997 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003998 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003999 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
4000 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004001
Carlo Bertollic6872252016-04-04 15:55:02 +00004002 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
4003 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004004 }
4005
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004006 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004007 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4008 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004009 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
4010 CapturedVars);
4011}
4012
4013void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00004014 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004015 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004016 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00004017 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4018 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004019 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004020 (void)PrivateScope.Privatize();
Alexey Bataev475a7442018-01-12 19:39:11 +00004021 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004022 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00004023 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00004024 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004025 emitPostUpdateForReductionClause(
4026 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00004027}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004028
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004029static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4030 const OMPTargetTeamsDirective &S) {
4031 auto *CS = S.getCapturedStmt(OMPD_teams);
4032 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004033 // Emit teams region as a standalone region.
4034 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
4035 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4036 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4037 CGF.EmitOMPPrivateClause(S, PrivateScope);
4038 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4039 (void)PrivateScope.Privatize();
4040 Action.Enter(CGF);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004041 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004042 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004043 };
4044 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00004045 emitPostUpdateForReductionClause(
4046 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004047}
4048
4049void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4050 CodeGenModule &CGM, StringRef ParentName,
4051 const OMPTargetTeamsDirective &S) {
4052 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4053 emitTargetTeamsRegion(CGF, Action, S);
4054 };
4055 llvm::Function *Fn;
4056 llvm::Constant *Addr;
4057 // Emit target region as a standalone region.
4058 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4059 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4060 assert(Fn && Addr && "Target device function emission failed.");
4061}
4062
4063void CodeGenFunction::EmitOMPTargetTeamsDirective(
4064 const OMPTargetTeamsDirective &S) {
4065 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4066 emitTargetTeamsRegion(CGF, Action, S);
4067 };
4068 emitCommonOMPTargetDirective(*this, S, CodeGen);
4069}
4070
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004071static void
4072emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4073 const OMPTargetTeamsDistributeDirective &S) {
4074 Action.Enter(CGF);
4075 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4076 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4077 };
4078
4079 // Emit teams region as a standalone region.
4080 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4081 PrePostActionTy &) {
4082 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4083 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4084 (void)PrivateScope.Privatize();
4085 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4086 CodeGenDistribute);
4087 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4088 };
4089 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4090 emitPostUpdateForReductionClause(CGF, S,
4091 [](CodeGenFunction &) { return nullptr; });
4092}
4093
4094void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4095 CodeGenModule &CGM, StringRef ParentName,
4096 const OMPTargetTeamsDistributeDirective &S) {
4097 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4098 emitTargetTeamsDistributeRegion(CGF, Action, S);
4099 };
4100 llvm::Function *Fn;
4101 llvm::Constant *Addr;
4102 // Emit target region as a standalone region.
4103 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4104 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4105 assert(Fn && Addr && "Target device function emission failed.");
4106}
4107
4108void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4109 const OMPTargetTeamsDistributeDirective &S) {
4110 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4111 emitTargetTeamsDistributeRegion(CGF, Action, S);
4112 };
4113 emitCommonOMPTargetDirective(*this, S, CodeGen);
4114}
4115
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004116static void emitTargetTeamsDistributeSimdRegion(
4117 CodeGenFunction &CGF, PrePostActionTy &Action,
4118 const OMPTargetTeamsDistributeSimdDirective &S) {
4119 Action.Enter(CGF);
4120 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4121 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4122 };
4123
4124 // Emit teams region as a standalone region.
4125 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4126 PrePostActionTy &) {
4127 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4128 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4129 (void)PrivateScope.Privatize();
4130 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4131 CodeGenDistribute);
4132 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4133 };
4134 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4135 emitPostUpdateForReductionClause(CGF, S,
4136 [](CodeGenFunction &) { return nullptr; });
4137}
4138
4139void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4140 CodeGenModule &CGM, StringRef ParentName,
4141 const OMPTargetTeamsDistributeSimdDirective &S) {
4142 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4143 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4144 };
4145 llvm::Function *Fn;
4146 llvm::Constant *Addr;
4147 // Emit target region as a standalone region.
4148 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4149 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4150 assert(Fn && Addr && "Target device function emission failed.");
4151}
4152
4153void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4154 const OMPTargetTeamsDistributeSimdDirective &S) {
4155 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4156 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4157 };
4158 emitCommonOMPTargetDirective(*this, S, CodeGen);
4159}
4160
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004161void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4162 const OMPTeamsDistributeDirective &S) {
4163
4164 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4165 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4166 };
4167
4168 // Emit teams region as a standalone region.
4169 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4170 PrePostActionTy &) {
4171 OMPPrivateScope PrivateScope(CGF);
4172 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4173 (void)PrivateScope.Privatize();
4174 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4175 CodeGenDistribute);
4176 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4177 };
Alexey Bataev95c6dd42017-11-29 15:14:16 +00004178 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004179 emitPostUpdateForReductionClause(*this, S,
4180 [](CodeGenFunction &) { return nullptr; });
4181}
4182
Alexey Bataev999277a2017-12-06 14:31:09 +00004183void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4184 const OMPTeamsDistributeSimdDirective &S) {
4185 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4186 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4187 };
4188
4189 // Emit teams region as a standalone region.
4190 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4191 PrePostActionTy &) {
4192 OMPPrivateScope PrivateScope(CGF);
4193 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4194 (void)PrivateScope.Privatize();
4195 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4196 CodeGenDistribute);
4197 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4198 };
4199 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4200 emitPostUpdateForReductionClause(*this, S,
4201 [](CodeGenFunction &) { return nullptr; });
4202}
4203
Carlo Bertolli62fae152017-11-20 20:46:39 +00004204void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4205 const OMPTeamsDistributeParallelForDirective &S) {
4206 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4207 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4208 S.getDistInc());
4209 };
4210
4211 // Emit teams region as a standalone region.
4212 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4213 PrePostActionTy &) {
4214 OMPPrivateScope PrivateScope(CGF);
4215 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4216 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00004217 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4218 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004219 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4220 };
4221 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4222 emitPostUpdateForReductionClause(*this, S,
4223 [](CodeGenFunction &) { return nullptr; });
4224}
4225
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004226void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4227 const OMPTeamsDistributeParallelForSimdDirective &S) {
4228 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4229 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4230 S.getDistInc());
4231 };
4232
4233 // Emit teams region as a standalone region.
4234 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4235 PrePostActionTy &) {
4236 OMPPrivateScope PrivateScope(CGF);
4237 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4238 (void)PrivateScope.Privatize();
4239 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4240 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4241 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4242 };
4243 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4244 emitPostUpdateForReductionClause(*this, S,
4245 [](CodeGenFunction &) { return nullptr; });
4246}
4247
Carlo Bertolli52978c32018-01-03 21:12:44 +00004248static void emitTargetTeamsDistributeParallelForRegion(
4249 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
4250 PrePostActionTy &Action) {
4251 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4252 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4253 S.getDistInc());
4254 };
4255
4256 // Emit teams region as a standalone region.
4257 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4258 PrePostActionTy &) {
4259 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4260 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4261 (void)PrivateScope.Privatize();
4262 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4263 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4264 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4265 };
4266
4267 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
4268 CodeGenTeams);
4269 emitPostUpdateForReductionClause(CGF, S,
4270 [](CodeGenFunction &) { return nullptr; });
4271}
4272
4273void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
4274 CodeGenModule &CGM, StringRef ParentName,
4275 const OMPTargetTeamsDistributeParallelForDirective &S) {
4276 // Emit SPMD target teams distribute parallel for region as a standalone
4277 // region.
4278 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4279 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4280 };
4281 llvm::Function *Fn;
4282 llvm::Constant *Addr;
4283 // Emit target region as a standalone region.
4284 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4285 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4286 assert(Fn && Addr && "Target device function emission failed.");
4287}
4288
4289void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
4290 const OMPTargetTeamsDistributeParallelForDirective &S) {
4291 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4292 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4293 };
4294 emitCommonOMPTargetDirective(*this, S, CodeGen);
4295}
4296
Alexey Bataev647dd842018-01-15 20:59:40 +00004297static void emitTargetTeamsDistributeParallelForSimdRegion(
4298 CodeGenFunction &CGF,
4299 const OMPTargetTeamsDistributeParallelForSimdDirective &S,
4300 PrePostActionTy &Action) {
4301 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4302 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4303 S.getDistInc());
4304 };
4305
4306 // Emit teams region as a standalone region.
4307 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4308 PrePostActionTy &) {
4309 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4310 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4311 (void)PrivateScope.Privatize();
4312 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4313 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4314 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4315 };
4316
4317 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
4318 CodeGenTeams);
4319 emitPostUpdateForReductionClause(CGF, S,
4320 [](CodeGenFunction &) { return nullptr; });
4321}
4322
4323void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
4324 CodeGenModule &CGM, StringRef ParentName,
4325 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4326 // Emit SPMD target teams distribute parallel for simd region as a standalone
4327 // region.
4328 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4329 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4330 };
4331 llvm::Function *Fn;
4332 llvm::Constant *Addr;
4333 // Emit target region as a standalone region.
4334 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4335 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4336 assert(Fn && Addr && "Target device function emission failed.");
4337}
4338
4339void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
4340 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4341 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4342 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4343 };
4344 emitCommonOMPTargetDirective(*this, S, CodeGen);
4345}
4346
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004347void CodeGenFunction::EmitOMPCancellationPointDirective(
4348 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00004349 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
4350 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004351}
4352
Alexey Bataev80909872015-07-02 11:25:17 +00004353void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004354 const Expr *IfCond = nullptr;
4355 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4356 if (C->getNameModifier() == OMPD_unknown ||
4357 C->getNameModifier() == OMPD_cancel) {
4358 IfCond = C->getCondition();
4359 break;
4360 }
4361 }
4362 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004363 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00004364}
4365
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004366CodeGenFunction::JumpDest
4367CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00004368 if (Kind == OMPD_parallel || Kind == OMPD_task ||
4369 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004370 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004371 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00004372 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
4373 Kind == OMPD_distribute_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004374 Kind == OMPD_target_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004375 Kind == OMPD_teams_distribute_parallel_for ||
4376 Kind == OMPD_target_teams_distribute_parallel_for);
Alexey Bataev957d8562016-11-17 15:12:05 +00004377 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004378}
Michael Wong65f367f2015-07-21 13:44:28 +00004379
Samuel Antaocc10b852016-07-28 14:23:26 +00004380void CodeGenFunction::EmitOMPUseDevicePtrClause(
4381 const OMPClause &NC, OMPPrivateScope &PrivateScope,
4382 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
4383 const auto &C = cast<OMPUseDevicePtrClause>(NC);
4384 auto OrigVarIt = C.varlist_begin();
4385 auto InitIt = C.inits().begin();
4386 for (auto PvtVarIt : C.private_copies()) {
4387 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
4388 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
4389 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
4390
4391 // In order to identify the right initializer we need to match the
4392 // declaration used by the mapping logic. In some cases we may get
4393 // OMPCapturedExprDecl that refers to the original declaration.
4394 const ValueDecl *MatchingVD = OrigVD;
4395 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
4396 // OMPCapturedExprDecl are used to privative fields of the current
4397 // structure.
4398 auto *ME = cast<MemberExpr>(OED->getInit());
4399 assert(isa<CXXThisExpr>(ME->getBase()) &&
4400 "Base should be the current struct!");
4401 MatchingVD = ME->getMemberDecl();
4402 }
4403
4404 // If we don't have information about the current list item, move on to
4405 // the next one.
4406 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
4407 if (InitAddrIt == CaptureDeviceAddrMap.end())
4408 continue;
4409
4410 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
4411 // Initialize the temporary initialization variable with the address we
4412 // get from the runtime library. We have to cast the source address
4413 // because it is always a void *. References are materialized in the
4414 // privatization scope, so the initialization here disregards the fact
4415 // the original variable is a reference.
4416 QualType AddrQTy =
4417 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
4418 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
4419 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
4420 setAddrOfLocalVar(InitVD, InitAddr);
4421
4422 // Emit private declaration, it will be initialized by the value we
4423 // declaration we just added to the local declarations map.
4424 EmitDecl(*PvtVD);
4425
4426 // The initialization variables reached its purpose in the emission
4427 // ofthe previous declaration, so we don't need it anymore.
4428 LocalDeclMap.erase(InitVD);
4429
4430 // Return the address of the private variable.
4431 return GetAddrOfLocalVar(PvtVD);
4432 });
4433 assert(IsRegistered && "firstprivate var already registered as private");
4434 // Silence the warning about unused variable.
4435 (void)IsRegistered;
4436
4437 ++OrigVarIt;
4438 ++InitIt;
4439 }
4440}
4441
Michael Wong65f367f2015-07-21 13:44:28 +00004442// Generate the instructions for '#pragma omp target data' directive.
4443void CodeGenFunction::EmitOMPTargetDataDirective(
4444 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004445 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4446
4447 // Create a pre/post action to signal the privatization of the device pointer.
4448 // This action can be replaced by the OpenMP runtime code generation to
4449 // deactivate privatization.
4450 bool PrivatizeDevicePointers = false;
4451 class DevicePointerPrivActionTy : public PrePostActionTy {
4452 bool &PrivatizeDevicePointers;
4453
4454 public:
4455 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4456 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4457 void Enter(CodeGenFunction &CGF) override {
4458 PrivatizeDevicePointers = true;
4459 }
Samuel Antaodf158d52016-04-27 22:58:19 +00004460 };
Samuel Antaocc10b852016-07-28 14:23:26 +00004461 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4462
4463 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
Alexey Bataev475a7442018-01-12 19:39:11 +00004464 CodeGenFunction &CGF, PrePostActionTy &Action) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004465 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev475a7442018-01-12 19:39:11 +00004466 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
Samuel Antaocc10b852016-07-28 14:23:26 +00004467 };
4468
4469 // Codegen that selects wheather to generate the privatization code or not.
4470 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4471 &InnermostCodeGen](CodeGenFunction &CGF,
4472 PrePostActionTy &Action) {
4473 RegionCodeGenTy RCG(InnermostCodeGen);
4474 PrivatizeDevicePointers = false;
4475
4476 // Call the pre-action to change the status of PrivatizeDevicePointers if
4477 // needed.
4478 Action.Enter(CGF);
4479
4480 if (PrivatizeDevicePointers) {
4481 OMPPrivateScope PrivateScope(CGF);
4482 // Emit all instances of the use_device_ptr clause.
4483 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4484 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4485 Info.CaptureDeviceAddrMap);
4486 (void)PrivateScope.Privatize();
4487 RCG(CGF);
4488 } else
4489 RCG(CGF);
4490 };
4491
4492 // Forward the provided action to the privatization codegen.
4493 RegionCodeGenTy PrivRCG(PrivCodeGen);
4494 PrivRCG.setAction(Action);
4495
4496 // Notwithstanding the body of the region is emitted as inlined directive,
4497 // we don't use an inline scope as changes in the references inside the
4498 // region are expected to be visible outside, so we do not privative them.
4499 OMPLexicalScope Scope(CGF, S);
4500 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4501 PrivRCG);
4502 };
4503
4504 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004505
4506 // If we don't have target devices, don't bother emitting the data mapping
4507 // code.
4508 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004509 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004510 return;
4511 }
4512
4513 // Check if we have any if clause associated with the directive.
4514 const Expr *IfCond = nullptr;
4515 if (auto *C = S.getSingleClause<OMPIfClause>())
4516 IfCond = C->getCondition();
4517
4518 // Check if we have any device clause associated with the directive.
4519 const Expr *Device = nullptr;
4520 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4521 Device = C->getDevice();
4522
Samuel Antaocc10b852016-07-28 14:23:26 +00004523 // Set the action to signal privatization of device pointers.
4524 RCG.setAction(PrivAction);
4525
4526 // Emit region code.
4527 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4528 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004529}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004530
Samuel Antaodf67fc42016-01-19 19:15:56 +00004531void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4532 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004533 // If we don't have target devices, don't bother emitting the data mapping
4534 // code.
4535 if (CGM.getLangOpts().OMPTargetTriples.empty())
4536 return;
4537
4538 // Check if we have any if clause associated with the directive.
4539 const Expr *IfCond = nullptr;
4540 if (auto *C = S.getSingleClause<OMPIfClause>())
4541 IfCond = C->getCondition();
4542
4543 // Check if we have any device clause associated with the directive.
4544 const Expr *Device = nullptr;
4545 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4546 Device = C->getDevice();
4547
Alexey Bataev475a7442018-01-12 19:39:11 +00004548 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004549 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004550}
4551
Samuel Antao72590762016-01-19 20:04:50 +00004552void CodeGenFunction::EmitOMPTargetExitDataDirective(
4553 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004554 // If we don't have target devices, don't bother emitting the data mapping
4555 // code.
4556 if (CGM.getLangOpts().OMPTargetTriples.empty())
4557 return;
4558
4559 // Check if we have any if clause associated with the directive.
4560 const Expr *IfCond = nullptr;
4561 if (auto *C = S.getSingleClause<OMPIfClause>())
4562 IfCond = C->getCondition();
4563
4564 // Check if we have any device clause associated with the directive.
4565 const Expr *Device = nullptr;
4566 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4567 Device = C->getDevice();
4568
Alexey Bataev475a7442018-01-12 19:39:11 +00004569 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004570 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004571}
4572
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004573static void emitTargetParallelRegion(CodeGenFunction &CGF,
4574 const OMPTargetParallelDirective &S,
4575 PrePostActionTy &Action) {
4576 // Get the captured statement associated with the 'parallel' region.
4577 auto *CS = S.getCapturedStmt(OMPD_parallel);
4578 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004579 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
4580 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4581 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4582 CGF.EmitOMPPrivateClause(S, PrivateScope);
4583 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4584 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004585 // TODO: Add support for clauses.
4586 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004587 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004588 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004589 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4590 emitEmptyBoundParameters);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004591 emitPostUpdateForReductionClause(
4592 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004593}
4594
4595void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4596 CodeGenModule &CGM, StringRef ParentName,
4597 const OMPTargetParallelDirective &S) {
4598 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4599 emitTargetParallelRegion(CGF, S, Action);
4600 };
4601 llvm::Function *Fn;
4602 llvm::Constant *Addr;
4603 // Emit target region as a standalone region.
4604 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4605 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4606 assert(Fn && Addr && "Target device function emission failed.");
4607}
4608
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004609void CodeGenFunction::EmitOMPTargetParallelDirective(
4610 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004611 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4612 emitTargetParallelRegion(CGF, S, Action);
4613 };
4614 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004615}
4616
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004617static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4618 const OMPTargetParallelForDirective &S,
4619 PrePostActionTy &Action) {
4620 Action.Enter(CGF);
4621 // Emit directive as a combined directive that consists of two implicit
4622 // directives: 'parallel' with 'for' directive.
4623 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev2139ed62017-11-16 18:20:21 +00004624 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4625 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004626 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4627 emitDispatchForLoopBounds);
4628 };
4629 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4630 emitEmptyBoundParameters);
4631}
4632
4633void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4634 CodeGenModule &CGM, StringRef ParentName,
4635 const OMPTargetParallelForDirective &S) {
4636 // Emit SPMD target parallel for region as a standalone region.
4637 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4638 emitTargetParallelForRegion(CGF, S, Action);
4639 };
4640 llvm::Function *Fn;
4641 llvm::Constant *Addr;
4642 // Emit target region as a standalone region.
4643 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4644 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4645 assert(Fn && Addr && "Target device function emission failed.");
4646}
4647
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004648void CodeGenFunction::EmitOMPTargetParallelForDirective(
4649 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004650 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4651 emitTargetParallelForRegion(CGF, S, Action);
4652 };
4653 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004654}
4655
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004656static void
4657emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4658 const OMPTargetParallelForSimdDirective &S,
4659 PrePostActionTy &Action) {
4660 Action.Enter(CGF);
4661 // Emit directive as a combined directive that consists of two implicit
4662 // directives: 'parallel' with 'for' directive.
4663 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4664 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4665 emitDispatchForLoopBounds);
4666 };
4667 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4668 emitEmptyBoundParameters);
4669}
4670
4671void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4672 CodeGenModule &CGM, StringRef ParentName,
4673 const OMPTargetParallelForSimdDirective &S) {
4674 // Emit SPMD target parallel for region as a standalone region.
4675 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4676 emitTargetParallelForSimdRegion(CGF, S, Action);
4677 };
4678 llvm::Function *Fn;
4679 llvm::Constant *Addr;
4680 // Emit target region as a standalone region.
4681 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4682 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4683 assert(Fn && Addr && "Target device function emission failed.");
4684}
4685
4686void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4687 const OMPTargetParallelForSimdDirective &S) {
4688 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4689 emitTargetParallelForSimdRegion(CGF, S, Action);
4690 };
4691 emitCommonOMPTargetDirective(*this, S, CodeGen);
4692}
4693
Alexey Bataev7292c292016-04-25 12:22:29 +00004694/// Emit a helper variable and return corresponding lvalue.
4695static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4696 const ImplicitParamDecl *PVD,
4697 CodeGenFunction::OMPPrivateScope &Privates) {
4698 auto *VDecl = cast<VarDecl>(Helper->getDecl());
4699 Privates.addPrivate(
4700 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
4701}
4702
4703void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4704 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4705 // Emit outlined function for task construct.
Alexey Bataev475a7442018-01-12 19:39:11 +00004706 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
Alexey Bataev7292c292016-04-25 12:22:29 +00004707 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
4708 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4709 const Expr *IfCond = nullptr;
4710 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4711 if (C->getNameModifier() == OMPD_unknown ||
4712 C->getNameModifier() == OMPD_taskloop) {
4713 IfCond = C->getCondition();
4714 break;
4715 }
4716 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004717
4718 OMPTaskDataTy Data;
4719 // Check if taskloop must be emitted without taskgroup.
4720 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004721 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004722 Data.Tied = true;
4723 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004724 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4725 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004726 Data.Schedule.setInt(/*IntVal=*/false);
4727 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004728 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4729 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004730 Data.Schedule.setInt(/*IntVal=*/true);
4731 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004732 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004733
4734 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4735 // if (PreCond) {
4736 // for (IV in 0..LastIteration) BODY;
4737 // <Final counter/linear vars updates>;
4738 // }
4739 //
4740
4741 // Emit: if (PreCond) - begin.
4742 // If the condition constant folds and can be elided, avoid emitting the
4743 // whole loop.
4744 bool CondConstant;
4745 llvm::BasicBlock *ContBlock = nullptr;
4746 OMPLoopScope PreInitScope(CGF, S);
4747 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4748 if (!CondConstant)
4749 return;
4750 } else {
4751 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4752 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4753 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4754 CGF.getProfileCount(&S));
4755 CGF.EmitBlock(ThenBlock);
4756 CGF.incrementProfileCounter(&S);
4757 }
4758
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004759 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4760 CGF.EmitOMPSimdInit(S);
4761
Alexey Bataev7292c292016-04-25 12:22:29 +00004762 OMPPrivateScope LoopScope(CGF);
4763 // Emit helper vars inits.
4764 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4765 auto *I = CS->getCapturedDecl()->param_begin();
4766 auto *LBP = std::next(I, LowerBound);
4767 auto *UBP = std::next(I, UpperBound);
4768 auto *STP = std::next(I, Stride);
4769 auto *LIP = std::next(I, LastIter);
4770 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4771 LoopScope);
4772 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4773 LoopScope);
4774 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4775 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4776 LoopScope);
4777 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004778 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004779 (void)LoopScope.Privatize();
4780 // Emit the loop iteration variable.
4781 const Expr *IVExpr = S.getIterationVariable();
4782 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4783 CGF.EmitVarDecl(*IVDecl);
4784 CGF.EmitIgnoredExpr(S.getInit());
4785
4786 // Emit the iterations count variable.
4787 // If it is not a variable, Sema decided to calculate iterations count on
4788 // each iteration (e.g., it is foldable into a constant).
4789 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4790 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4791 // Emit calculation of the iterations count.
4792 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4793 }
4794
4795 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4796 S.getInc(),
4797 [&S](CodeGenFunction &CGF) {
4798 CGF.EmitOMPLoopBody(S, JumpDest());
4799 CGF.EmitStopPoint(&S);
4800 },
4801 [](CodeGenFunction &) {});
4802 // Emit: if (PreCond) - end.
4803 if (ContBlock) {
4804 CGF.EmitBranch(ContBlock);
4805 CGF.EmitBlock(ContBlock, true);
4806 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004807 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4808 if (HasLastprivateClause) {
4809 CGF.EmitOMPLastprivateClauseFinal(
4810 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4811 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4812 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4813 (*LIP)->getType(), S.getLocStart())));
4814 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004815 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004816 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4817 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4818 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004819 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4820 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004821 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4822 OutlinedFn, SharedsTy,
4823 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004824 };
4825 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4826 CodeGen);
4827 };
Alexey Bataev475a7442018-01-12 19:39:11 +00004828 if (Data.Nogroup) {
4829 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
4830 } else {
Alexey Bataev33446032017-07-12 18:09:32 +00004831 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4832 *this,
4833 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4834 PrePostActionTy &Action) {
4835 Action.Enter(CGF);
Alexey Bataev475a7442018-01-12 19:39:11 +00004836 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
4837 Data);
Alexey Bataev33446032017-07-12 18:09:32 +00004838 },
4839 S.getLocStart());
4840 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004841}
4842
Alexey Bataev49f6e782015-12-01 04:18:41 +00004843void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004844 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004845}
4846
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004847void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4848 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004849 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004850}
Samuel Antao686c70c2016-05-26 17:30:50 +00004851
4852// Generate the instructions for '#pragma omp target update' directive.
4853void CodeGenFunction::EmitOMPTargetUpdateDirective(
4854 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00004855 // If we don't have target devices, don't bother emitting the data mapping
4856 // code.
4857 if (CGM.getLangOpts().OMPTargetTriples.empty())
4858 return;
4859
4860 // Check if we have any if clause associated with the directive.
4861 const Expr *IfCond = nullptr;
4862 if (auto *C = S.getSingleClause<OMPIfClause>())
4863 IfCond = C->getCondition();
4864
4865 // Check if we have any device clause associated with the directive.
4866 const Expr *Device = nullptr;
4867 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4868 Device = C->getDevice();
4869
Alexey Bataev475a7442018-01-12 19:39:11 +00004870 OMPLexicalScope Scope(*this, S, OMPD_task);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004871 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00004872}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00004873
4874void CodeGenFunction::EmitSimpleOMPExecutableDirective(
4875 const OMPExecutableDirective &D) {
4876 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
4877 return;
4878 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
4879 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
4880 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
4881 } else {
4882 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
4883 for (const auto *E : LD->counters()) {
4884 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
4885 cast<DeclRefExpr>(E)->getDecl())) {
4886 // Emit only those that were not explicitly referenced in clauses.
4887 if (!CGF.LocalDeclMap.count(VD))
4888 CGF.EmitVarDecl(*VD);
4889 }
4890 }
4891 }
Alexey Bataev475a7442018-01-12 19:39:11 +00004892 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00004893 }
4894 };
4895 OMPSimdLexicalScope Scope(*this, D);
4896 CGM.getOpenMPRuntime().emitInlinedDirective(
4897 *this,
4898 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
4899 : D.getDirectiveKind(),
4900 CodeGen);
4901}