blob: 045c88f63097529a1fa3b9215f090bdb721d80bc [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 Bataev4ba78a42016-04-27 07:56:03 +000056 OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S,
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000057 bool AsInlined = false, bool EmitPreInitStmt = true)
Alexey Bataev4ba78a42016-04-27 07:56:03 +000058 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
59 InlinedShareds(CGF) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000060 if (EmitPreInitStmt)
61 emitPreInitStmt(CGF, S);
Alexey Bataev4ba78a42016-04-27 07:56:03 +000062 if (AsInlined) {
63 if (S.hasAssociatedStmt()) {
64 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
65 for (auto &C : CS->captures()) {
66 if (C.capturesVariable() || C.capturesVariableByCopy()) {
67 auto *VD = C.getCapturedVar();
Alexey Bataev6a71f362017-08-22 17:54:52 +000068 assert(VD == VD->getCanonicalDecl() &&
69 "Canonical decl must be captured.");
Alexey Bataev4ba78a42016-04-27 07:56:03 +000070 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
71 isCapturedVar(CGF, VD) ||
72 (CGF.CapturedStmtInfo &&
73 InlinedShareds.isGlobalVarCaptured(VD)),
74 VD->getType().getNonReferenceType(), VK_LValue,
75 SourceLocation());
76 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
77 return CGF.EmitLValue(&DRE).getAddress();
78 });
79 }
80 }
81 (void)InlinedShareds.Privatize();
82 }
83 }
Alexey Bataev3392d762016-02-16 11:18:12 +000084 }
85};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000086
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000087/// Lexical scope for OpenMP parallel construct, that handles correct codegen
88/// for captured expressions.
89class OMPParallelScope final : public OMPLexicalScope {
90 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
91 OpenMPDirectiveKind Kind = S.getDirectiveKind();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +000092 return !(isOpenMPTargetExecutionDirective(Kind) ||
93 isOpenMPLoopBoundSharingDirective(Kind)) &&
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000094 isOpenMPParallelDirective(Kind);
95 }
96
97public:
98 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
99 : OMPLexicalScope(CGF, S,
100 /*AsInlined=*/false,
101 /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
102};
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)
115 : OMPLexicalScope(CGF, S,
116 /*AsInlined=*/false,
117 /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
118};
119
Alexey Bataev5a3af132016-03-29 08:58:54 +0000120/// Private scope for OpenMP loop-based directives, that supports capturing
121/// of used expression from loop statement.
122class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
123 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
Alexey Bataevc2e88a82017-12-04 21:30:42 +0000124 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
125 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
126 (void)PreCondScope.Privatize();
Alexey Bataev5a3af132016-03-29 08:58:54 +0000127 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
128 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
129 for (const auto *I : PreInits->decls())
130 CGF.EmitVarDecl(cast<VarDecl>(*I));
131 }
132 }
133 }
134
135public:
136 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
137 : CodeGenFunction::RunCleanupsScope(CGF) {
138 emitPreInitStmt(CGF, S);
139 }
140};
141
Alexey Bataev3392d762016-02-16 11:18:12 +0000142} // namespace
143
Alexey Bataevf8365372017-11-17 17:57:25 +0000144static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
145 const OMPExecutableDirective &S,
146 const RegionCodeGenTy &CodeGen);
147
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000148LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
149 if (auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
150 if (auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
151 OrigVD = OrigVD->getCanonicalDecl();
152 bool IsCaptured =
153 LambdaCaptureFields.lookup(OrigVD) ||
154 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
155 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
156 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), IsCaptured,
157 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
158 return EmitLValue(&DRE);
159 }
160 }
161 return EmitLValue(E);
162}
163
Alexey Bataev1189bd02016-01-26 12:20:39 +0000164llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
165 auto &C = getContext();
166 llvm::Value *Size = nullptr;
167 auto SizeInChars = C.getTypeSizeInChars(Ty);
168 if (SizeInChars.isZero()) {
169 // getTypeSizeInChars() returns 0 for a VLA.
170 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
171 llvm::Value *ArraySize;
172 std::tie(ArraySize, Ty) = getVLASize(VAT);
173 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
174 }
175 SizeInChars = C.getTypeSizeInChars(Ty);
176 if (SizeInChars.isZero())
177 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
178 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
179 } else
180 Size = CGM.getSize(SizeInChars);
181 return Size;
182}
183
Alexey Bataev2377fe92015-09-10 08:12:02 +0000184void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000185 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000186 const RecordDecl *RD = S.getCapturedRecordDecl();
187 auto CurField = RD->field_begin();
188 auto CurCap = S.captures().begin();
189 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
190 E = S.capture_init_end();
191 I != E; ++I, ++CurField, ++CurCap) {
192 if (CurField->hasCapturedVLAType()) {
193 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000194 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000195 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000196 } else if (CurCap->capturesThis())
197 CapturedVars.push_back(CXXThisValue);
Samuel Antao6d004262016-06-16 18:39:34 +0000198 else if (CurCap->capturesVariableByCopy()) {
199 llvm::Value *CV =
200 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal();
201
202 // If the field is not a pointer, we need to save the actual value
203 // and load it as a void pointer.
204 if (!CurField->getType()->isAnyPointerType()) {
205 auto &Ctx = getContext();
206 auto DstAddr = CreateMemTemp(
207 Ctx.getUIntPtrType(),
208 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
209 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
210
211 auto *SrcAddrVal = EmitScalarConversion(
212 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
213 Ctx.getPointerType(CurField->getType()), SourceLocation());
214 LValue SrcLV =
215 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
216
217 // Store the value using the source type pointer.
218 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
219
220 // Load the value using the destination type pointer.
221 CV = EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
222 }
223 CapturedVars.push_back(CV);
224 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000225 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000226 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000227 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000228 }
229}
230
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000231static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
232 StringRef Name, LValue AddrLV,
233 bool isReferenceType = false) {
234 ASTContext &Ctx = CGF.getContext();
235
236 auto *CastedPtr = CGF.EmitScalarConversion(
237 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
238 Ctx.getPointerType(DstType), SourceLocation());
239 auto TmpAddr =
240 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
241 .getAddress();
242
243 // If we are dealing with references we need to return the address of the
244 // reference instead of the reference of the value.
245 if (isReferenceType) {
246 QualType RefType = Ctx.getLValueReferenceType(DstType);
247 auto *RefVal = TmpAddr.getPointer();
248 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
249 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
Akira Hatanaka642f7992016-10-18 19:05:41 +0000250 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000251 }
252
253 return TmpAddr;
254}
255
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000256static QualType getCanonicalParamType(ASTContext &C, QualType T) {
257 if (T->isLValueReferenceType()) {
258 return C.getLValueReferenceType(
259 getCanonicalParamType(C, T.getNonReferenceType()),
260 /*SpelledAsLValue=*/false);
261 }
262 if (T->isPointerType())
263 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000264 if (auto *A = T->getAsArrayTypeUnsafe()) {
265 if (auto *VLA = dyn_cast<VariableArrayType>(A))
266 return getCanonicalParamType(C, VLA->getElementType());
267 else if (!A->isVariablyModifiedType())
268 return C.getCanonicalType(T);
269 }
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000270 return C.getCanonicalParamType(T);
271}
272
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000273namespace {
274 /// Contains required data for proper outlined function codegen.
275 struct FunctionOptions {
276 /// Captured statement for which the function is generated.
277 const CapturedStmt *S = nullptr;
278 /// true if cast to/from UIntPtr is required for variables captured by
279 /// value.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000280 const bool UIntPtrCastRequired = true;
Alexey Bataeve754b182017-08-09 19:38:53 +0000281 /// true if only casted arguments must be registered as local args or VLA
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000282 /// sizes.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000283 const bool RegisterCastedArgsOnly = false;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000284 /// Name of the generated function.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000285 const StringRef FunctionName;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000286 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
287 bool RegisterCastedArgsOnly,
Alexey Bataev4aa19052017-08-08 16:45:36 +0000288 StringRef FunctionName)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000289 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
290 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
Alexey Bataev4aa19052017-08-08 16:45:36 +0000291 FunctionName(FunctionName) {}
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000292 };
293}
294
Alexey Bataeve754b182017-08-09 19:38:53 +0000295static llvm::Function *emitOutlinedFunctionPrologue(
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000296 CodeGenFunction &CGF, FunctionArgList &Args,
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000297 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000298 &LocalAddrs,
299 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
300 &VLASizes,
301 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
302 const CapturedDecl *CD = FO.S->getCapturedDecl();
303 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000304 assert(CD->hasBody() && "missing CapturedDecl body");
305
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000306 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000307 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000308 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000309 ASTContext &Ctx = CGM.getContext();
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000310 FunctionArgList TargetArgs;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000311 Args.append(CD->param_begin(),
312 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000313 TargetArgs.append(
314 CD->param_begin(),
315 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000316 auto I = FO.S->captures().begin();
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000317 FunctionDecl *DebugFunctionDecl = nullptr;
318 if (!FO.UIntPtrCastRequired) {
319 FunctionProtoType::ExtProtoInfo EPI;
320 DebugFunctionDecl = FunctionDecl::Create(
321 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getLocStart(),
322 SourceLocation(), DeclarationName(), Ctx.VoidTy,
323 Ctx.getTrivialTypeSourceInfo(
324 Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI)),
325 SC_Static, /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
326 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000327 for (auto *FD : RD->fields()) {
328 QualType ArgType = FD->getType();
329 IdentifierInfo *II = nullptr;
330 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000331
332 // If this is a capture by copy and the type is not a pointer, the outlined
333 // function argument type should be uintptr and the value properly casted to
334 // uintptr. This is necessary given that the runtime library is only able to
335 // deal with pointers. We can pass in the same way the VLA type sizes to the
336 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000337 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000338 I->capturesVariableArrayType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000339 if (FO.UIntPtrCastRequired)
340 ArgType = Ctx.getUIntPtrType();
341 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000342
343 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000344 CapVar = I->getCapturedVar();
345 II = CapVar->getIdentifier();
346 } else if (I->capturesThis())
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000347 II = &Ctx.Idents.get("this");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000348 else {
349 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000350 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000351 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000352 if (ArgType->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000353 ArgType = getCanonicalParamType(Ctx, ArgType);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000354 VarDecl *Arg;
355 if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
356 Arg = ParmVarDecl::Create(
357 Ctx, DebugFunctionDecl,
358 CapVar ? CapVar->getLocStart() : FD->getLocStart(),
359 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
360 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
361 } else {
362 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
363 II, ArgType, ImplicitParamDecl::Other);
364 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000365 Args.emplace_back(Arg);
366 // Do not cast arguments if we emit function with non-original types.
367 TargetArgs.emplace_back(
368 FO.UIntPtrCastRequired
369 ? Arg
370 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000371 ++I;
372 }
373 Args.append(
374 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
375 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000376 TargetArgs.append(
377 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
378 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000379
380 // Create the function declaration.
Alexey Bataev2377fe92015-09-10 08:12:02 +0000381 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000382 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000383 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
384
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000385 llvm::Function *F =
386 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
387 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000388 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
389 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000390 F->setDoesNotThrow();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000391
392 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000393 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
394 FO.S->getLocStart(), CD->getBody()->getLocStart());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000395 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000396 I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000397 for (auto *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000398 // Do not map arguments if we emit function with non-original types.
399 Address LocalAddr(Address::invalid());
400 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
401 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
402 TargetArgs[Cnt]);
403 } else {
404 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
405 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000406 // If we are capturing a pointer by copy we don't need to do anything, just
407 // use the value that we get from the arguments.
408 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000409 const VarDecl *CurVD = I->getCapturedVar();
Samuel Antao403ffd42016-07-27 22:49:49 +0000410 // If the variable is a reference we need to materialize it here.
411 if (CurVD->getType()->isReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000412 Address RefAddr = CGF.CreateMemTemp(
413 CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
414 CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
415 /*Volatile=*/false, CurVD->getType());
Samuel Antao403ffd42016-07-27 22:49:49 +0000416 LocalAddr = RefAddr;
417 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000418 if (!FO.RegisterCastedArgsOnly)
419 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000420 ++Cnt;
421 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000422 continue;
423 }
424
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000425 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
426 AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000427 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000428 if (FO.UIntPtrCastRequired) {
429 ArgLVal = CGF.MakeAddrLValue(castValueFromUintptr(CGF, FD->getType(),
430 Args[Cnt]->getName(),
431 ArgLVal),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000432 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000433 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000434 auto *ExprArg =
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000435 CGF.EmitLoadOfLValue(ArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000436 auto VAT = FD->getCapturedVLAType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000437 VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000438 } else if (I->capturesVariable()) {
439 auto *Var = I->getCapturedVar();
440 QualType VarTy = Var->getType();
441 Address ArgAddr = ArgLVal.getAddress();
442 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000443 if (ArgLVal.getType()->isLValueReferenceType()) {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +0000444 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000445 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000446 assert(ArgLVal.getType()->isPointerType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000447 ArgAddr = CGF.EmitLoadOfPointer(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000448 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
449 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000450 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000451 if (!FO.RegisterCastedArgsOnly) {
452 LocalAddrs.insert(
453 {Args[Cnt],
454 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
455 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000456 } else if (I->capturesVariableByCopy()) {
457 assert(!FD->getType()->isAnyPointerType() &&
458 "Not expecting a captured pointer.");
459 auto *Var = I->getCapturedVar();
460 QualType VarTy = Var->getType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000461 LocalAddrs.insert(
462 {Args[Cnt],
463 {Var,
464 FO.UIntPtrCastRequired
465 ? castValueFromUintptr(CGF, FD->getType(), Args[Cnt]->getName(),
466 ArgLVal, VarTy->isReferenceType())
467 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000468 } else {
469 // If 'this' is captured, load it into CXXThisValue.
470 assert(I->capturesThis());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000471 CXXThisValue = CGF.EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation())
472 .getScalarVal();
473 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000474 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000475 ++Cnt;
476 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000477 }
478
Alexey Bataeve754b182017-08-09 19:38:53 +0000479 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000480}
481
482llvm::Function *
483CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
484 assert(
485 CapturedStmtInfo &&
486 "CapturedStmtInfo should be set when generating the captured function");
487 const CapturedDecl *CD = S.getCapturedDecl();
488 // Build the argument list.
489 bool NeedWrapperFunction =
490 getDebugInfo() &&
491 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
492 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000493 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000494 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000495 SmallString<256> Buffer;
496 llvm::raw_svector_ostream Out(Buffer);
497 Out << CapturedStmtInfo->getHelperName();
498 if (NeedWrapperFunction)
499 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000500 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataeve754b182017-08-09 19:38:53 +0000501 Out.str());
502 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
503 VLASizes, CXXThisValue, FO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000504 for (const auto &LocalAddrPair : LocalAddrs) {
505 if (LocalAddrPair.second.first) {
506 setAddrOfLocalVar(LocalAddrPair.second.first,
507 LocalAddrPair.second.second);
508 }
509 }
510 for (const auto &VLASizePair : VLASizes)
511 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000512 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000513 CapturedStmtInfo->EmitBody(*this, CD->getBody());
514 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000515 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000516 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000517
Alexey Bataevefd884d2017-08-04 21:26:25 +0000518 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000519 /*RegisterCastedArgsOnly=*/true,
520 CapturedStmtInfo->getHelperName());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000521 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000522 Args.clear();
523 LocalAddrs.clear();
524 VLASizes.clear();
525 llvm::Function *WrapperF =
526 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000527 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000528 llvm::SmallVector<llvm::Value *, 4> CallArgs;
529 for (const auto *Arg : Args) {
530 llvm::Value *CallArg;
531 auto I = LocalAddrs.find(Arg);
532 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000533 LValue LV = WrapperCGF.MakeAddrLValue(
534 I->second.second,
535 I->second.first ? I->second.first->getType() : Arg->getType(),
536 AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000537 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
538 } else {
539 auto EI = VLASizes.find(Arg);
540 if (EI != VLASizes.end())
541 CallArg = EI->second.second;
542 else {
543 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000544 Arg->getType(),
545 AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000546 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
547 }
548 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000549 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000550 }
Alexey Bataev3c595a62017-08-14 15:01:03 +0000551 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getLocStart(),
552 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000553 WrapperCGF.FinishFunction();
554 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000555}
556
Alexey Bataev9959db52014-05-06 10:08:46 +0000557//===----------------------------------------------------------------------===//
558// OpenMP Directive Emission
559//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000560void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000561 Address DestAddr, Address SrcAddr, QualType OriginalType,
562 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000563 // Perform element-by-element initialization.
564 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000565
566 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000567 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000568 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
569 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
570
571 auto SrcBegin = SrcAddr.getPointer();
572 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000573 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000574 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
575 // The basic structure here is a while-do loop.
576 auto BodyBB = createBasicBlock("omp.arraycpy.body");
577 auto DoneBB = createBasicBlock("omp.arraycpy.done");
578 auto IsEmpty =
579 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
580 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000581
Alexey Bataev420d45b2015-04-14 05:11:24 +0000582 // Enter the loop body, making that address the current address.
583 auto EntryBB = Builder.GetInsertBlock();
584 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000585
586 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
587
588 llvm::PHINode *SrcElementPHI =
589 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
590 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
591 Address SrcElementCurrent =
592 Address(SrcElementPHI,
593 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
594
595 llvm::PHINode *DestElementPHI =
596 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
597 DestElementPHI->addIncoming(DestBegin, EntryBB);
598 Address DestElementCurrent =
599 Address(DestElementPHI,
600 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000601
Alexey Bataev420d45b2015-04-14 05:11:24 +0000602 // Emit copy.
603 CopyGen(DestElementCurrent, SrcElementCurrent);
604
605 // Shift the address forward by one element.
606 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000607 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000608 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000609 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000610 // Check whether we've reached the end.
611 auto Done =
612 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
613 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000614 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
615 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000616
617 // Done.
618 EmitBlock(DoneBB, /*IsFinished=*/true);
619}
620
John McCall7f416cc2015-09-08 08:05:57 +0000621void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
622 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000623 const VarDecl *SrcVD, const Expr *Copy) {
624 if (OriginalType->isArrayType()) {
625 auto *BO = dyn_cast<BinaryOperator>(Copy);
626 if (BO && BO->getOpcode() == BO_Assign) {
627 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000628 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000629 } else {
630 // For arrays with complex element types perform element by element
631 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000632 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000633 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000634 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000635 // Working with the single array element, so have to remap
636 // destination and source variables to corresponding array
637 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000638 CodeGenFunction::OMPPrivateScope Remap(*this);
639 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000640 return DestElement;
641 });
642 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000643 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000644 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000645 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000646 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000647 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000648 } else {
649 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000650 CodeGenFunction::OMPPrivateScope Remap(*this);
651 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
652 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000653 (void)Remap.Privatize();
654 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000655 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000656 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000657}
658
Alexey Bataev69c62a92015-04-15 04:52:20 +0000659bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
660 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000661 if (!HaveInsertPoint())
662 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000663 bool FirstprivateIsLastprivate = false;
664 llvm::DenseSet<const VarDecl *> Lastprivates;
665 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
666 for (const auto *D : C->varlists())
667 Lastprivates.insert(
668 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
669 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000670 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000671 CGCapturedStmtInfo CapturesInfo(cast<CapturedStmt>(*D.getAssociatedStmt()));
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000672 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000673 auto IRef = C->varlist_begin();
674 auto InitsRef = C->inits().begin();
675 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000676 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000677 bool ThisFirstprivateIsLastprivate =
678 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000679 auto *CapFD = CapturesInfo.lookup(OrigVD);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000680 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9afe5752016-05-24 07:40:12 +0000681 if (!ThisFirstprivateIsLastprivate && FD && (FD == CapFD) &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000682 !FD->getType()->isReferenceType()) {
683 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
684 ++IRef;
685 ++InitsRef;
686 continue;
687 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000688 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000689 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000690 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000691 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
692 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
693 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000694 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
695 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
696 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000697 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000698 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000699 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000700 // Emit VarDecl with copy init for arrays.
701 // Get the address of the original variable captured in current
702 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000703 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000704 auto Emission = EmitAutoVarAlloca(*VD);
705 auto *Init = VD->getInit();
706 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
707 // Perform simple memcpy.
708 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000709 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000710 } else {
711 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000712 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000713 [this, VDInit, Init](Address DestElement,
714 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000715 // Clean up any temporaries needed by the initialization.
716 RunCleanupsScope InitScope(*this);
717 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000718 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000719 EmitAnyExprToMem(Init, DestElement,
720 Init->getType().getQualifiers(),
721 /*IsInitializer*/ false);
722 LocalDeclMap.erase(VDInit);
723 });
724 }
725 EmitAutoVarCleanups(Emission);
726 return Emission.getAllocatedAddress();
727 });
728 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000729 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000730 // Emit private VarDecl with copy init.
731 // Remap temp VDInit variable to the address of the original
732 // variable
733 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000734 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000735 EmitDecl(*VD);
736 LocalDeclMap.erase(VDInit);
737 return GetAddrOfLocalVar(VD);
738 });
739 }
740 assert(IsRegistered &&
741 "firstprivate var already registered as private");
742 // Silence the warning about unused variable.
743 (void)IsRegistered;
744 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000745 ++IRef;
746 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000747 }
748 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000749 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000750}
751
Alexey Bataev03b340a2014-10-21 03:16:40 +0000752void CodeGenFunction::EmitOMPPrivateClause(
753 const OMPExecutableDirective &D,
754 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000755 if (!HaveInsertPoint())
756 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000757 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000758 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000759 auto IRef = C->varlist_begin();
760 for (auto IInit : C->private_copies()) {
761 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000762 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
763 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
764 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000765 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000766 // Emit private VarDecl with copy init.
767 EmitDecl(*VD);
768 return GetAddrOfLocalVar(VD);
769 });
770 assert(IsRegistered && "private var already registered as private");
771 // Silence the warning about unused variable.
772 (void)IsRegistered;
773 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000774 ++IRef;
775 }
776 }
777}
778
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000779bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000780 if (!HaveInsertPoint())
781 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000782 // threadprivate_var1 = master_threadprivate_var1;
783 // operator=(threadprivate_var2, master_threadprivate_var2);
784 // ...
785 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000786 llvm::DenseSet<const VarDecl *> CopiedVars;
787 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000788 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000789 auto IRef = C->varlist_begin();
790 auto ISrcRef = C->source_exprs().begin();
791 auto IDestRef = C->destination_exprs().begin();
792 for (auto *AssignOp : C->assignment_ops()) {
793 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000794 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000795 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000796 // Get the address of the master variable. If we are emitting code with
797 // TLS support, the address is passed from the master as field in the
798 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000799 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000800 if (getLangOpts().OpenMPUseTLS &&
801 getContext().getTargetInfo().isTLSSupported()) {
802 assert(CapturedStmtInfo->lookup(VD) &&
803 "Copyin threadprivates should have been captured!");
804 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
805 VK_LValue, (*IRef)->getExprLoc());
806 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000807 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000808 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000809 MasterAddr =
810 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
811 : CGM.GetAddrOfGlobal(VD),
812 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000813 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000814 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000815 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000816 if (CopiedVars.size() == 1) {
817 // At first check if current thread is a master thread. If it is, no
818 // need to copy data.
819 CopyBegin = createBasicBlock("copyin.not.master");
820 CopyEnd = createBasicBlock("copyin.not.master.end");
821 Builder.CreateCondBr(
822 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000823 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
824 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000825 CopyBegin, CopyEnd);
826 EmitBlock(CopyBegin);
827 }
828 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
829 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000830 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000831 }
832 ++IRef;
833 ++ISrcRef;
834 ++IDestRef;
835 }
836 }
837 if (CopyEnd) {
838 // Exit out of copying procedure for non-master thread.
839 EmitBlock(CopyEnd, /*IsFinished=*/true);
840 return true;
841 }
842 return false;
843}
844
Alexey Bataev38e89532015-04-16 04:54:05 +0000845bool CodeGenFunction::EmitOMPLastprivateClauseInit(
846 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000847 if (!HaveInsertPoint())
848 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000849 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000850 llvm::DenseSet<const VarDecl *> SIMDLCVs;
851 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
852 auto *LoopDirective = cast<OMPLoopDirective>(&D);
853 for (auto *C : LoopDirective->counters()) {
854 SIMDLCVs.insert(
855 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
856 }
857 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000858 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000859 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000860 HasAtLeastOneLastprivate = true;
Alexey Bataevf93095a2016-05-05 08:46:22 +0000861 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()))
862 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000863 auto IRef = C->varlist_begin();
864 auto IDestRef = C->destination_exprs().begin();
865 for (auto *IInit : C->private_copies()) {
866 // Keep the address of the original variable for future update at the end
867 // of the loop.
868 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000869 // Taskloops do not require additional initialization, it is done in
870 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000871 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
872 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000873 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000874 DeclRefExpr DRE(
875 const_cast<VarDecl *>(OrigVD),
876 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
877 OrigVD) != nullptr,
878 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
879 return EmitLValue(&DRE).getAddress();
880 });
881 // Check if the variable is also a firstprivate: in this case IInit is
882 // not generated. Initialization of this variable will happen in codegen
883 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000884 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000885 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000886 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
887 // Emit private VarDecl with copy init.
888 EmitDecl(*VD);
889 return GetAddrOfLocalVar(VD);
890 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000891 assert(IsRegistered &&
892 "lastprivate var already registered as private");
893 (void)IsRegistered;
894 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000895 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000896 ++IRef;
897 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000898 }
899 }
900 return HasAtLeastOneLastprivate;
901}
902
903void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000904 const OMPExecutableDirective &D, bool NoFinals,
905 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000906 if (!HaveInsertPoint())
907 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000908 // Emit following code:
909 // if (<IsLastIterCond>) {
910 // orig_var1 = private_orig_var1;
911 // ...
912 // orig_varn = private_orig_varn;
913 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000914 llvm::BasicBlock *ThenBB = nullptr;
915 llvm::BasicBlock *DoneBB = nullptr;
916 if (IsLastIterCond) {
917 ThenBB = createBasicBlock(".omp.lastprivate.then");
918 DoneBB = createBasicBlock(".omp.lastprivate.done");
919 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
920 EmitBlock(ThenBB);
921 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000922 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
923 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000924 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000925 auto IC = LoopDirective->counters().begin();
926 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000927 auto *D =
928 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
929 if (NoFinals)
930 AlreadyEmittedVars.insert(D);
931 else
932 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000933 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000934 }
935 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000936 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
937 auto IRef = C->varlist_begin();
938 auto ISrcRef = C->source_exprs().begin();
939 auto IDestRef = C->destination_exprs().begin();
940 for (auto *AssignOp : C->assignment_ops()) {
941 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
942 QualType Type = PrivateVD->getType();
943 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
944 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
945 // If lastprivate variable is a loop control variable for loop-based
946 // directive, update its value before copyin back to original
947 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000948 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
949 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000950 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
951 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
952 // Get the address of the original variable.
953 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
954 // Get the address of the private variable.
955 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
956 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
957 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000958 Address(Builder.CreateLoad(PrivateAddr),
959 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000960 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000961 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000962 ++IRef;
963 ++ISrcRef;
964 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000965 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000966 if (auto *PostUpdate = C->getPostUpdateExpr())
967 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000968 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000969 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000970 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000971}
972
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000973void CodeGenFunction::EmitOMPReductionClauseInit(
974 const OMPExecutableDirective &D,
975 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000976 if (!HaveInsertPoint())
977 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000978 SmallVector<const Expr *, 4> Shareds;
979 SmallVector<const Expr *, 4> Privates;
980 SmallVector<const Expr *, 4> ReductionOps;
981 SmallVector<const Expr *, 4> LHSs;
982 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000983 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000984 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000985 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000986 auto ILHS = C->lhs_exprs().begin();
987 auto IRHS = C->rhs_exprs().begin();
988 for (const auto *Ref : C->varlists()) {
989 Shareds.emplace_back(Ref);
990 Privates.emplace_back(*IPriv);
991 ReductionOps.emplace_back(*IRed);
992 LHSs.emplace_back(*ILHS);
993 RHSs.emplace_back(*IRHS);
994 std::advance(IPriv, 1);
995 std::advance(IRed, 1);
996 std::advance(ILHS, 1);
997 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000998 }
999 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001000 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1001 unsigned Count = 0;
1002 auto ILHS = LHSs.begin();
1003 auto IRHS = RHSs.begin();
1004 auto IPriv = Privates.begin();
1005 for (const auto *IRef : Shareds) {
1006 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
1007 // Emit private VarDecl with reduction init.
1008 RedCG.emitSharedLValue(*this, Count);
1009 RedCG.emitAggregateType(*this, Count);
1010 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1011 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1012 RedCG.getSharedLValue(Count),
1013 [&Emission](CodeGenFunction &CGF) {
1014 CGF.EmitAutoVarInit(Emission);
1015 return true;
1016 });
1017 EmitAutoVarCleanups(Emission);
1018 Address BaseAddr = RedCG.adjustPrivateAddress(
1019 *this, Count, Emission.getAllocatedAddress());
1020 bool IsRegistered = PrivateScope.addPrivate(
1021 RedCG.getBaseDecl(Count), [BaseAddr]() -> Address { return BaseAddr; });
1022 assert(IsRegistered && "private var already registered as private");
1023 // Silence the warning about unused variable.
1024 (void)IsRegistered;
1025
1026 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1027 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001028 QualType Type = PrivateVD->getType();
1029 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1030 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001031 // Store the address of the original variable associated with the LHS
1032 // implicit variable.
1033 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1034 return RedCG.getSharedLValue(Count).getAddress();
1035 });
1036 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1037 return GetAddrOfLocalVar(PrivateVD);
1038 });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001039 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1040 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001041 // Store the address of the original variable associated with the LHS
1042 // implicit variable.
1043 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1044 return RedCG.getSharedLValue(Count).getAddress();
1045 });
1046 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1047 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1048 ConvertTypeForMem(RHSVD->getType()),
1049 "rhs.begin");
1050 });
1051 } else {
1052 QualType Type = PrivateVD->getType();
1053 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1054 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1055 // Store the address of the original variable associated with the LHS
1056 // implicit variable.
1057 if (IsArray) {
1058 OriginalAddr = Builder.CreateElementBitCast(
1059 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1060 }
1061 PrivateScope.addPrivate(
1062 LHSVD, [OriginalAddr]() -> Address { return OriginalAddr; });
1063 PrivateScope.addPrivate(
1064 RHSVD, [this, PrivateVD, RHSVD, IsArray]() -> Address {
1065 return IsArray
1066 ? Builder.CreateElementBitCast(
1067 GetAddrOfLocalVar(PrivateVD),
1068 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1069 : GetAddrOfLocalVar(PrivateVD);
1070 });
1071 }
1072 ++ILHS;
1073 ++IRHS;
1074 ++IPriv;
1075 ++Count;
1076 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001077}
1078
1079void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001080 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001081 if (!HaveInsertPoint())
1082 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001083 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001084 llvm::SmallVector<const Expr *, 8> LHSExprs;
1085 llvm::SmallVector<const Expr *, 8> RHSExprs;
1086 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001087 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001088 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001089 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001090 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001091 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1092 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1093 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1094 }
1095 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001096 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1097 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1098 D.getDirectiveKind() == OMPD_simd;
Alexey Bataev617db5f2017-12-04 15:38:33 +00001099 bool SimpleReduction = D.getDirectiveKind() == OMPD_simd ||
1100 D.getDirectiveKind() == OMPD_distribute_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001101 // Emit nowait reduction if nowait clause is present or directive is a
1102 // parallel directive (it always has implicit barrier).
1103 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001104 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001105 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001106 }
1107}
1108
Alexey Bataev61205072016-03-02 04:57:40 +00001109static void emitPostUpdateForReductionClause(
1110 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1111 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1112 if (!CGF.HaveInsertPoint())
1113 return;
1114 llvm::BasicBlock *DoneBB = nullptr;
1115 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1116 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1117 if (!DoneBB) {
1118 if (auto *Cond = CondGen(CGF)) {
1119 // If the first post-update expression is found, emit conditional
1120 // block if it was requested.
1121 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1122 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1123 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1124 CGF.EmitBlock(ThenBB);
1125 }
1126 }
1127 CGF.EmitIgnoredExpr(PostUpdate);
1128 }
1129 }
1130 if (DoneBB)
1131 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1132}
1133
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001134namespace {
1135/// Codegen lambda for appending distribute lower and upper bounds to outlined
1136/// parallel function. This is necessary for combined constructs such as
1137/// 'distribute parallel for'
1138typedef llvm::function_ref<void(CodeGenFunction &,
1139 const OMPExecutableDirective &,
1140 llvm::SmallVectorImpl<llvm::Value *> &)>
1141 CodeGenBoundParametersTy;
1142} // anonymous namespace
1143
1144static void emitCommonOMPParallelDirective(
1145 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1146 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1147 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001148 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1149 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1150 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001151 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001152 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001153 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1154 /*IgnoreResultAssign*/ true);
1155 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1156 CGF, NumThreads, NumThreadsClause->getLocStart());
1157 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001158 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001159 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001160 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1161 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1162 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001163 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001164 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1165 if (C->getNameModifier() == OMPD_unknown ||
1166 C->getNameModifier() == OMPD_parallel) {
1167 IfCond = C->getCondition();
1168 break;
1169 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001170 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001171
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001172 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001173 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001174 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1175 // lower and upper bounds with the pragma 'for' chunking mechanism.
1176 // The following lambda takes care of appending the lower and upper bound
1177 // parameters when necessary
1178 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001179 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001180 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001181 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001182}
1183
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001184static void emitEmptyBoundParameters(CodeGenFunction &,
1185 const OMPExecutableDirective &,
1186 llvm::SmallVectorImpl<llvm::Value *> &) {}
1187
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001188void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001189 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001190 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001191 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001192 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001193 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1194 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001195 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001196 // propagation master's thread values of threadprivate variables to local
1197 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001198 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1199 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1200 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001201 }
1202 CGF.EmitOMPPrivateClause(S, PrivateScope);
1203 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1204 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001205 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001206 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001207 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001208 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1209 emitEmptyBoundParameters);
Alexey Bataev61205072016-03-02 04:57:40 +00001210 emitPostUpdateForReductionClause(
1211 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001212}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001213
Alexey Bataev0f34da12015-07-02 04:17:07 +00001214void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1215 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001216 RunCleanupsScope BodyScope(*this);
1217 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001218 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001219 EmitIgnoredExpr(I);
1220 }
Alexander Musman3276a272015-03-21 10:12:56 +00001221 // Update the linear variables.
Alexey Bataev617db5f2017-12-04 15:38:33 +00001222 // In distribute directives only loop counters may be marked as linear, no
1223 // need to generate the code for them.
1224 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1225 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1226 for (auto *U : C->updates())
1227 EmitIgnoredExpr(U);
1228 }
Alexander Musman3276a272015-03-21 10:12:56 +00001229 }
1230
Alexander Musmana5f070a2014-10-01 06:03:56 +00001231 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001232 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001233 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001234 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001235 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001236 // The end (updates/cleanups).
1237 EmitBlock(Continue.getBlock());
1238 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001239}
1240
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001241void CodeGenFunction::EmitOMPInnerLoop(
1242 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1243 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001244 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1245 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001246 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001247
1248 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001249 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001250 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001251 const SourceRange &R = S.getSourceRange();
1252 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1253 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001254
1255 // If there are any cleanups between here and the loop-exit scope,
1256 // create a block to stage a loop exit along.
1257 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001258 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001259 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001260
Alexander Musmand196ef22014-10-07 08:57:09 +00001261 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001262
Alexey Bataev2df54a02015-03-12 08:53:29 +00001263 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001264 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001265 if (ExitBlock != LoopExit.getBlock()) {
1266 EmitBlock(ExitBlock);
1267 EmitBranchThroughCleanup(LoopExit);
1268 }
1269
1270 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001271 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001272
1273 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001274 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001275 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1276
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001277 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001278
1279 // Emit "IV = IV + 1" and a back-edge to the condition block.
1280 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001281 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001282 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001283 BreakContinueStack.pop_back();
1284 EmitBranch(CondBlock);
1285 LoopStack.pop();
1286 // Emit the fall-through block.
1287 EmitBlock(LoopExit.getBlock());
1288}
1289
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001290bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001291 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001292 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001293 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001294 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001295 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001296 for (auto *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001297 HasLinears = true;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001298 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001299 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1300 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1301 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1302 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1303 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1304 VD->getInit()->getType(), VK_LValue,
1305 VD->getInit()->getExprLoc());
1306 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1307 VD->getType()),
1308 /*capturedByInit=*/false);
1309 EmitAutoVarCleanups(Emission);
1310 } else
1311 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001312 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001313 // Emit the linear steps for the linear clauses.
1314 // If a step is not constant, it is pre-calculated before the loop.
1315 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1316 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001317 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001318 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001319 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001320 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001321 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001322 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001323}
1324
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001325void CodeGenFunction::EmitOMPLinearClauseFinal(
1326 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001327 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001328 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001329 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001330 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001331 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001332 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001333 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001334 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001335 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001336 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001337 // If the first post-update expression is found, emit conditional
1338 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001339 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1340 DoneBB = createBasicBlock(".omp.linear.pu.done");
1341 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1342 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001343 }
1344 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001345 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1346 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001347 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001348 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001349 Address OrigAddr = EmitLValue(&DRE).getAddress();
1350 CodeGenFunction::OMPPrivateScope VarScope(*this);
1351 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001352 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001353 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001354 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001355 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001356 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001357 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001358 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001359 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001360 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001361}
1362
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001363static void emitAlignedClause(CodeGenFunction &CGF,
1364 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001365 if (!CGF.HaveInsertPoint())
1366 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001367 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001368 unsigned ClauseAlignment = 0;
1369 if (auto AlignmentExpr = Clause->getAlignment()) {
1370 auto AlignmentCI =
1371 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1372 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001373 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001374 for (auto E : Clause->varlists()) {
1375 unsigned Alignment = ClauseAlignment;
1376 if (Alignment == 0) {
1377 // OpenMP [2.8.1, Description]
1378 // If no optional parameter is specified, implementation-defined default
1379 // alignments for SIMD instructions on the target platforms are assumed.
1380 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001381 CGF.getContext()
1382 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1383 E->getType()->getPointeeType()))
1384 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001385 }
1386 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1387 "alignment is not power of 2");
1388 if (Alignment != 0) {
1389 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1390 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1391 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001392 }
1393 }
1394}
1395
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001396void CodeGenFunction::EmitOMPPrivateLoopCounters(
1397 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1398 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001399 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001400 auto I = S.private_counters().begin();
1401 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001402 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1403 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001404 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001405 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001406 if (!LocalDeclMap.count(PrivateVD)) {
1407 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1408 EmitAutoVarCleanups(VarEmission);
1409 }
1410 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1411 /*RefersToEnclosingVariableOrCapture=*/false,
1412 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1413 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001414 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001415 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1416 VD->hasGlobalStorage()) {
1417 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1418 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1419 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1420 E->getType(), VK_LValue, E->getExprLoc());
1421 return EmitLValue(&DRE).getAddress();
1422 });
1423 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001424 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001425 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001426}
1427
Alexey Bataev62dbb972015-04-22 11:59:37 +00001428static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1429 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1430 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001431 if (!CGF.HaveInsertPoint())
1432 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001433 {
1434 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001435 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001436 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001437 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001438 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001439 CGF.EmitIgnoredExpr(I);
1440 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001441 }
1442 // Check that loop is executed at least one time.
1443 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1444}
1445
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001446void CodeGenFunction::EmitOMPLinearClause(
1447 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1448 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001449 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001450 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1451 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1452 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1453 for (auto *C : LoopDirective->counters()) {
1454 SIMDLCVs.insert(
1455 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1456 }
1457 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001458 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001459 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001460 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001461 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1462 auto *PrivateVD =
1463 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001464 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1465 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1466 // Emit private VarDecl with copy init.
1467 EmitVarDecl(*PrivateVD);
1468 return GetAddrOfLocalVar(PrivateVD);
1469 });
1470 assert(IsRegistered && "linear var already registered as private");
1471 // Silence the warning about unused variable.
1472 (void)IsRegistered;
1473 } else
1474 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001475 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001476 }
1477 }
1478}
1479
Alexey Bataev45bfad52015-08-21 12:19:04 +00001480static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001481 const OMPExecutableDirective &D,
1482 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001483 if (!CGF.HaveInsertPoint())
1484 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001485 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001486 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1487 /*ignoreResult=*/true);
1488 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1489 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1490 // In presence of finite 'safelen', it may be unsafe to mark all
1491 // the memory instructions parallel, because loop-carried
1492 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001493 if (!IsMonotonic)
1494 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001495 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001496 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1497 /*ignoreResult=*/true);
1498 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001499 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001500 // In presence of finite 'safelen', it may be unsafe to mark all
1501 // the memory instructions parallel, because loop-carried
1502 // dependences of 'safelen' iterations are possible.
1503 CGF.LoopStack.setParallel(false);
1504 }
1505}
1506
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001507void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1508 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001509 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001510 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001511 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001512 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001513}
1514
Alexey Bataevef549a82016-03-09 09:49:09 +00001515void CodeGenFunction::EmitOMPSimdFinal(
1516 const OMPLoopDirective &D,
1517 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001518 if (!HaveInsertPoint())
1519 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001520 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001521 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001522 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001523 for (auto F : D.finals()) {
1524 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001525 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1526 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1527 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1528 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001529 if (!DoneBB) {
1530 if (auto *Cond = CondGen(*this)) {
1531 // If the first post-update expression is found, emit conditional
1532 // block if it was requested.
1533 auto *ThenBB = createBasicBlock(".omp.final.then");
1534 DoneBB = createBasicBlock(".omp.final.done");
1535 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1536 EmitBlock(ThenBB);
1537 }
1538 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001539 Address OrigAddr = Address::invalid();
1540 if (CED)
1541 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1542 else {
1543 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1544 /*RefersToEnclosingVariableOrCapture=*/false,
1545 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1546 OrigAddr = EmitLValue(&DRE).getAddress();
1547 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001548 OMPPrivateScope VarScope(*this);
1549 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001550 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001551 (void)VarScope.Privatize();
1552 EmitIgnoredExpr(F);
1553 }
1554 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001555 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001556 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001557 if (DoneBB)
1558 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001559}
1560
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001561static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1562 const OMPLoopDirective &S,
1563 CodeGenFunction::JumpDest LoopExit) {
1564 CGF.EmitOMPLoopBody(S, LoopExit);
1565 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001566}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001567
Alexey Bataevf8365372017-11-17 17:57:25 +00001568static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1569 PrePostActionTy &Action) {
1570 Action.Enter(CGF);
1571 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1572 "Expected simd directive");
1573 OMPLoopScope PreInitScope(CGF, S);
1574 // if (PreCond) {
1575 // for (IV in 0..LastIteration) BODY;
1576 // <Final counter/linear vars updates>;
1577 // }
1578 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001579
Alexey Bataevf8365372017-11-17 17:57:25 +00001580 // Emit: if (PreCond) - begin.
1581 // If the condition constant folds and can be elided, avoid emitting the
1582 // whole loop.
1583 bool CondConstant;
1584 llvm::BasicBlock *ContBlock = nullptr;
1585 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1586 if (!CondConstant)
1587 return;
1588 } else {
1589 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1590 ContBlock = CGF.createBasicBlock("simd.if.end");
1591 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1592 CGF.getProfileCount(&S));
1593 CGF.EmitBlock(ThenBlock);
1594 CGF.incrementProfileCounter(&S);
1595 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001596
Alexey Bataevf8365372017-11-17 17:57:25 +00001597 // Emit the loop iteration variable.
1598 const Expr *IVExpr = S.getIterationVariable();
1599 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1600 CGF.EmitVarDecl(*IVDecl);
1601 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001602
Alexey Bataevf8365372017-11-17 17:57:25 +00001603 // Emit the iterations count variable.
1604 // If it is not a variable, Sema decided to calculate iterations count on
1605 // each iteration (e.g., it is foldable into a constant).
1606 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1607 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1608 // Emit calculation of the iterations count.
1609 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1610 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001611
Alexey Bataevf8365372017-11-17 17:57:25 +00001612 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001613
Alexey Bataevf8365372017-11-17 17:57:25 +00001614 emitAlignedClause(CGF, S);
1615 (void)CGF.EmitOMPLinearClauseInit(S);
1616 {
1617 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1618 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1619 CGF.EmitOMPLinearClause(S, LoopScope);
1620 CGF.EmitOMPPrivateClause(S, LoopScope);
1621 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1622 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1623 (void)LoopScope.Privatize();
1624 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1625 S.getInc(),
1626 [&S](CodeGenFunction &CGF) {
1627 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1628 CGF.EmitStopPoint(&S);
1629 },
1630 [](CodeGenFunction &) {});
1631 CGF.EmitOMPSimdFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001632 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001633 // Emit final copy of the lastprivate variables at the end of loops.
1634 if (HasLastprivateClause)
1635 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1636 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
1637 emitPostUpdateForReductionClause(
1638 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1639 }
1640 CGF.EmitOMPLinearClauseFinal(
1641 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1642 // Emit: if (PreCond) - end.
1643 if (ContBlock) {
1644 CGF.EmitBranch(ContBlock);
1645 CGF.EmitBlock(ContBlock, true);
1646 }
1647}
1648
1649void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1650 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1651 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001652 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00001653 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001654 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001655}
1656
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001657void CodeGenFunction::EmitOMPOuterLoop(
1658 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1659 CodeGenFunction::OMPPrivateScope &LoopScope,
1660 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1661 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1662 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001663 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001664
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001665 const Expr *IVExpr = S.getIterationVariable();
1666 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1667 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1668
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001669 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1670
1671 // Start the loop with a block that tests the condition.
1672 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1673 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001674 const SourceRange &R = S.getSourceRange();
1675 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1676 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001677
1678 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001679 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001680 // UB = min(UB, GlobalUB) or
1681 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1682 // 'distribute parallel for')
1683 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001684 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001685 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001686 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001687 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001688 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001689 BoolCondVal =
1690 RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1691 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001692 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001693
1694 // If there are any cleanups between here and the loop-exit scope,
1695 // create a block to stage a loop exit along.
1696 auto ExitBlock = LoopExit.getBlock();
1697 if (LoopScope.requiresCleanups())
1698 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1699
1700 auto LoopBody = createBasicBlock("omp.dispatch.body");
1701 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1702 if (ExitBlock != LoopExit.getBlock()) {
1703 EmitBlock(ExitBlock);
1704 EmitBranchThroughCleanup(LoopExit);
1705 }
1706 EmitBlock(LoopBody);
1707
Alexander Musman92bdaab2015-03-12 13:37:50 +00001708 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1709 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001710 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001711 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001712
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001713 // Create a block for the increment.
1714 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1715 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1716
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001717 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1718 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001719 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1720 LoopStack.setParallel(!IsMonotonic);
1721 else
1722 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001723
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001724 SourceLocation Loc = S.getLocStart();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001725
1726 // when 'distribute' is not combined with a 'for':
1727 // while (idx <= UB) { BODY; ++idx; }
1728 // when 'distribute' is combined with a 'for'
1729 // (e.g. 'distribute parallel for')
1730 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1731 EmitOMPInnerLoop(
1732 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1733 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1734 CodeGenLoop(CGF, S, LoopExit);
1735 },
1736 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1737 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1738 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001739
1740 EmitBlock(Continue.getBlock());
1741 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001742 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001743 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001744 EmitIgnoredExpr(LoopArgs.NextLB);
1745 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001746 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001747
1748 EmitBranch(CondBlock);
1749 LoopStack.pop();
1750 // Emit the fall-through block.
1751 EmitBlock(LoopExit.getBlock());
1752
1753 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001754 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1755 if (!DynamicOrOrdered)
Alexey Bataevf43f7142017-09-06 16:17:35 +00001756 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
1757 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00001758 };
1759 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001760}
1761
1762void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001763 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001764 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001765 const OMPLoopArguments &LoopArgs,
1766 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001767 auto &RT = CGM.getOpenMPRuntime();
1768
1769 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001770 const bool DynamicOrOrdered =
1771 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001772
1773 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001774 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001775 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001776 "static non-chunked schedule does not need outer loop");
1777
1778 // Emit outer loop.
1779 //
1780 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1781 // When schedule(dynamic,chunk_size) is specified, the iterations are
1782 // distributed to threads in the team in chunks as the threads request them.
1783 // Each thread executes a chunk of iterations, then requests another chunk,
1784 // until no chunks remain to be distributed. Each chunk contains chunk_size
1785 // iterations, except for the last chunk to be distributed, which may have
1786 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1787 //
1788 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1789 // to threads in the team in chunks as the executing threads request them.
1790 // Each thread executes a chunk of iterations, then requests another chunk,
1791 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1792 // each chunk is proportional to the number of unassigned iterations divided
1793 // by the number of threads in the team, decreasing to 1. For a chunk_size
1794 // with value k (greater than 1), the size of each chunk is determined in the
1795 // same way, with the restriction that the chunks do not contain fewer than k
1796 // iterations (except for the last chunk to be assigned, which may have fewer
1797 // than k iterations).
1798 //
1799 // When schedule(auto) is specified, the decision regarding scheduling is
1800 // delegated to the compiler and/or runtime system. The programmer gives the
1801 // implementation the freedom to choose any possible mapping of iterations to
1802 // threads in the team.
1803 //
1804 // When schedule(runtime) is specified, the decision regarding scheduling is
1805 // deferred until run time, and the schedule and chunk size are taken from the
1806 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1807 // implementation defined
1808 //
1809 // while(__kmpc_dispatch_next(&LB, &UB)) {
1810 // idx = LB;
1811 // while (idx <= UB) { BODY; ++idx;
1812 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1813 // } // inner loop
1814 // }
1815 //
1816 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1817 // When schedule(static, chunk_size) is specified, iterations are divided into
1818 // chunks of size chunk_size, and the chunks are assigned to the threads in
1819 // the team in a round-robin fashion in the order of the thread number.
1820 //
1821 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1822 // while (idx <= UB) { BODY; ++idx; } // inner loop
1823 // LB = LB + ST;
1824 // UB = UB + ST;
1825 // }
1826 //
1827
1828 const Expr *IVExpr = S.getIterationVariable();
1829 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1830 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1831
1832 if (DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001833 auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1834 llvm::Value *LBVal = DispatchBounds.first;
1835 llvm::Value *UBVal = DispatchBounds.second;
1836 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1837 LoopArgs.Chunk};
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001838 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001839 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001840 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001841 CGOpenMPRuntime::StaticRTInput StaticInit(
1842 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1843 LoopArgs.ST, LoopArgs.Chunk);
1844 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
1845 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001846 }
1847
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001848 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1849 const unsigned IVSize,
1850 const bool IVSigned) {
1851 if (Ordered) {
1852 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1853 IVSigned);
1854 }
1855 };
1856
1857 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1858 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1859 OuterLoopArgs.IncExpr = S.getInc();
1860 OuterLoopArgs.Init = S.getInit();
1861 OuterLoopArgs.Cond = S.getCond();
1862 OuterLoopArgs.NextLB = S.getNextLowerBound();
1863 OuterLoopArgs.NextUB = S.getNextUpperBound();
1864 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1865 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001866}
1867
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001868static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1869 const unsigned IVSize, const bool IVSigned) {}
1870
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001871void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001872 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1873 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1874 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001875
1876 auto &RT = CGM.getOpenMPRuntime();
1877
1878 // Emit outer loop.
1879 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1880 // dynamic
1881 //
1882
1883 const Expr *IVExpr = S.getIterationVariable();
1884 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1885 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1886
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001887 CGOpenMPRuntime::StaticRTInput StaticInit(
1888 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
1889 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
1890 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001891
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001892 // for combined 'distribute' and 'for' the increment expression of distribute
1893 // is store in DistInc. For 'distribute' alone, it is in Inc.
1894 Expr *IncExpr;
1895 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1896 IncExpr = S.getDistInc();
1897 else
1898 IncExpr = S.getInc();
1899
1900 // this routine is shared by 'omp distribute parallel for' and
1901 // 'omp distribute': select the right EUB expression depending on the
1902 // directive
1903 OMPLoopArguments OuterLoopArgs;
1904 OuterLoopArgs.LB = LoopArgs.LB;
1905 OuterLoopArgs.UB = LoopArgs.UB;
1906 OuterLoopArgs.ST = LoopArgs.ST;
1907 OuterLoopArgs.IL = LoopArgs.IL;
1908 OuterLoopArgs.Chunk = LoopArgs.Chunk;
1909 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1910 ? S.getCombinedEnsureUpperBound()
1911 : S.getEnsureUpperBound();
1912 OuterLoopArgs.IncExpr = IncExpr;
1913 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1914 ? S.getCombinedInit()
1915 : S.getInit();
1916 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1917 ? S.getCombinedCond()
1918 : S.getCond();
1919 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1920 ? S.getCombinedNextLowerBound()
1921 : S.getNextLowerBound();
1922 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1923 ? S.getCombinedNextUpperBound()
1924 : S.getNextUpperBound();
1925
1926 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
1927 LoopScope, OuterLoopArgs, CodeGenLoopContent,
1928 emitEmptyOrdered);
1929}
1930
1931/// Emit a helper variable and return corresponding lvalue.
1932static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1933 const DeclRefExpr *Helper) {
1934 auto VDecl = cast<VarDecl>(Helper->getDecl());
1935 CGF.EmitVarDecl(*VDecl);
1936 return CGF.EmitLValue(Helper);
1937}
1938
1939static std::pair<LValue, LValue>
1940emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
1941 const OMPExecutableDirective &S) {
1942 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1943 LValue LB =
1944 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
1945 LValue UB =
1946 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
1947
1948 // When composing 'distribute' with 'for' (e.g. as in 'distribute
1949 // parallel for') we need to use the 'distribute'
1950 // chunk lower and upper bounds rather than the whole loop iteration
1951 // space. These are parameters to the outlined function for 'parallel'
1952 // and we copy the bounds of the previous schedule into the
1953 // the current ones.
1954 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
1955 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
1956 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(PrevLB, SourceLocation());
1957 PrevLBVal = CGF.EmitScalarConversion(
1958 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
1959 LS.getIterationVariable()->getType(), SourceLocation());
1960 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(PrevUB, SourceLocation());
1961 PrevUBVal = CGF.EmitScalarConversion(
1962 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
1963 LS.getIterationVariable()->getType(), SourceLocation());
1964
1965 CGF.EmitStoreOfScalar(PrevLBVal, LB);
1966 CGF.EmitStoreOfScalar(PrevUBVal, UB);
1967
1968 return {LB, UB};
1969}
1970
1971/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
1972/// we need to use the LB and UB expressions generated by the worksharing
1973/// code generation support, whereas in non combined situations we would
1974/// just emit 0 and the LastIteration expression
1975/// This function is necessary due to the difference of the LB and UB
1976/// types for the RT emission routines for 'for_static_init' and
1977/// 'for_dispatch_init'
1978static std::pair<llvm::Value *, llvm::Value *>
1979emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
1980 const OMPExecutableDirective &S,
1981 Address LB, Address UB) {
1982 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1983 const Expr *IVExpr = LS.getIterationVariable();
1984 // when implementing a dynamic schedule for a 'for' combined with a
1985 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
1986 // is not normalized as each team only executes its own assigned
1987 // distribute chunk
1988 QualType IteratorTy = IVExpr->getType();
1989 llvm::Value *LBVal = CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy,
1990 SourceLocation());
1991 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy,
1992 SourceLocation());
1993 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00001994}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001995
1996static void emitDistributeParallelForDistributeInnerBoundParams(
1997 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1998 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
1999 const auto &Dir = cast<OMPLoopDirective>(S);
2000 LValue LB =
2001 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
2002 auto LBCast = CGF.Builder.CreateIntCast(
2003 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2004 CapturedVars.push_back(LBCast);
2005 LValue UB =
2006 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2007
2008 auto UBCast = CGF.Builder.CreateIntCast(
2009 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2010 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00002011}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002012
2013static void
2014emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2015 const OMPLoopDirective &S,
2016 CodeGenFunction::JumpDest LoopExit) {
2017 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
2018 PrePostActionTy &) {
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002019 bool HasCancel = false;
2020 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2021 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2022 HasCancel = D->hasCancel();
2023 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2024 HasCancel = D->hasCancel();
Alexey Bataev16e79882017-11-22 21:12:03 +00002025 else if (const auto *D =
2026 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2027 HasCancel = D->hasCancel();
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002028 }
2029 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2030 HasCancel);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002031 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2032 emitDistributeParallelForInnerBounds,
2033 emitDistributeParallelForDispatchBounds);
2034 };
2035
2036 emitCommonOMPParallelDirective(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002037 CGF, S,
2038 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2039 CGInlinedWorksharingLoop,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002040 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002041}
2042
Carlo Bertolli9925f152016-06-27 14:55:37 +00002043void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2044 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002045 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2046 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2047 S.getDistInc());
2048 };
Carlo Bertolli9925f152016-06-27 14:55:37 +00002049 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev10a54312017-11-27 16:54:08 +00002050 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002051}
2052
Kelvin Li4a39add2016-07-05 05:00:15 +00002053void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2054 const OMPDistributeParallelForSimdDirective &S) {
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002055 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2056 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2057 S.getDistInc());
2058 };
Kelvin Li4a39add2016-07-05 05:00:15 +00002059 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002060 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Kelvin Li4a39add2016-07-05 05:00:15 +00002061}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002062
2063void CodeGenFunction::EmitOMPDistributeSimdDirective(
2064 const OMPDistributeSimdDirective &S) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00002065 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2066 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2067 };
Kelvin Li787f3fc2016-07-06 04:45:38 +00002068 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev617db5f2017-12-04 15:38:33 +00002069 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002070}
2071
Alexey Bataevf8365372017-11-17 17:57:25 +00002072void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2073 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2074 // Emit SPMD target parallel for region as a standalone region.
2075 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2076 emitOMPSimdRegion(CGF, S, Action);
2077 };
2078 llvm::Function *Fn;
2079 llvm::Constant *Addr;
2080 // Emit target region as a standalone region.
2081 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2082 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2083 assert(Fn && Addr && "Target device function emission failed.");
2084}
2085
Kelvin Li986330c2016-07-20 22:57:10 +00002086void CodeGenFunction::EmitOMPTargetSimdDirective(
2087 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002088 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2089 emitOMPSimdRegion(CGF, S, Action);
2090 };
2091 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002092}
2093
Kelvin Li80e8f562016-12-29 22:16:30 +00002094void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
2095 const OMPTargetTeamsDistributeParallelForDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002096 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Li80e8f562016-12-29 22:16:30 +00002097 CGM.getOpenMPRuntime().emitInlinedDirective(
2098 *this, OMPD_target_teams_distribute_parallel_for,
2099 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2100 CGF.EmitStmt(
2101 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2102 });
2103}
2104
Kelvin Li1851df52017-01-03 05:23:48 +00002105void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2106 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002107 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Li1851df52017-01-03 05:23:48 +00002108 CGM.getOpenMPRuntime().emitInlinedDirective(
2109 *this, OMPD_target_teams_distribute_parallel_for_simd,
2110 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2111 CGF.EmitStmt(
2112 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2113 });
2114}
2115
Kelvin Lida681182017-01-10 18:08:18 +00002116void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
2117 const OMPTargetTeamsDistributeSimdDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002118 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Lida681182017-01-10 18:08:18 +00002119 CGM.getOpenMPRuntime().emitInlinedDirective(
2120 *this, OMPD_target_teams_distribute_simd,
2121 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2122 CGF.EmitStmt(
2123 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2124 });
2125}
2126
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002127namespace {
2128 struct ScheduleKindModifiersTy {
2129 OpenMPScheduleClauseKind Kind;
2130 OpenMPScheduleClauseModifier M1;
2131 OpenMPScheduleClauseModifier M2;
2132 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2133 OpenMPScheduleClauseModifier M1,
2134 OpenMPScheduleClauseModifier M2)
2135 : Kind(Kind), M1(M1), M2(M2) {}
2136 };
2137} // namespace
2138
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002139bool CodeGenFunction::EmitOMPWorksharingLoop(
2140 const OMPLoopDirective &S, Expr *EUB,
2141 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2142 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002143 // Emit the loop iteration variable.
2144 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2145 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2146 EmitVarDecl(*IVDecl);
2147
2148 // Emit the iterations count variable.
2149 // If it is not a variable, Sema decided to calculate iterations count on each
2150 // iteration (e.g., it is foldable into a constant).
2151 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2152 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2153 // Emit calculation of the iterations count.
2154 EmitIgnoredExpr(S.getCalcLastIteration());
2155 }
2156
2157 auto &RT = CGM.getOpenMPRuntime();
2158
Alexey Bataev38e89532015-04-16 04:54:05 +00002159 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002160 // Check pre-condition.
2161 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002162 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002163 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002164 // If the condition constant folds and can be elided, avoid emitting the
2165 // whole loop.
2166 bool CondConstant;
2167 llvm::BasicBlock *ContBlock = nullptr;
2168 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2169 if (!CondConstant)
2170 return false;
2171 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002172 auto *ThenBlock = createBasicBlock("omp.precond.then");
2173 ContBlock = createBasicBlock("omp.precond.end");
2174 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002175 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002176 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002177 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002178 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002179
Alexey Bataev8b427062016-05-25 12:36:08 +00002180 bool Ordered = false;
2181 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2182 if (OrderedClause->getNumForLoops())
2183 RT.emitDoacrossInit(*this, S);
2184 else
2185 Ordered = true;
2186 }
2187
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002188 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002189 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002190 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002191 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002192
2193 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2194 LValue LB = Bounds.first;
2195 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002196 LValue ST =
2197 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2198 LValue IL =
2199 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2200
Alexander Musmanc6388682014-12-15 07:07:06 +00002201 // Emit 'then' code.
2202 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002203 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002204 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002205 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002206 // initialization of firstprivate variables and post-update of
2207 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002208 CGM.getOpenMPRuntime().emitBarrierCall(
2209 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2210 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002211 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002212 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002213 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002214 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002215 EmitOMPPrivateLoopCounters(S, LoopScope);
2216 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002217 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002218
2219 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002220 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002221 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002222 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002223 ScheduleKind.Schedule = C->getScheduleKind();
2224 ScheduleKind.M1 = C->getFirstScheduleModifier();
2225 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002226 if (const auto *Ch = C->getChunkSize()) {
2227 Chunk = EmitScalarExpr(Ch);
2228 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2229 S.getIterationVariable()->getType(),
2230 S.getLocStart());
2231 }
2232 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002233 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2234 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002235 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2236 // If the static schedule kind is specified or if the ordered clause is
2237 // specified, and if no monotonic modifier is specified, the effect will
2238 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002239 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002240 /* Chunked */ Chunk != nullptr) &&
2241 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002242 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2243 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002244 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2245 // When no chunk_size is specified, the iteration space is divided into
2246 // chunks that are approximately equal in size, and at most one chunk is
2247 // distributed to each thread. Note that the size of the chunks is
2248 // unspecified in this case.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002249 CGOpenMPRuntime::StaticRTInput StaticInit(
2250 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
2251 UB.getAddress(), ST.getAddress());
2252 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
2253 ScheduleKind, StaticInit);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002254 auto LoopExit =
2255 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002256 // UB = min(UB, GlobalUB);
2257 EmitIgnoredExpr(S.getEnsureUpperBound());
2258 // IV = LB;
2259 EmitIgnoredExpr(S.getInit());
2260 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002261 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2262 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002263 [&S, LoopExit](CodeGenFunction &CGF) {
2264 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002265 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002266 },
2267 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002268 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002269 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002270 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002271 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2272 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002273 };
2274 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002275 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002276 const bool IsMonotonic =
2277 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2278 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2279 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2280 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002281 // Emit the outer loop, which requests its work chunk [LB..UB] from
2282 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002283 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2284 ST.getAddress(), IL.getAddress(),
2285 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002286 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002287 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002288 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002289 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2290 EmitOMPSimdFinal(S,
2291 [&](CodeGenFunction &CGF) -> llvm::Value * {
2292 return CGF.Builder.CreateIsNotNull(
2293 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2294 });
2295 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002296 EmitOMPReductionClauseFinal(
2297 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2298 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2299 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002300 // Emit post-update of the reduction variables if IsLastIter != 0.
2301 emitPostUpdateForReductionClause(
2302 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2303 return CGF.Builder.CreateIsNotNull(
2304 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2305 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002306 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2307 if (HasLastprivateClause)
2308 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002309 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2310 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002311 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002312 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002313 return CGF.Builder.CreateIsNotNull(
2314 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2315 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002316 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002317 if (ContBlock) {
2318 EmitBranch(ContBlock);
2319 EmitBlock(ContBlock, true);
2320 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002321 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002322 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002323}
2324
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002325/// The following two functions generate expressions for the loop lower
2326/// and upper bounds in case of static and dynamic (dispatch) schedule
2327/// of the associated 'for' or 'distribute' loop.
2328static std::pair<LValue, LValue>
2329emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2330 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2331 LValue LB =
2332 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2333 LValue UB =
2334 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2335 return {LB, UB};
2336}
2337
2338/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2339/// consider the lower and upper bound expressions generated by the
2340/// worksharing loop support, but we use 0 and the iteration space size as
2341/// constants
2342static std::pair<llvm::Value *, llvm::Value *>
2343emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2344 Address LB, Address UB) {
2345 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2346 const Expr *IVExpr = LS.getIterationVariable();
2347 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2348 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2349 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2350 return {LBVal, UBVal};
2351}
2352
Alexander Musmanc6388682014-12-15 07:07:06 +00002353void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002354 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002355 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2356 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002357 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002358 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2359 emitForLoopBounds,
2360 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002361 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002362 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002363 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002364 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2365 S.hasCancel());
2366 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002367
2368 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002369 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002370 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2371 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002372}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002373
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002374void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002375 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002376 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2377 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002378 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2379 emitForLoopBounds,
2380 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002381 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002382 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002383 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002384 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2385 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002386
2387 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002388 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002389 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2390 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002391}
2392
Alexey Bataev2df54a02015-03-12 08:53:29 +00002393static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2394 const Twine &Name,
2395 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002396 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002397 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002398 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002399 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002400}
2401
Alexey Bataev3392d762016-02-16 11:18:12 +00002402void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00002403 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2404 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002405 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002406 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2407 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002408 auto &C = CGF.CGM.getContext();
2409 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2410 // Emit helper vars inits.
2411 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2412 CGF.Builder.getInt32(0));
2413 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2414 : CGF.Builder.getInt32(0);
2415 LValue UB =
2416 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2417 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2418 CGF.Builder.getInt32(1));
2419 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2420 CGF.Builder.getInt32(0));
2421 // Loop counter.
2422 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2423 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2424 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2425 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2426 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2427 // Generate condition for loop.
2428 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002429 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002430 // Increment for loop counter.
2431 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2432 S.getLocStart());
2433 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2434 // Iterate through all sections and emit a switch construct:
2435 // switch (IV) {
2436 // case 0:
2437 // <SectionStmt[0]>;
2438 // break;
2439 // ...
2440 // case <NumSection> - 1:
2441 // <SectionStmt[<NumSection> - 1]>;
2442 // break;
2443 // }
2444 // .omp.sections.exit:
2445 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2446 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2447 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2448 CS == nullptr ? 1 : CS->size());
2449 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002450 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002451 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002452 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2453 CGF.EmitBlock(CaseBB);
2454 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002455 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002456 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002457 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002458 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002459 } else {
2460 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2461 CGF.EmitBlock(CaseBB);
2462 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2463 CGF.EmitStmt(Stmt);
2464 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002465 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002466 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002467 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002468
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002469 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2470 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002471 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002472 // initialization of firstprivate variables and post-update of lastprivate
2473 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002474 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2475 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2476 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002477 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002478 CGF.EmitOMPPrivateClause(S, LoopScope);
2479 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2480 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2481 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002482
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002483 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002484 OpenMPScheduleTy ScheduleKind;
2485 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002486 CGOpenMPRuntime::StaticRTInput StaticInit(
2487 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2488 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002489 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002490 CGF, S.getLocStart(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002491 // UB = min(UB, GlobalUB);
2492 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2493 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2494 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2495 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2496 // IV = LB;
2497 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2498 // while (idx <= UB) { BODY; ++idx; }
2499 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2500 [](CodeGenFunction &) {});
2501 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002502 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002503 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2504 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002505 };
2506 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002507 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002508 // Emit post-update of the reduction variables if IsLastIter != 0.
2509 emitPostUpdateForReductionClause(
2510 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2511 return CGF.Builder.CreateIsNotNull(
2512 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2513 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002514
2515 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2516 if (HasLastprivates)
2517 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002518 S, /*NoFinals=*/false,
2519 CGF.Builder.CreateIsNotNull(
2520 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002521 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002522
2523 bool HasCancel = false;
2524 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2525 HasCancel = OSD->hasCancel();
2526 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2527 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002528 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002529 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2530 HasCancel);
2531 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2532 // clause. Otherwise the barrier will be generated by the codegen for the
2533 // directive.
2534 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002535 // Emit implicit barrier to synchronize threads and avoid data races on
2536 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002537 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2538 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002539 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002540}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002541
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002542void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002543 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002544 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002545 EmitSections(S);
2546 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002547 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002548 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002549 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2550 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002551 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002552}
2553
2554void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002555 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002556 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002557 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002558 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002559 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2560 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002561}
2562
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002563void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002564 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002565 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002566 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002567 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002568 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002569 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002570 // Build a list of copyprivate variables along with helper expressions
2571 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002572 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002573 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002574 DestExprs.append(C->destination_exprs().begin(),
2575 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002576 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002577 AssignmentOps.append(C->assignment_ops().begin(),
2578 C->assignment_ops().end());
2579 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002580 // Emit code for 'single' region along with 'copyprivate' clauses
2581 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2582 Action.Enter(CGF);
2583 OMPPrivateScope SingleScope(CGF);
2584 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2585 CGF.EmitOMPPrivateClause(S, SingleScope);
2586 (void)SingleScope.Privatize();
2587 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2588 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002589 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002590 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002591 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2592 CopyprivateVars, DestExprs,
2593 SrcExprs, AssignmentOps);
2594 }
2595 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2596 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002597 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002598 CGM.getOpenMPRuntime().emitBarrierCall(
2599 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002600 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002601 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002602}
2603
Alexey Bataev8d690652014-12-04 07:23:53 +00002604void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002605 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2606 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002607 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002608 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002609 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002610 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002611}
2612
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002613void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002614 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2615 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002616 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002617 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002618 Expr *Hint = nullptr;
2619 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2620 Hint = HintClause->getHint();
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002621 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002622 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2623 S.getDirectiveName().getAsString(),
2624 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002625}
2626
Alexey Bataev671605e2015-04-13 05:28:11 +00002627void CodeGenFunction::EmitOMPParallelForDirective(
2628 const OMPParallelForDirective &S) {
2629 // Emit directive as a combined directive that consists of two implicit
2630 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002631 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002632 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002633 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2634 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002635 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002636 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2637 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002638}
2639
Alexander Musmane4e893b2014-09-23 09:33:00 +00002640void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002641 const OMPParallelForSimdDirective &S) {
2642 // Emit directive as a combined directive that consists of two implicit
2643 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002644 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002645 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2646 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002647 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002648 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2649 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002650}
2651
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002652void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002653 const OMPParallelSectionsDirective &S) {
2654 // Emit directive as a combined directive that consists of two implicit
2655 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002656 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2657 CGF.EmitSections(S);
2658 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002659 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2660 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002661}
2662
Alexey Bataev7292c292016-04-25 12:22:29 +00002663void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2664 const RegionCodeGenTy &BodyGen,
2665 const TaskGenTy &TaskGen,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002666 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002667 // Emit outlined function for task construct.
2668 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002669 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002670 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002671 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002672 // Check if the task is final
2673 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2674 // If the condition constant folds and can be elided, try to avoid emitting
2675 // the condition and the dead arm of the if/else.
2676 auto *Cond = Clause->getCondition();
2677 bool CondConstant;
2678 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2679 Data.Final.setInt(CondConstant);
2680 else
2681 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2682 } else {
2683 // By default the task is not final.
2684 Data.Final.setInt(/*IntVal=*/false);
2685 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002686 // Check if the task has 'priority' clause.
2687 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002688 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002689 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002690 Data.Priority.setPointer(EmitScalarConversion(
2691 EmitScalarExpr(Prio), Prio->getType(),
2692 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2693 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002694 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002695 // The first function argument for tasks is a thread id, the second one is a
2696 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002697 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2698 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002699 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002700 auto IRef = C->varlist_begin();
2701 for (auto *IInit : C->private_copies()) {
2702 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2703 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002704 Data.PrivateVars.push_back(*IRef);
2705 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002706 }
2707 ++IRef;
2708 }
2709 }
2710 EmittedAsPrivate.clear();
2711 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002712 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002713 auto IRef = C->varlist_begin();
2714 auto IElemInitRef = C->inits().begin();
2715 for (auto *IInit : C->private_copies()) {
2716 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2717 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002718 Data.FirstprivateVars.push_back(*IRef);
2719 Data.FirstprivateCopies.push_back(IInit);
2720 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002721 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002722 ++IRef;
2723 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002724 }
2725 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002726 // Get list of lastprivate variables (for taskloops).
2727 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2728 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2729 auto IRef = C->varlist_begin();
2730 auto ID = C->destination_exprs().begin();
2731 for (auto *IInit : C->private_copies()) {
2732 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2733 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2734 Data.LastprivateVars.push_back(*IRef);
2735 Data.LastprivateCopies.push_back(IInit);
2736 }
2737 LastprivateDstsOrigs.insert(
2738 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2739 cast<DeclRefExpr>(*IRef)});
2740 ++IRef;
2741 ++ID;
2742 }
2743 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002744 SmallVector<const Expr *, 4> LHSs;
2745 SmallVector<const Expr *, 4> RHSs;
2746 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2747 auto IPriv = C->privates().begin();
2748 auto IRed = C->reduction_ops().begin();
2749 auto ILHS = C->lhs_exprs().begin();
2750 auto IRHS = C->rhs_exprs().begin();
2751 for (const auto *Ref : C->varlists()) {
2752 Data.ReductionVars.emplace_back(Ref);
2753 Data.ReductionCopies.emplace_back(*IPriv);
2754 Data.ReductionOps.emplace_back(*IRed);
2755 LHSs.emplace_back(*ILHS);
2756 RHSs.emplace_back(*IRHS);
2757 std::advance(IPriv, 1);
2758 std::advance(IRed, 1);
2759 std::advance(ILHS, 1);
2760 std::advance(IRHS, 1);
2761 }
2762 }
2763 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2764 *this, S.getLocStart(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002765 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002766 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2767 for (auto *IRef : C->varlists())
2768 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002769 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs](
Alexey Bataevf93095a2016-05-05 08:46:22 +00002770 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002771 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002772 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002773 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2774 !Data.LastprivateVars.empty()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00002775 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataev48591dd2016-04-20 04:01:36 +00002776 auto *CopyFn = CGF.Builder.CreateLoad(
2777 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2778 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2779 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2780 // Map privates.
2781 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2782 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2783 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002784 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002785 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2786 Address PrivatePtr = CGF.CreateMemTemp(
2787 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2788 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2789 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002790 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002791 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002792 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2793 Address PrivatePtr =
2794 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2795 ".firstpriv.ptr.addr");
2796 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2797 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002798 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002799 for (auto *E : Data.LastprivateVars) {
2800 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2801 Address PrivatePtr =
2802 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2803 ".lastpriv.ptr.addr");
2804 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2805 CallArgs.push_back(PrivatePtr.getPointer());
2806 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00002807 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
2808 CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002809 for (auto &&Pair : LastprivateDstsOrigs) {
2810 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2811 DeclRefExpr DRE(
2812 const_cast<VarDecl *>(OrigVD),
2813 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2814 OrigVD) != nullptr,
2815 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2816 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2817 return CGF.EmitLValue(&DRE).getAddress();
2818 });
2819 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002820 for (auto &&Pair : PrivatePtrs) {
2821 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2822 CGF.getContext().getDeclAlign(Pair.first));
2823 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2824 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002825 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002826 if (Data.Reductions) {
2827 OMPLexicalScope LexScope(CGF, S, /*AsInlined=*/true);
2828 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2829 Data.ReductionOps);
2830 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2831 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2832 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2833 RedCG.emitSharedLValue(CGF, Cnt);
2834 RedCG.emitAggregateType(CGF, Cnt);
2835 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2836 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2837 Replacement =
2838 Address(CGF.EmitScalarConversion(
2839 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2840 CGF.getContext().getPointerType(
2841 Data.ReductionCopies[Cnt]->getType()),
2842 SourceLocation()),
2843 Replacement.getAlignment());
2844 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2845 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2846 [Replacement]() { return Replacement; });
2847 // FIXME: This must removed once the runtime library is fixed.
2848 // Emit required threadprivate variables for
2849 // initilizer/combiner/finalizer.
2850 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2851 RedCG, Cnt);
2852 }
2853 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002854 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002855 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002856 SmallVector<const Expr *, 4> InRedVars;
2857 SmallVector<const Expr *, 4> InRedPrivs;
2858 SmallVector<const Expr *, 4> InRedOps;
2859 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2860 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2861 auto IPriv = C->privates().begin();
2862 auto IRed = C->reduction_ops().begin();
2863 auto ITD = C->taskgroup_descriptors().begin();
2864 for (const auto *Ref : C->varlists()) {
2865 InRedVars.emplace_back(Ref);
2866 InRedPrivs.emplace_back(*IPriv);
2867 InRedOps.emplace_back(*IRed);
2868 TaskgroupDescriptors.emplace_back(*ITD);
2869 std::advance(IPriv, 1);
2870 std::advance(IRed, 1);
2871 std::advance(ITD, 1);
2872 }
2873 }
2874 // Privatize in_reduction items here, because taskgroup descriptors must be
2875 // privatized earlier.
2876 OMPPrivateScope InRedScope(CGF);
2877 if (!InRedVars.empty()) {
2878 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2879 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2880 RedCG.emitSharedLValue(CGF, Cnt);
2881 RedCG.emitAggregateType(CGF, Cnt);
2882 // The taskgroup descriptor variable is always implicit firstprivate and
2883 // privatized already during procoessing of the firstprivates.
2884 llvm::Value *ReductionsPtr = CGF.EmitLoadOfScalar(
2885 CGF.EmitLValue(TaskgroupDescriptors[Cnt]), SourceLocation());
2886 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2887 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2888 Replacement = Address(
2889 CGF.EmitScalarConversion(
2890 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2891 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
2892 SourceLocation()),
2893 Replacement.getAlignment());
2894 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2895 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2896 [Replacement]() { return Replacement; });
2897 // FIXME: This must removed once the runtime library is fixed.
2898 // Emit required threadprivate variables for
2899 // initilizer/combiner/finalizer.
2900 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2901 RedCG, Cnt);
2902 }
2903 }
2904 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00002905
2906 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002907 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002908 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002909 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2910 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2911 Data.NumberOfParts);
2912 OMPLexicalScope Scope(*this, S);
2913 TaskGen(*this, OutlinedFn, Data);
2914}
2915
2916void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2917 // Emit outlined function for task construct.
2918 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2919 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002920 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002921 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002922 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2923 if (C->getNameModifier() == OMPD_unknown ||
2924 C->getNameModifier() == OMPD_task) {
2925 IfCond = C->getCondition();
2926 break;
2927 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002928 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002929
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002930 OMPTaskDataTy Data;
2931 // Check if we should emit tied or untied task.
2932 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00002933 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
2934 CGF.EmitStmt(CS->getCapturedStmt());
2935 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002936 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00002937 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002938 const OMPTaskDataTy &Data) {
2939 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
2940 SharedsTy, CapturedStruct, IfCond,
2941 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00002942 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002943 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002944}
2945
Alexey Bataev9f797f32015-02-05 05:57:51 +00002946void CodeGenFunction::EmitOMPTaskyieldDirective(
2947 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002948 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002949}
2950
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002951void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002952 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002953}
2954
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002955void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2956 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002957}
2958
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002959void CodeGenFunction::EmitOMPTaskgroupDirective(
2960 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002961 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2962 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002963 if (const Expr *E = S.getReductionRef()) {
2964 SmallVector<const Expr *, 4> LHSs;
2965 SmallVector<const Expr *, 4> RHSs;
2966 OMPTaskDataTy Data;
2967 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
2968 auto IPriv = C->privates().begin();
2969 auto IRed = C->reduction_ops().begin();
2970 auto ILHS = C->lhs_exprs().begin();
2971 auto IRHS = C->rhs_exprs().begin();
2972 for (const auto *Ref : C->varlists()) {
2973 Data.ReductionVars.emplace_back(Ref);
2974 Data.ReductionCopies.emplace_back(*IPriv);
2975 Data.ReductionOps.emplace_back(*IRed);
2976 LHSs.emplace_back(*ILHS);
2977 RHSs.emplace_back(*IRHS);
2978 std::advance(IPriv, 1);
2979 std::advance(IRed, 1);
2980 std::advance(ILHS, 1);
2981 std::advance(IRHS, 1);
2982 }
2983 }
2984 llvm::Value *ReductionDesc =
2985 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getLocStart(),
2986 LHSs, RHSs, Data);
2987 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2988 CGF.EmitVarDecl(*VD);
2989 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
2990 /*Volatile=*/false, E->getType());
2991 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002992 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002993 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002994 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002995 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2996}
2997
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002998void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002999 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003000 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003001 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3002 FlushClause->varlist_end());
3003 }
3004 return llvm::None;
3005 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00003006}
3007
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003008void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3009 const CodeGenLoopTy &CodeGenLoop,
3010 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003011 // Emit the loop iteration variable.
3012 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3013 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
3014 EmitVarDecl(*IVDecl);
3015
3016 // Emit the iterations count variable.
3017 // If it is not a variable, Sema decided to calculate iterations count on each
3018 // iteration (e.g., it is foldable into a constant).
3019 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3020 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3021 // Emit calculation of the iterations count.
3022 EmitIgnoredExpr(S.getCalcLastIteration());
3023 }
3024
3025 auto &RT = CGM.getOpenMPRuntime();
3026
Carlo Bertolli962bb802017-01-03 18:24:42 +00003027 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003028 // Check pre-condition.
3029 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003030 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003031 // Skip the entire loop if we don't meet the precondition.
3032 // If the condition constant folds and can be elided, avoid emitting the
3033 // whole loop.
3034 bool CondConstant;
3035 llvm::BasicBlock *ContBlock = nullptr;
3036 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3037 if (!CondConstant)
3038 return;
3039 } else {
3040 auto *ThenBlock = createBasicBlock("omp.precond.then");
3041 ContBlock = createBasicBlock("omp.precond.end");
3042 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3043 getProfileCount(&S));
3044 EmitBlock(ThenBlock);
3045 incrementProfileCounter(&S);
3046 }
3047
Alexey Bataev617db5f2017-12-04 15:38:33 +00003048 emitAlignedClause(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003049 // Emit 'then' code.
3050 {
3051 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003052
3053 LValue LB = EmitOMPHelperVar(
3054 *this, cast<DeclRefExpr>(
3055 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3056 ? S.getCombinedLowerBoundVariable()
3057 : S.getLowerBoundVariable())));
3058 LValue UB = EmitOMPHelperVar(
3059 *this, cast<DeclRefExpr>(
3060 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3061 ? S.getCombinedUpperBoundVariable()
3062 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003063 LValue ST =
3064 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3065 LValue IL =
3066 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3067
3068 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003069 if (EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003070 // Emit implicit barrier to synchronize threads and avoid data races
3071 // on initialization of firstprivate variables and post-update of
Carlo Bertolli962bb802017-01-03 18:24:42 +00003072 // lastprivate variables.
3073 CGM.getOpenMPRuntime().emitBarrierCall(
Alexey Bataev617db5f2017-12-04 15:38:33 +00003074 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3075 /*ForceSimpleCall=*/true);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003076 }
3077 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev617db5f2017-12-04 15:38:33 +00003078 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
Alexey Bataev999277a2017-12-06 14:31:09 +00003079 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3080 !isOpenMPTeamsDirective(S.getDirectiveKind()))
Alexey Bataev617db5f2017-12-04 15:38:33 +00003081 EmitOMPReductionClauseInit(S, LoopScope);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003082 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003083 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003084 (void)LoopScope.Privatize();
3085
3086 // Detect the distribute schedule kind and chunk.
3087 llvm::Value *Chunk = nullptr;
3088 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3089 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3090 ScheduleKind = C->getDistScheduleKind();
3091 if (const auto *Ch = C->getChunkSize()) {
3092 Chunk = EmitScalarExpr(Ch);
3093 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
Alexey Bataev617db5f2017-12-04 15:38:33 +00003094 S.getIterationVariable()->getType(),
3095 S.getLocStart());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003096 }
3097 }
3098 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3099 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3100
3101 // OpenMP [2.10.8, distribute Construct, Description]
3102 // If dist_schedule is specified, kind must be static. If specified,
3103 // iterations are divided into chunks of size chunk_size, chunks are
3104 // assigned to the teams of the league in a round-robin fashion in the
3105 // order of the team number. When no chunk_size is specified, the
3106 // iteration space is divided into chunks that are approximately equal
3107 // in size, and at most one chunk is distributed to each team of the
3108 // league. The size of the chunks is unspecified in this case.
3109 if (RT.isStaticNonchunked(ScheduleKind,
3110 /* Chunked */ Chunk != nullptr)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003111 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3112 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003113 CGOpenMPRuntime::StaticRTInput StaticInit(
3114 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3115 LB.getAddress(), UB.getAddress(), ST.getAddress());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003116 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003117 StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003118 auto LoopExit =
3119 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3120 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003121 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3122 ? S.getCombinedEnsureUpperBound()
3123 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003124 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003125 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3126 ? S.getCombinedInit()
3127 : S.getInit());
3128
3129 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3130 ? S.getCombinedCond()
3131 : S.getCond();
3132
3133 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003134 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003135 // when combined with 'for' (e.g. as in 'distribute parallel for')
3136 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3137 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3138 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3139 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003140 },
3141 [](CodeGenFunction &) {});
3142 EmitBlock(LoopExit.getBlock());
3143 // Tell the runtime we are done.
Alexey Bataevf43f7142017-09-06 16:17:35 +00003144 RT.emitForStaticFinish(*this, S.getLocStart(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003145 } else {
3146 // Emit the outer loop, which requests its work chunk [LB..UB] from
3147 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003148 const OMPLoopArguments LoopArguments = {
3149 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3150 Chunk};
3151 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3152 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003153 }
Alexey Bataev617db5f2017-12-04 15:38:33 +00003154 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3155 EmitOMPSimdFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3156 return CGF.Builder.CreateIsNotNull(
3157 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3158 });
3159 }
3160 OpenMPDirectiveKind ReductionKind = OMPD_unknown;
3161 if (isOpenMPParallelDirective(S.getDirectiveKind()) &&
3162 isOpenMPSimdDirective(S.getDirectiveKind())) {
3163 ReductionKind = OMPD_parallel_for_simd;
3164 } else if (isOpenMPParallelDirective(S.getDirectiveKind())) {
3165 ReductionKind = OMPD_parallel_for;
3166 } else if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3167 ReductionKind = OMPD_simd;
3168 } else if (!isOpenMPTeamsDirective(S.getDirectiveKind()) &&
3169 S.hasClausesOfKind<OMPReductionClause>()) {
3170 llvm_unreachable(
3171 "No reduction clauses is allowed in distribute directive.");
3172 }
3173 EmitOMPReductionClauseFinal(S, ReductionKind);
3174 // Emit post-update of the reduction variables if IsLastIter != 0.
3175 emitPostUpdateForReductionClause(
3176 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3177 return CGF.Builder.CreateIsNotNull(
3178 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3179 });
Carlo Bertolli962bb802017-01-03 18:24:42 +00003180 // Emit final copy of the lastprivate variables if IsLastIter != 0.
Alexey Bataev617db5f2017-12-04 15:38:33 +00003181 if (HasLastprivateClause) {
Carlo Bertolli962bb802017-01-03 18:24:42 +00003182 EmitOMPLastprivateClauseFinal(
3183 S, /*NoFinals=*/false,
Alexey Bataev617db5f2017-12-04 15:38:33 +00003184 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
3185 }
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003186 }
3187
3188 // We're now done with the loop, so jump to the continuation block.
3189 if (ContBlock) {
3190 EmitBranch(ContBlock);
3191 EmitBlock(ContBlock, true);
3192 }
3193 }
3194}
3195
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003196void CodeGenFunction::EmitOMPDistributeDirective(
3197 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003198 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003199
3200 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003201 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003202 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev10a54312017-11-27 16:54:08 +00003203 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003204}
3205
Alexey Bataev5f600d62015-09-29 03:48:57 +00003206static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3207 const CapturedStmt *S) {
3208 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3209 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3210 CGF.CapturedStmtInfo = &CapStmtInfo;
3211 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3212 Fn->addFnAttr(llvm::Attribute::NoInline);
3213 return Fn;
3214}
3215
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003216void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8b427062016-05-25 12:36:08 +00003217 if (!S.getAssociatedStmt()) {
3218 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3219 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003220 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003221 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003222 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003223 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3224 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003225 if (C) {
3226 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3227 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3228 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3229 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Alexey Bataev3c595a62017-08-14 15:01:03 +00003230 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3231 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003232 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003233 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003234 CGF.EmitStmt(
3235 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3236 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003237 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003238 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003239 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003240}
3241
Alexey Bataevb57056f2015-01-22 06:17:56 +00003242static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003243 QualType SrcType, QualType DestType,
3244 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003245 assert(CGF.hasScalarEvaluationKind(DestType) &&
3246 "DestType must have scalar evaluation kind.");
3247 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3248 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003249 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3250 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00003251 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003252 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003253}
3254
3255static CodeGenFunction::ComplexPairTy
3256convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003257 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003258 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3259 "DestType must have complex evaluation kind.");
3260 CodeGenFunction::ComplexPairTy ComplexVal;
3261 if (Val.isScalar()) {
3262 // Convert the input element to the element type of the complex.
3263 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003264 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3265 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003266 ComplexVal = CodeGenFunction::ComplexPairTy(
3267 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3268 } else {
3269 assert(Val.isComplex() && "Must be a scalar or complex.");
3270 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3271 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3272 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003273 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003274 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003275 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003276 }
3277 return ComplexVal;
3278}
3279
Alexey Bataev5e018f92015-04-23 06:35:10 +00003280static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3281 LValue LVal, RValue RVal) {
3282 if (LVal.isGlobalReg()) {
3283 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3284 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003285 CGF.EmitAtomicStore(RVal, LVal,
3286 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3287 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003288 LVal.isVolatile(), /*IsInit=*/false);
3289 }
3290}
3291
Alexey Bataev8524d152016-01-21 12:35:58 +00003292void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3293 QualType RValTy, SourceLocation Loc) {
3294 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003295 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003296 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3297 *this, RVal, RValTy, LVal.getType(), Loc)),
3298 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003299 break;
3300 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003301 EmitStoreOfComplex(
3302 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003303 /*isInit=*/false);
3304 break;
3305 case TEK_Aggregate:
3306 llvm_unreachable("Must be a scalar or complex.");
3307 }
3308}
3309
Alexey Bataevb57056f2015-01-22 06:17:56 +00003310static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3311 const Expr *X, const Expr *V,
3312 SourceLocation Loc) {
3313 // v = x;
3314 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3315 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3316 LValue XLValue = CGF.EmitLValue(X);
3317 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003318 RValue Res = XLValue.isGlobalReg()
3319 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003320 : CGF.EmitAtomicLoad(
3321 XLValue, Loc,
3322 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3323 : llvm::AtomicOrdering::Monotonic,
3324 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003325 // OpenMP, 2.12.6, atomic Construct
3326 // Any atomic construct with a seq_cst clause forces the atomically
3327 // performed operation to include an implicit flush operation without a
3328 // list.
3329 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003330 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003331 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003332}
3333
Alexey Bataevb8329262015-02-27 06:33:30 +00003334static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3335 const Expr *X, const Expr *E,
3336 SourceLocation Loc) {
3337 // x = expr;
3338 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003339 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003340 // OpenMP, 2.12.6, atomic Construct
3341 // Any atomic construct with a seq_cst clause forces the atomically
3342 // performed operation to include an implicit flush operation without a
3343 // list.
3344 if (IsSeqCst)
3345 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3346}
3347
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003348static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3349 RValue Update,
3350 BinaryOperatorKind BO,
3351 llvm::AtomicOrdering AO,
3352 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003353 auto &Context = CGF.CGM.getContext();
3354 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003355 // expression is simple and atomic is allowed for the given type for the
3356 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003357 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003358 !Update.getScalarVal()->getType()->isIntegerTy() ||
3359 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3360 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003361 X.getAddress().getElementType())) ||
3362 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003363 !Context.getTargetInfo().hasBuiltinAtomic(
3364 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003365 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003366
3367 llvm::AtomicRMWInst::BinOp RMWOp;
3368 switch (BO) {
3369 case BO_Add:
3370 RMWOp = llvm::AtomicRMWInst::Add;
3371 break;
3372 case BO_Sub:
3373 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003374 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003375 RMWOp = llvm::AtomicRMWInst::Sub;
3376 break;
3377 case BO_And:
3378 RMWOp = llvm::AtomicRMWInst::And;
3379 break;
3380 case BO_Or:
3381 RMWOp = llvm::AtomicRMWInst::Or;
3382 break;
3383 case BO_Xor:
3384 RMWOp = llvm::AtomicRMWInst::Xor;
3385 break;
3386 case BO_LT:
3387 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3388 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3389 : llvm::AtomicRMWInst::Max)
3390 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3391 : llvm::AtomicRMWInst::UMax);
3392 break;
3393 case BO_GT:
3394 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3395 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3396 : llvm::AtomicRMWInst::Min)
3397 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3398 : llvm::AtomicRMWInst::UMin);
3399 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003400 case BO_Assign:
3401 RMWOp = llvm::AtomicRMWInst::Xchg;
3402 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003403 case BO_Mul:
3404 case BO_Div:
3405 case BO_Rem:
3406 case BO_Shl:
3407 case BO_Shr:
3408 case BO_LAnd:
3409 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003410 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003411 case BO_PtrMemD:
3412 case BO_PtrMemI:
3413 case BO_LE:
3414 case BO_GE:
3415 case BO_EQ:
3416 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003417 case BO_AddAssign:
3418 case BO_SubAssign:
3419 case BO_AndAssign:
3420 case BO_OrAssign:
3421 case BO_XorAssign:
3422 case BO_MulAssign:
3423 case BO_DivAssign:
3424 case BO_RemAssign:
3425 case BO_ShlAssign:
3426 case BO_ShrAssign:
3427 case BO_Comma:
3428 llvm_unreachable("Unsupported atomic update operation");
3429 }
3430 auto *UpdateVal = Update.getScalarVal();
3431 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3432 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003433 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003434 X.getType()->hasSignedIntegerRepresentation());
3435 }
John McCall7f416cc2015-09-08 08:05:57 +00003436 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003437 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003438}
3439
Alexey Bataev5e018f92015-04-23 06:35:10 +00003440std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003441 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3442 llvm::AtomicOrdering AO, SourceLocation Loc,
3443 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3444 // Update expressions are allowed to have the following forms:
3445 // x binop= expr; -> xrval + expr;
3446 // x++, ++x -> xrval + 1;
3447 // x--, --x -> xrval - 1;
3448 // x = x binop expr; -> xrval binop expr
3449 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003450 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3451 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003452 if (X.isGlobalReg()) {
3453 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3454 // 'xrval'.
3455 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3456 } else {
3457 // Perform compare-and-swap procedure.
3458 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003459 }
3460 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003461 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003462}
3463
3464static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3465 const Expr *X, const Expr *E,
3466 const Expr *UE, bool IsXLHSInRHSPart,
3467 SourceLocation Loc) {
3468 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3469 "Update expr in 'atomic update' must be a binary operator.");
3470 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3471 // Update expressions are allowed to have the following forms:
3472 // x binop= expr; -> xrval + expr;
3473 // x++, ++x -> xrval + 1;
3474 // x--, --x -> xrval - 1;
3475 // x = x binop expr; -> xrval binop expr
3476 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003477 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003478 LValue XLValue = CGF.EmitLValue(X);
3479 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003480 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3481 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003482 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3483 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3484 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3485 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3486 auto Gen =
3487 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3488 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3489 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3490 return CGF.EmitAnyExpr(UE);
3491 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003492 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3493 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3494 // OpenMP, 2.12.6, atomic Construct
3495 // Any atomic construct with a seq_cst clause forces the atomically
3496 // performed operation to include an implicit flush operation without a
3497 // list.
3498 if (IsSeqCst)
3499 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3500}
3501
3502static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003503 QualType SourceType, QualType ResType,
3504 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003505 switch (CGF.getEvaluationKind(ResType)) {
3506 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003507 return RValue::get(
3508 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003509 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003510 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003511 return RValue::getComplex(Res.first, Res.second);
3512 }
3513 case TEK_Aggregate:
3514 break;
3515 }
3516 llvm_unreachable("Must be a scalar or complex.");
3517}
3518
3519static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3520 bool IsPostfixUpdate, const Expr *V,
3521 const Expr *X, const Expr *E,
3522 const Expr *UE, bool IsXLHSInRHSPart,
3523 SourceLocation Loc) {
3524 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3525 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3526 RValue NewVVal;
3527 LValue VLValue = CGF.EmitLValue(V);
3528 LValue XLValue = CGF.EmitLValue(X);
3529 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003530 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3531 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003532 QualType NewVValType;
3533 if (UE) {
3534 // 'x' is updated with some additional value.
3535 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3536 "Update expr in 'atomic capture' must be a binary operator.");
3537 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3538 // Update expressions are allowed to have the following forms:
3539 // x binop= expr; -> xrval + expr;
3540 // x++, ++x -> xrval + 1;
3541 // x--, --x -> xrval - 1;
3542 // x = x binop expr; -> xrval binop expr
3543 // x = expr Op x; - > expr binop xrval;
3544 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3545 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3546 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3547 NewVValType = XRValExpr->getType();
3548 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3549 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003550 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003551 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3552 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3553 RValue Res = CGF.EmitAnyExpr(UE);
3554 NewVVal = IsPostfixUpdate ? XRValue : Res;
3555 return Res;
3556 };
3557 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3558 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3559 if (Res.first) {
3560 // 'atomicrmw' instruction was generated.
3561 if (IsPostfixUpdate) {
3562 // Use old value from 'atomicrmw'.
3563 NewVVal = Res.second;
3564 } else {
3565 // 'atomicrmw' does not provide new value, so evaluate it using old
3566 // value of 'x'.
3567 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3568 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3569 NewVVal = CGF.EmitAnyExpr(UE);
3570 }
3571 }
3572 } else {
3573 // 'x' is simply rewritten with some 'expr'.
3574 NewVValType = X->getType().getNonReferenceType();
3575 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003576 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003577 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003578 NewVVal = XRValue;
3579 return ExprRValue;
3580 };
3581 // Try to perform atomicrmw xchg, otherwise simple exchange.
3582 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3583 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3584 Loc, Gen);
3585 if (Res.first) {
3586 // 'atomicrmw' instruction was generated.
3587 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3588 }
3589 }
3590 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003591 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003592 // OpenMP, 2.12.6, atomic Construct
3593 // Any atomic construct with a seq_cst clause forces the atomically
3594 // performed operation to include an implicit flush operation without a
3595 // list.
3596 if (IsSeqCst)
3597 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3598}
3599
Alexey Bataevb57056f2015-01-22 06:17:56 +00003600static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003601 bool IsSeqCst, bool IsPostfixUpdate,
3602 const Expr *X, const Expr *V, const Expr *E,
3603 const Expr *UE, bool IsXLHSInRHSPart,
3604 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003605 switch (Kind) {
3606 case OMPC_read:
3607 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3608 break;
3609 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003610 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3611 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003612 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003613 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003614 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3615 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003616 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003617 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3618 IsXLHSInRHSPart, Loc);
3619 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003620 case OMPC_if:
3621 case OMPC_final:
3622 case OMPC_num_threads:
3623 case OMPC_private:
3624 case OMPC_firstprivate:
3625 case OMPC_lastprivate:
3626 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003627 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003628 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003629 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003630 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003631 case OMPC_collapse:
3632 case OMPC_default:
3633 case OMPC_seq_cst:
3634 case OMPC_shared:
3635 case OMPC_linear:
3636 case OMPC_aligned:
3637 case OMPC_copyin:
3638 case OMPC_copyprivate:
3639 case OMPC_flush:
3640 case OMPC_proc_bind:
3641 case OMPC_schedule:
3642 case OMPC_ordered:
3643 case OMPC_nowait:
3644 case OMPC_untied:
3645 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003646 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003647 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003648 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003649 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003650 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003651 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003652 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003653 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003654 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003655 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003656 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003657 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003658 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003659 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003660 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003661 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003662 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003663 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003664 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003665 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003666 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3667 }
3668}
3669
3670void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003671 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003672 OpenMPClauseKind Kind = OMPC_unknown;
3673 for (auto *C : S.clauses()) {
3674 // Find first clause (skip seq_cst clause, if it is first).
3675 if (C->getClauseKind() != OMPC_seq_cst) {
3676 Kind = C->getClauseKind();
3677 break;
3678 }
3679 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003680
3681 const auto *CS =
3682 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003683 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003684 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003685 }
3686 // Processing for statements under 'atomic capture'.
3687 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3688 for (const auto *C : Compound->body()) {
3689 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3690 enterFullExpression(EWC);
3691 }
3692 }
3693 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003694
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003695 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3696 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003697 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003698 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3699 S.getV(), S.getExpr(), S.getUpdateExpr(),
3700 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003701 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003702 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003703 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003704}
3705
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003706static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3707 const OMPExecutableDirective &S,
3708 const RegionCodeGenTy &CodeGen) {
3709 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3710 CodeGenModule &CGM = CGF.CGM;
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00003711 const CapturedStmt &CS = *S.getCapturedStmt(OMPD_target);
Samuel Antaobed3c462015-10-02 16:14:20 +00003712
Samuel Antaoee8fb302016-01-06 13:42:12 +00003713 llvm::Function *Fn = nullptr;
3714 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003715
Samuel Antaobed3c462015-10-02 16:14:20 +00003716 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003717 // Check for the at most one if clause associated with the target region.
3718 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3719 if (C->getNameModifier() == OMPD_unknown ||
3720 C->getNameModifier() == OMPD_target) {
3721 IfCond = C->getCondition();
3722 break;
3723 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003724 }
3725
3726 // Check if we have any device clause associated with the directive.
3727 const Expr *Device = nullptr;
3728 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3729 Device = C->getDevice();
3730 }
3731
Samuel Antaoee8fb302016-01-06 13:42:12 +00003732 // Check if we have an if clause whose conditional always evaluates to false
3733 // or if we do not have any targets specified. If so the target region is not
3734 // an offload entry point.
3735 bool IsOffloadEntry = true;
3736 if (IfCond) {
3737 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003738 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003739 IsOffloadEntry = false;
3740 }
3741 if (CGM.getLangOpts().OMPTargetTriples.empty())
3742 IsOffloadEntry = false;
3743
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003744 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003745 StringRef ParentName;
3746 // In case we have Ctors/Dtors we use the complete type variant to produce
3747 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003748 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003749 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003750 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003751 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3752 else
3753 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003754 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003755
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003756 // Emit target region as a standalone region.
3757 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3758 IsOffloadEntry, CodeGen);
3759 OMPLexicalScope Scope(CGF, S);
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003760 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3761 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003762 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003763 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003764}
3765
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003766static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3767 PrePostActionTy &Action) {
3768 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3769 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3770 CGF.EmitOMPPrivateClause(S, PrivateScope);
3771 (void)PrivateScope.Privatize();
3772
3773 Action.Enter(CGF);
3774 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3775}
3776
3777void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3778 StringRef ParentName,
3779 const OMPTargetDirective &S) {
3780 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3781 emitTargetRegion(CGF, S, Action);
3782 };
3783 llvm::Function *Fn;
3784 llvm::Constant *Addr;
3785 // Emit target region as a standalone region.
3786 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3787 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3788 assert(Fn && Addr && "Target device function emission failed.");
3789}
3790
3791void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3792 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3793 emitTargetRegion(CGF, S, Action);
3794 };
3795 emitCommonOMPTargetDirective(*this, S, CodeGen);
3796}
3797
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003798static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3799 const OMPExecutableDirective &S,
3800 OpenMPDirectiveKind InnermostKind,
3801 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003802 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
3803 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
3804 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003805
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003806 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
3807 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003808 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003809 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3810 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003811
Carlo Bertollic6872252016-04-04 15:55:02 +00003812 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3813 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003814 }
3815
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003816 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003817 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3818 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003819 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3820 CapturedVars);
3821}
3822
3823void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00003824 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003825 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003826 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003827 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3828 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003829 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003830 (void)PrivateScope.Privatize();
3831 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003832 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003833 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00003834 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003835 emitPostUpdateForReductionClause(
3836 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00003837}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003838
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003839static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
3840 const OMPTargetTeamsDirective &S) {
3841 auto *CS = S.getCapturedStmt(OMPD_teams);
3842 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00003843 // Emit teams region as a standalone region.
3844 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
3845 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3846 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3847 CGF.EmitOMPPrivateClause(S, PrivateScope);
3848 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3849 (void)PrivateScope.Privatize();
3850 Action.Enter(CGF);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003851 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00003852 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003853 };
3854 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00003855 emitPostUpdateForReductionClause(
3856 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003857}
3858
3859void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
3860 CodeGenModule &CGM, StringRef ParentName,
3861 const OMPTargetTeamsDirective &S) {
3862 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3863 emitTargetTeamsRegion(CGF, Action, S);
3864 };
3865 llvm::Function *Fn;
3866 llvm::Constant *Addr;
3867 // Emit target region as a standalone region.
3868 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3869 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3870 assert(Fn && Addr && "Target device function emission failed.");
3871}
3872
3873void CodeGenFunction::EmitOMPTargetTeamsDirective(
3874 const OMPTargetTeamsDirective &S) {
3875 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3876 emitTargetTeamsRegion(CGF, Action, S);
3877 };
3878 emitCommonOMPTargetDirective(*this, S, CodeGen);
3879}
3880
Alexey Bataevdfa430f2017-12-08 15:03:50 +00003881static void
3882emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
3883 const OMPTargetTeamsDistributeDirective &S) {
3884 Action.Enter(CGF);
3885 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3886 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
3887 };
3888
3889 // Emit teams region as a standalone region.
3890 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
3891 PrePostActionTy &) {
3892 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3893 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3894 (void)PrivateScope.Privatize();
3895 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
3896 CodeGenDistribute);
3897 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3898 };
3899 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
3900 emitPostUpdateForReductionClause(CGF, S,
3901 [](CodeGenFunction &) { return nullptr; });
3902}
3903
3904void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
3905 CodeGenModule &CGM, StringRef ParentName,
3906 const OMPTargetTeamsDistributeDirective &S) {
3907 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3908 emitTargetTeamsDistributeRegion(CGF, Action, S);
3909 };
3910 llvm::Function *Fn;
3911 llvm::Constant *Addr;
3912 // Emit target region as a standalone region.
3913 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3914 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3915 assert(Fn && Addr && "Target device function emission failed.");
3916}
3917
3918void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
3919 const OMPTargetTeamsDistributeDirective &S) {
3920 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3921 emitTargetTeamsDistributeRegion(CGF, Action, S);
3922 };
3923 emitCommonOMPTargetDirective(*this, S, CodeGen);
3924}
3925
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003926void CodeGenFunction::EmitOMPTeamsDistributeDirective(
3927 const OMPTeamsDistributeDirective &S) {
3928
3929 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3930 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
3931 };
3932
3933 // Emit teams region as a standalone region.
3934 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
3935 PrePostActionTy &) {
3936 OMPPrivateScope PrivateScope(CGF);
3937 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3938 (void)PrivateScope.Privatize();
3939 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
3940 CodeGenDistribute);
3941 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3942 };
Alexey Bataev95c6dd42017-11-29 15:14:16 +00003943 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003944 emitPostUpdateForReductionClause(*this, S,
3945 [](CodeGenFunction &) { return nullptr; });
3946}
3947
Alexey Bataev999277a2017-12-06 14:31:09 +00003948void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
3949 const OMPTeamsDistributeSimdDirective &S) {
3950 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3951 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
3952 };
3953
3954 // Emit teams region as a standalone region.
3955 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
3956 PrePostActionTy &) {
3957 OMPPrivateScope PrivateScope(CGF);
3958 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3959 (void)PrivateScope.Privatize();
3960 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
3961 CodeGenDistribute);
3962 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3963 };
3964 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
3965 emitPostUpdateForReductionClause(*this, S,
3966 [](CodeGenFunction &) { return nullptr; });
3967}
3968
Carlo Bertolli62fae152017-11-20 20:46:39 +00003969void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
3970 const OMPTeamsDistributeParallelForDirective &S) {
3971 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3972 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
3973 S.getDistInc());
3974 };
3975
3976 // Emit teams region as a standalone region.
3977 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
3978 PrePostActionTy &) {
3979 OMPPrivateScope PrivateScope(CGF);
3980 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3981 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00003982 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
3983 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003984 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3985 };
3986 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
3987 emitPostUpdateForReductionClause(*this, S,
3988 [](CodeGenFunction &) { return nullptr; });
3989}
3990
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003991void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
3992 const OMPTeamsDistributeParallelForSimdDirective &S) {
3993 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3994 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
3995 S.getDistInc());
3996 };
3997
3998 // Emit teams region as a standalone region.
3999 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4000 PrePostActionTy &) {
4001 OMPPrivateScope PrivateScope(CGF);
4002 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4003 (void)PrivateScope.Privatize();
4004 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4005 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4006 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4007 };
4008 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4009 emitPostUpdateForReductionClause(*this, S,
4010 [](CodeGenFunction &) { return nullptr; });
4011}
4012
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004013void CodeGenFunction::EmitOMPCancellationPointDirective(
4014 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00004015 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
4016 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004017}
4018
Alexey Bataev80909872015-07-02 11:25:17 +00004019void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004020 const Expr *IfCond = nullptr;
4021 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4022 if (C->getNameModifier() == OMPD_unknown ||
4023 C->getNameModifier() == OMPD_cancel) {
4024 IfCond = C->getCondition();
4025 break;
4026 }
4027 }
4028 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004029 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00004030}
4031
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004032CodeGenFunction::JumpDest
4033CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00004034 if (Kind == OMPD_parallel || Kind == OMPD_task ||
4035 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004036 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004037 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00004038 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
4039 Kind == OMPD_distribute_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004040 Kind == OMPD_target_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004041 Kind == OMPD_teams_distribute_parallel_for ||
4042 Kind == OMPD_target_teams_distribute_parallel_for);
Alexey Bataev957d8562016-11-17 15:12:05 +00004043 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004044}
Michael Wong65f367f2015-07-21 13:44:28 +00004045
Samuel Antaocc10b852016-07-28 14:23:26 +00004046void CodeGenFunction::EmitOMPUseDevicePtrClause(
4047 const OMPClause &NC, OMPPrivateScope &PrivateScope,
4048 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
4049 const auto &C = cast<OMPUseDevicePtrClause>(NC);
4050 auto OrigVarIt = C.varlist_begin();
4051 auto InitIt = C.inits().begin();
4052 for (auto PvtVarIt : C.private_copies()) {
4053 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
4054 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
4055 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
4056
4057 // In order to identify the right initializer we need to match the
4058 // declaration used by the mapping logic. In some cases we may get
4059 // OMPCapturedExprDecl that refers to the original declaration.
4060 const ValueDecl *MatchingVD = OrigVD;
4061 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
4062 // OMPCapturedExprDecl are used to privative fields of the current
4063 // structure.
4064 auto *ME = cast<MemberExpr>(OED->getInit());
4065 assert(isa<CXXThisExpr>(ME->getBase()) &&
4066 "Base should be the current struct!");
4067 MatchingVD = ME->getMemberDecl();
4068 }
4069
4070 // If we don't have information about the current list item, move on to
4071 // the next one.
4072 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
4073 if (InitAddrIt == CaptureDeviceAddrMap.end())
4074 continue;
4075
4076 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
4077 // Initialize the temporary initialization variable with the address we
4078 // get from the runtime library. We have to cast the source address
4079 // because it is always a void *. References are materialized in the
4080 // privatization scope, so the initialization here disregards the fact
4081 // the original variable is a reference.
4082 QualType AddrQTy =
4083 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
4084 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
4085 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
4086 setAddrOfLocalVar(InitVD, InitAddr);
4087
4088 // Emit private declaration, it will be initialized by the value we
4089 // declaration we just added to the local declarations map.
4090 EmitDecl(*PvtVD);
4091
4092 // The initialization variables reached its purpose in the emission
4093 // ofthe previous declaration, so we don't need it anymore.
4094 LocalDeclMap.erase(InitVD);
4095
4096 // Return the address of the private variable.
4097 return GetAddrOfLocalVar(PvtVD);
4098 });
4099 assert(IsRegistered && "firstprivate var already registered as private");
4100 // Silence the warning about unused variable.
4101 (void)IsRegistered;
4102
4103 ++OrigVarIt;
4104 ++InitIt;
4105 }
4106}
4107
Michael Wong65f367f2015-07-21 13:44:28 +00004108// Generate the instructions for '#pragma omp target data' directive.
4109void CodeGenFunction::EmitOMPTargetDataDirective(
4110 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004111 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4112
4113 // Create a pre/post action to signal the privatization of the device pointer.
4114 // This action can be replaced by the OpenMP runtime code generation to
4115 // deactivate privatization.
4116 bool PrivatizeDevicePointers = false;
4117 class DevicePointerPrivActionTy : public PrePostActionTy {
4118 bool &PrivatizeDevicePointers;
4119
4120 public:
4121 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4122 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4123 void Enter(CodeGenFunction &CGF) override {
4124 PrivatizeDevicePointers = true;
4125 }
Samuel Antaodf158d52016-04-27 22:58:19 +00004126 };
Samuel Antaocc10b852016-07-28 14:23:26 +00004127 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4128
4129 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
4130 CodeGenFunction &CGF, PrePostActionTy &Action) {
4131 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4132 CGF.EmitStmt(
4133 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
4134 };
4135
4136 // Codegen that selects wheather to generate the privatization code or not.
4137 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4138 &InnermostCodeGen](CodeGenFunction &CGF,
4139 PrePostActionTy &Action) {
4140 RegionCodeGenTy RCG(InnermostCodeGen);
4141 PrivatizeDevicePointers = false;
4142
4143 // Call the pre-action to change the status of PrivatizeDevicePointers if
4144 // needed.
4145 Action.Enter(CGF);
4146
4147 if (PrivatizeDevicePointers) {
4148 OMPPrivateScope PrivateScope(CGF);
4149 // Emit all instances of the use_device_ptr clause.
4150 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4151 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4152 Info.CaptureDeviceAddrMap);
4153 (void)PrivateScope.Privatize();
4154 RCG(CGF);
4155 } else
4156 RCG(CGF);
4157 };
4158
4159 // Forward the provided action to the privatization codegen.
4160 RegionCodeGenTy PrivRCG(PrivCodeGen);
4161 PrivRCG.setAction(Action);
4162
4163 // Notwithstanding the body of the region is emitted as inlined directive,
4164 // we don't use an inline scope as changes in the references inside the
4165 // region are expected to be visible outside, so we do not privative them.
4166 OMPLexicalScope Scope(CGF, S);
4167 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4168 PrivRCG);
4169 };
4170
4171 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004172
4173 // If we don't have target devices, don't bother emitting the data mapping
4174 // code.
4175 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004176 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004177 return;
4178 }
4179
4180 // Check if we have any if clause associated with the directive.
4181 const Expr *IfCond = nullptr;
4182 if (auto *C = S.getSingleClause<OMPIfClause>())
4183 IfCond = C->getCondition();
4184
4185 // Check if we have any device clause associated with the directive.
4186 const Expr *Device = nullptr;
4187 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4188 Device = C->getDevice();
4189
Samuel Antaocc10b852016-07-28 14:23:26 +00004190 // Set the action to signal privatization of device pointers.
4191 RCG.setAction(PrivAction);
4192
4193 // Emit region code.
4194 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4195 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004196}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004197
Samuel Antaodf67fc42016-01-19 19:15:56 +00004198void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4199 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004200 // If we don't have target devices, don't bother emitting the data mapping
4201 // code.
4202 if (CGM.getLangOpts().OMPTargetTriples.empty())
4203 return;
4204
4205 // Check if we have any if clause associated with the directive.
4206 const Expr *IfCond = nullptr;
4207 if (auto *C = S.getSingleClause<OMPIfClause>())
4208 IfCond = C->getCondition();
4209
4210 // Check if we have any device clause associated with the directive.
4211 const Expr *Device = nullptr;
4212 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4213 Device = C->getDevice();
4214
Alexey Bataev7828b252017-11-21 17:08:48 +00004215 auto &&CodeGen = [&S, IfCond, Device](CodeGenFunction &CGF,
4216 PrePostActionTy &) {
4217 CGF.CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(CGF, S, IfCond,
4218 Device);
4219 };
4220 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
4221 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_target_enter_data,
4222 CodeGen);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004223}
4224
Samuel Antao72590762016-01-19 20:04:50 +00004225void CodeGenFunction::EmitOMPTargetExitDataDirective(
4226 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004227 // If we don't have target devices, don't bother emitting the data mapping
4228 // code.
4229 if (CGM.getLangOpts().OMPTargetTriples.empty())
4230 return;
4231
4232 // Check if we have any if clause associated with the directive.
4233 const Expr *IfCond = nullptr;
4234 if (auto *C = S.getSingleClause<OMPIfClause>())
4235 IfCond = C->getCondition();
4236
4237 // Check if we have any device clause associated with the directive.
4238 const Expr *Device = nullptr;
4239 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4240 Device = C->getDevice();
4241
Alexey Bataev7828b252017-11-21 17:08:48 +00004242 auto &&CodeGen = [&S, IfCond, Device](CodeGenFunction &CGF,
4243 PrePostActionTy &) {
4244 CGF.CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(CGF, S, IfCond,
4245 Device);
4246 };
4247 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
4248 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_target_exit_data,
4249 CodeGen);
Samuel Antao72590762016-01-19 20:04:50 +00004250}
4251
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004252static void emitTargetParallelRegion(CodeGenFunction &CGF,
4253 const OMPTargetParallelDirective &S,
4254 PrePostActionTy &Action) {
4255 // Get the captured statement associated with the 'parallel' region.
4256 auto *CS = S.getCapturedStmt(OMPD_parallel);
4257 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004258 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
4259 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4260 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4261 CGF.EmitOMPPrivateClause(S, PrivateScope);
4262 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4263 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004264 // TODO: Add support for clauses.
4265 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004266 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004267 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004268 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4269 emitEmptyBoundParameters);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004270 emitPostUpdateForReductionClause(
4271 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004272}
4273
4274void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4275 CodeGenModule &CGM, StringRef ParentName,
4276 const OMPTargetParallelDirective &S) {
4277 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4278 emitTargetParallelRegion(CGF, S, Action);
4279 };
4280 llvm::Function *Fn;
4281 llvm::Constant *Addr;
4282 // Emit target region as a standalone region.
4283 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4284 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4285 assert(Fn && Addr && "Target device function emission failed.");
4286}
4287
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004288void CodeGenFunction::EmitOMPTargetParallelDirective(
4289 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004290 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4291 emitTargetParallelRegion(CGF, S, Action);
4292 };
4293 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004294}
4295
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004296static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4297 const OMPTargetParallelForDirective &S,
4298 PrePostActionTy &Action) {
4299 Action.Enter(CGF);
4300 // Emit directive as a combined directive that consists of two implicit
4301 // directives: 'parallel' with 'for' directive.
4302 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev2139ed62017-11-16 18:20:21 +00004303 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4304 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004305 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4306 emitDispatchForLoopBounds);
4307 };
4308 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4309 emitEmptyBoundParameters);
4310}
4311
4312void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4313 CodeGenModule &CGM, StringRef ParentName,
4314 const OMPTargetParallelForDirective &S) {
4315 // Emit SPMD target parallel for region as a standalone region.
4316 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4317 emitTargetParallelForRegion(CGF, S, Action);
4318 };
4319 llvm::Function *Fn;
4320 llvm::Constant *Addr;
4321 // Emit target region as a standalone region.
4322 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4323 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4324 assert(Fn && Addr && "Target device function emission failed.");
4325}
4326
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004327void CodeGenFunction::EmitOMPTargetParallelForDirective(
4328 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004329 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4330 emitTargetParallelForRegion(CGF, S, Action);
4331 };
4332 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004333}
4334
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004335static void
4336emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4337 const OMPTargetParallelForSimdDirective &S,
4338 PrePostActionTy &Action) {
4339 Action.Enter(CGF);
4340 // Emit directive as a combined directive that consists of two implicit
4341 // directives: 'parallel' with 'for' directive.
4342 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4343 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4344 emitDispatchForLoopBounds);
4345 };
4346 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4347 emitEmptyBoundParameters);
4348}
4349
4350void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4351 CodeGenModule &CGM, StringRef ParentName,
4352 const OMPTargetParallelForSimdDirective &S) {
4353 // Emit SPMD target parallel for region as a standalone region.
4354 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4355 emitTargetParallelForSimdRegion(CGF, S, Action);
4356 };
4357 llvm::Function *Fn;
4358 llvm::Constant *Addr;
4359 // Emit target region as a standalone region.
4360 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4361 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4362 assert(Fn && Addr && "Target device function emission failed.");
4363}
4364
4365void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4366 const OMPTargetParallelForSimdDirective &S) {
4367 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4368 emitTargetParallelForSimdRegion(CGF, S, Action);
4369 };
4370 emitCommonOMPTargetDirective(*this, S, CodeGen);
4371}
4372
Alexey Bataev7292c292016-04-25 12:22:29 +00004373/// Emit a helper variable and return corresponding lvalue.
4374static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4375 const ImplicitParamDecl *PVD,
4376 CodeGenFunction::OMPPrivateScope &Privates) {
4377 auto *VDecl = cast<VarDecl>(Helper->getDecl());
4378 Privates.addPrivate(
4379 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
4380}
4381
4382void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4383 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4384 // Emit outlined function for task construct.
4385 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
4386 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
4387 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4388 const Expr *IfCond = nullptr;
4389 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4390 if (C->getNameModifier() == OMPD_unknown ||
4391 C->getNameModifier() == OMPD_taskloop) {
4392 IfCond = C->getCondition();
4393 break;
4394 }
4395 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004396
4397 OMPTaskDataTy Data;
4398 // Check if taskloop must be emitted without taskgroup.
4399 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004400 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004401 Data.Tied = true;
4402 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004403 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4404 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004405 Data.Schedule.setInt(/*IntVal=*/false);
4406 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004407 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4408 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004409 Data.Schedule.setInt(/*IntVal=*/true);
4410 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004411 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004412
4413 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4414 // if (PreCond) {
4415 // for (IV in 0..LastIteration) BODY;
4416 // <Final counter/linear vars updates>;
4417 // }
4418 //
4419
4420 // Emit: if (PreCond) - begin.
4421 // If the condition constant folds and can be elided, avoid emitting the
4422 // whole loop.
4423 bool CondConstant;
4424 llvm::BasicBlock *ContBlock = nullptr;
4425 OMPLoopScope PreInitScope(CGF, S);
4426 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4427 if (!CondConstant)
4428 return;
4429 } else {
4430 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4431 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4432 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4433 CGF.getProfileCount(&S));
4434 CGF.EmitBlock(ThenBlock);
4435 CGF.incrementProfileCounter(&S);
4436 }
4437
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004438 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4439 CGF.EmitOMPSimdInit(S);
4440
Alexey Bataev7292c292016-04-25 12:22:29 +00004441 OMPPrivateScope LoopScope(CGF);
4442 // Emit helper vars inits.
4443 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4444 auto *I = CS->getCapturedDecl()->param_begin();
4445 auto *LBP = std::next(I, LowerBound);
4446 auto *UBP = std::next(I, UpperBound);
4447 auto *STP = std::next(I, Stride);
4448 auto *LIP = std::next(I, LastIter);
4449 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4450 LoopScope);
4451 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4452 LoopScope);
4453 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4454 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4455 LoopScope);
4456 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004457 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004458 (void)LoopScope.Privatize();
4459 // Emit the loop iteration variable.
4460 const Expr *IVExpr = S.getIterationVariable();
4461 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4462 CGF.EmitVarDecl(*IVDecl);
4463 CGF.EmitIgnoredExpr(S.getInit());
4464
4465 // Emit the iterations count variable.
4466 // If it is not a variable, Sema decided to calculate iterations count on
4467 // each iteration (e.g., it is foldable into a constant).
4468 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4469 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4470 // Emit calculation of the iterations count.
4471 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4472 }
4473
4474 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4475 S.getInc(),
4476 [&S](CodeGenFunction &CGF) {
4477 CGF.EmitOMPLoopBody(S, JumpDest());
4478 CGF.EmitStopPoint(&S);
4479 },
4480 [](CodeGenFunction &) {});
4481 // Emit: if (PreCond) - end.
4482 if (ContBlock) {
4483 CGF.EmitBranch(ContBlock);
4484 CGF.EmitBlock(ContBlock, true);
4485 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004486 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4487 if (HasLastprivateClause) {
4488 CGF.EmitOMPLastprivateClauseFinal(
4489 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4490 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4491 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4492 (*LIP)->getType(), S.getLocStart())));
4493 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004494 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004495 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4496 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4497 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004498 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4499 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004500 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4501 OutlinedFn, SharedsTy,
4502 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004503 };
4504 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4505 CodeGen);
4506 };
Alexey Bataev33446032017-07-12 18:09:32 +00004507 if (Data.Nogroup)
4508 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4509 else {
4510 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4511 *this,
4512 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4513 PrePostActionTy &Action) {
4514 Action.Enter(CGF);
4515 CGF.EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4516 },
4517 S.getLocStart());
4518 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004519}
4520
Alexey Bataev49f6e782015-12-01 04:18:41 +00004521void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004522 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004523}
4524
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004525void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4526 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004527 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004528}
Samuel Antao686c70c2016-05-26 17:30:50 +00004529
4530// Generate the instructions for '#pragma omp target update' directive.
4531void CodeGenFunction::EmitOMPTargetUpdateDirective(
4532 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +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 Bataev7828b252017-11-21 17:08:48 +00004548 auto &&CodeGen = [&S, IfCond, Device](CodeGenFunction &CGF,
4549 PrePostActionTy &) {
4550 CGF.CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(CGF, S, IfCond,
4551 Device);
4552 };
4553 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
4554 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_target_update,
4555 CodeGen);
Samuel Antao686c70c2016-05-26 17:30:50 +00004556}