blob: 488c7fa0a11c03fece2ab0387919b11b6f026bf8 [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 Li83c451e2016-12-25 04:52:54 +00002094void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
2095 const OMPTargetTeamsDistributeDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002096 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Li26fd21a2016-12-28 17:57:07 +00002097 CGM.getOpenMPRuntime().emitInlinedDirective(
2098 *this, OMPD_target_teams_distribute,
Kelvin Li83c451e2016-12-25 04:52:54 +00002099 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002100 CGF.EmitStmt(
2101 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Kelvin Li83c451e2016-12-25 04:52:54 +00002102 });
2103}
2104
Kelvin Li80e8f562016-12-29 22:16:30 +00002105void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
2106 const OMPTargetTeamsDistributeParallelForDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002107 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Li80e8f562016-12-29 22:16:30 +00002108 CGM.getOpenMPRuntime().emitInlinedDirective(
2109 *this, OMPD_target_teams_distribute_parallel_for,
2110 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2111 CGF.EmitStmt(
2112 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2113 });
2114}
2115
Kelvin Li1851df52017-01-03 05:23:48 +00002116void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2117 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002118 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Li1851df52017-01-03 05:23:48 +00002119 CGM.getOpenMPRuntime().emitInlinedDirective(
2120 *this, OMPD_target_teams_distribute_parallel_for_simd,
2121 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2122 CGF.EmitStmt(
2123 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2124 });
2125}
2126
Kelvin Lida681182017-01-10 18:08:18 +00002127void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
2128 const OMPTargetTeamsDistributeSimdDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002129 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Lida681182017-01-10 18:08:18 +00002130 CGM.getOpenMPRuntime().emitInlinedDirective(
2131 *this, OMPD_target_teams_distribute_simd,
2132 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2133 CGF.EmitStmt(
2134 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2135 });
2136}
2137
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002138namespace {
2139 struct ScheduleKindModifiersTy {
2140 OpenMPScheduleClauseKind Kind;
2141 OpenMPScheduleClauseModifier M1;
2142 OpenMPScheduleClauseModifier M2;
2143 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2144 OpenMPScheduleClauseModifier M1,
2145 OpenMPScheduleClauseModifier M2)
2146 : Kind(Kind), M1(M1), M2(M2) {}
2147 };
2148} // namespace
2149
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002150bool CodeGenFunction::EmitOMPWorksharingLoop(
2151 const OMPLoopDirective &S, Expr *EUB,
2152 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2153 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002154 // Emit the loop iteration variable.
2155 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2156 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2157 EmitVarDecl(*IVDecl);
2158
2159 // Emit the iterations count variable.
2160 // If it is not a variable, Sema decided to calculate iterations count on each
2161 // iteration (e.g., it is foldable into a constant).
2162 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2163 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2164 // Emit calculation of the iterations count.
2165 EmitIgnoredExpr(S.getCalcLastIteration());
2166 }
2167
2168 auto &RT = CGM.getOpenMPRuntime();
2169
Alexey Bataev38e89532015-04-16 04:54:05 +00002170 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002171 // Check pre-condition.
2172 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002173 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002174 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002175 // If the condition constant folds and can be elided, avoid emitting the
2176 // whole loop.
2177 bool CondConstant;
2178 llvm::BasicBlock *ContBlock = nullptr;
2179 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2180 if (!CondConstant)
2181 return false;
2182 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002183 auto *ThenBlock = createBasicBlock("omp.precond.then");
2184 ContBlock = createBasicBlock("omp.precond.end");
2185 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002186 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002187 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002188 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002189 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002190
Alexey Bataev8b427062016-05-25 12:36:08 +00002191 bool Ordered = false;
2192 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2193 if (OrderedClause->getNumForLoops())
2194 RT.emitDoacrossInit(*this, S);
2195 else
2196 Ordered = true;
2197 }
2198
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002199 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002200 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002201 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002202 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002203
2204 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2205 LValue LB = Bounds.first;
2206 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002207 LValue ST =
2208 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2209 LValue IL =
2210 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2211
Alexander Musmanc6388682014-12-15 07:07:06 +00002212 // Emit 'then' code.
2213 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002214 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002215 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002216 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002217 // initialization of firstprivate variables and post-update of
2218 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002219 CGM.getOpenMPRuntime().emitBarrierCall(
2220 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2221 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002222 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002223 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002224 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002225 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002226 EmitOMPPrivateLoopCounters(S, LoopScope);
2227 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002228 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002229
2230 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002231 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002232 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002233 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002234 ScheduleKind.Schedule = C->getScheduleKind();
2235 ScheduleKind.M1 = C->getFirstScheduleModifier();
2236 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002237 if (const auto *Ch = C->getChunkSize()) {
2238 Chunk = EmitScalarExpr(Ch);
2239 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2240 S.getIterationVariable()->getType(),
2241 S.getLocStart());
2242 }
2243 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002244 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2245 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002246 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2247 // If the static schedule kind is specified or if the ordered clause is
2248 // specified, and if no monotonic modifier is specified, the effect will
2249 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002250 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002251 /* Chunked */ Chunk != nullptr) &&
2252 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002253 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2254 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002255 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2256 // When no chunk_size is specified, the iteration space is divided into
2257 // chunks that are approximately equal in size, and at most one chunk is
2258 // distributed to each thread. Note that the size of the chunks is
2259 // unspecified in this case.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002260 CGOpenMPRuntime::StaticRTInput StaticInit(
2261 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
2262 UB.getAddress(), ST.getAddress());
2263 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
2264 ScheduleKind, StaticInit);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002265 auto LoopExit =
2266 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002267 // UB = min(UB, GlobalUB);
2268 EmitIgnoredExpr(S.getEnsureUpperBound());
2269 // IV = LB;
2270 EmitIgnoredExpr(S.getInit());
2271 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002272 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2273 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002274 [&S, LoopExit](CodeGenFunction &CGF) {
2275 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002276 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002277 },
2278 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002279 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002280 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002281 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002282 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2283 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002284 };
2285 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002286 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002287 const bool IsMonotonic =
2288 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2289 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2290 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2291 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002292 // Emit the outer loop, which requests its work chunk [LB..UB] from
2293 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002294 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2295 ST.getAddress(), IL.getAddress(),
2296 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002297 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002298 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002299 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002300 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2301 EmitOMPSimdFinal(S,
2302 [&](CodeGenFunction &CGF) -> llvm::Value * {
2303 return CGF.Builder.CreateIsNotNull(
2304 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2305 });
2306 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002307 EmitOMPReductionClauseFinal(
2308 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2309 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2310 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002311 // Emit post-update of the reduction variables if IsLastIter != 0.
2312 emitPostUpdateForReductionClause(
2313 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2314 return CGF.Builder.CreateIsNotNull(
2315 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2316 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002317 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2318 if (HasLastprivateClause)
2319 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002320 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2321 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002322 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002323 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002324 return CGF.Builder.CreateIsNotNull(
2325 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2326 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002327 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002328 if (ContBlock) {
2329 EmitBranch(ContBlock);
2330 EmitBlock(ContBlock, true);
2331 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002332 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002333 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002334}
2335
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002336/// The following two functions generate expressions for the loop lower
2337/// and upper bounds in case of static and dynamic (dispatch) schedule
2338/// of the associated 'for' or 'distribute' loop.
2339static std::pair<LValue, LValue>
2340emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2341 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2342 LValue LB =
2343 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2344 LValue UB =
2345 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2346 return {LB, UB};
2347}
2348
2349/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2350/// consider the lower and upper bound expressions generated by the
2351/// worksharing loop support, but we use 0 and the iteration space size as
2352/// constants
2353static std::pair<llvm::Value *, llvm::Value *>
2354emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2355 Address LB, Address UB) {
2356 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2357 const Expr *IVExpr = LS.getIterationVariable();
2358 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2359 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2360 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2361 return {LBVal, UBVal};
2362}
2363
Alexander Musmanc6388682014-12-15 07:07:06 +00002364void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002365 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002366 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2367 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002368 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002369 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2370 emitForLoopBounds,
2371 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002372 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002373 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002374 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002375 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2376 S.hasCancel());
2377 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002378
2379 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002380 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002381 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2382 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002383}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002384
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002385void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002386 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002387 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2388 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002389 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2390 emitForLoopBounds,
2391 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002392 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002393 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002394 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002395 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2396 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002397
2398 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002399 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002400 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2401 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002402}
2403
Alexey Bataev2df54a02015-03-12 08:53:29 +00002404static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2405 const Twine &Name,
2406 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002407 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002408 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002409 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002410 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002411}
2412
Alexey Bataev3392d762016-02-16 11:18:12 +00002413void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00002414 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2415 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002416 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002417 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2418 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002419 auto &C = CGF.CGM.getContext();
2420 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2421 // Emit helper vars inits.
2422 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2423 CGF.Builder.getInt32(0));
2424 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2425 : CGF.Builder.getInt32(0);
2426 LValue UB =
2427 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2428 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2429 CGF.Builder.getInt32(1));
2430 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2431 CGF.Builder.getInt32(0));
2432 // Loop counter.
2433 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2434 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2435 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2436 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2437 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2438 // Generate condition for loop.
2439 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002440 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002441 // Increment for loop counter.
2442 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2443 S.getLocStart());
2444 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2445 // Iterate through all sections and emit a switch construct:
2446 // switch (IV) {
2447 // case 0:
2448 // <SectionStmt[0]>;
2449 // break;
2450 // ...
2451 // case <NumSection> - 1:
2452 // <SectionStmt[<NumSection> - 1]>;
2453 // break;
2454 // }
2455 // .omp.sections.exit:
2456 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2457 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2458 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2459 CS == nullptr ? 1 : CS->size());
2460 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002461 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002462 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002463 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2464 CGF.EmitBlock(CaseBB);
2465 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002466 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002467 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002468 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002469 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002470 } else {
2471 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2472 CGF.EmitBlock(CaseBB);
2473 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2474 CGF.EmitStmt(Stmt);
2475 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002476 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002477 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002478 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002479
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002480 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2481 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002482 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002483 // initialization of firstprivate variables and post-update of lastprivate
2484 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002485 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2486 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2487 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002488 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002489 CGF.EmitOMPPrivateClause(S, LoopScope);
2490 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2491 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2492 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002493
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002494 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002495 OpenMPScheduleTy ScheduleKind;
2496 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002497 CGOpenMPRuntime::StaticRTInput StaticInit(
2498 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2499 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002500 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002501 CGF, S.getLocStart(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002502 // UB = min(UB, GlobalUB);
2503 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2504 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2505 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2506 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2507 // IV = LB;
2508 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2509 // while (idx <= UB) { BODY; ++idx; }
2510 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2511 [](CodeGenFunction &) {});
2512 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002513 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002514 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2515 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002516 };
2517 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002518 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002519 // Emit post-update of the reduction variables if IsLastIter != 0.
2520 emitPostUpdateForReductionClause(
2521 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2522 return CGF.Builder.CreateIsNotNull(
2523 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2524 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002525
2526 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2527 if (HasLastprivates)
2528 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002529 S, /*NoFinals=*/false,
2530 CGF.Builder.CreateIsNotNull(
2531 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002532 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002533
2534 bool HasCancel = false;
2535 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2536 HasCancel = OSD->hasCancel();
2537 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2538 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002539 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002540 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2541 HasCancel);
2542 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2543 // clause. Otherwise the barrier will be generated by the codegen for the
2544 // directive.
2545 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002546 // Emit implicit barrier to synchronize threads and avoid data races on
2547 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002548 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2549 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002550 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002551}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002552
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002553void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002554 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002555 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002556 EmitSections(S);
2557 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002558 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002559 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002560 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2561 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002562 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002563}
2564
2565void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002566 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002567 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002568 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002569 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002570 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2571 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002572}
2573
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002574void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002575 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002576 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002577 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002578 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002579 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002580 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002581 // Build a list of copyprivate variables along with helper expressions
2582 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002583 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002584 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002585 DestExprs.append(C->destination_exprs().begin(),
2586 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002587 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002588 AssignmentOps.append(C->assignment_ops().begin(),
2589 C->assignment_ops().end());
2590 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002591 // Emit code for 'single' region along with 'copyprivate' clauses
2592 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2593 Action.Enter(CGF);
2594 OMPPrivateScope SingleScope(CGF);
2595 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2596 CGF.EmitOMPPrivateClause(S, SingleScope);
2597 (void)SingleScope.Privatize();
2598 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2599 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002600 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002601 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002602 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2603 CopyprivateVars, DestExprs,
2604 SrcExprs, AssignmentOps);
2605 }
2606 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2607 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002608 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002609 CGM.getOpenMPRuntime().emitBarrierCall(
2610 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002611 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002612 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002613}
2614
Alexey Bataev8d690652014-12-04 07:23:53 +00002615void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002616 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2617 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002618 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002619 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002620 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002621 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002622}
2623
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002624void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002625 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2626 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002627 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002628 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002629 Expr *Hint = nullptr;
2630 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2631 Hint = HintClause->getHint();
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002632 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002633 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2634 S.getDirectiveName().getAsString(),
2635 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002636}
2637
Alexey Bataev671605e2015-04-13 05:28:11 +00002638void CodeGenFunction::EmitOMPParallelForDirective(
2639 const OMPParallelForDirective &S) {
2640 // Emit directive as a combined directive that consists of two implicit
2641 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002642 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002643 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002644 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2645 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002646 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002647 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2648 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002649}
2650
Alexander Musmane4e893b2014-09-23 09:33:00 +00002651void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002652 const OMPParallelForSimdDirective &S) {
2653 // Emit directive as a combined directive that consists of two implicit
2654 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002655 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002656 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2657 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002658 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002659 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2660 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002661}
2662
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002663void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002664 const OMPParallelSectionsDirective &S) {
2665 // Emit directive as a combined directive that consists of two implicit
2666 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002667 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2668 CGF.EmitSections(S);
2669 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002670 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2671 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002672}
2673
Alexey Bataev7292c292016-04-25 12:22:29 +00002674void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2675 const RegionCodeGenTy &BodyGen,
2676 const TaskGenTy &TaskGen,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002677 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002678 // Emit outlined function for task construct.
2679 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002680 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002681 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002682 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002683 // Check if the task is final
2684 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2685 // If the condition constant folds and can be elided, try to avoid emitting
2686 // the condition and the dead arm of the if/else.
2687 auto *Cond = Clause->getCondition();
2688 bool CondConstant;
2689 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2690 Data.Final.setInt(CondConstant);
2691 else
2692 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2693 } else {
2694 // By default the task is not final.
2695 Data.Final.setInt(/*IntVal=*/false);
2696 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002697 // Check if the task has 'priority' clause.
2698 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002699 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002700 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002701 Data.Priority.setPointer(EmitScalarConversion(
2702 EmitScalarExpr(Prio), Prio->getType(),
2703 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2704 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002705 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002706 // The first function argument for tasks is a thread id, the second one is a
2707 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002708 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2709 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002710 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002711 auto IRef = C->varlist_begin();
2712 for (auto *IInit : C->private_copies()) {
2713 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2714 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002715 Data.PrivateVars.push_back(*IRef);
2716 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002717 }
2718 ++IRef;
2719 }
2720 }
2721 EmittedAsPrivate.clear();
2722 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002723 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002724 auto IRef = C->varlist_begin();
2725 auto IElemInitRef = C->inits().begin();
2726 for (auto *IInit : C->private_copies()) {
2727 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2728 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002729 Data.FirstprivateVars.push_back(*IRef);
2730 Data.FirstprivateCopies.push_back(IInit);
2731 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002732 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002733 ++IRef;
2734 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002735 }
2736 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002737 // Get list of lastprivate variables (for taskloops).
2738 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2739 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2740 auto IRef = C->varlist_begin();
2741 auto ID = C->destination_exprs().begin();
2742 for (auto *IInit : C->private_copies()) {
2743 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2744 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2745 Data.LastprivateVars.push_back(*IRef);
2746 Data.LastprivateCopies.push_back(IInit);
2747 }
2748 LastprivateDstsOrigs.insert(
2749 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2750 cast<DeclRefExpr>(*IRef)});
2751 ++IRef;
2752 ++ID;
2753 }
2754 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002755 SmallVector<const Expr *, 4> LHSs;
2756 SmallVector<const Expr *, 4> RHSs;
2757 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2758 auto IPriv = C->privates().begin();
2759 auto IRed = C->reduction_ops().begin();
2760 auto ILHS = C->lhs_exprs().begin();
2761 auto IRHS = C->rhs_exprs().begin();
2762 for (const auto *Ref : C->varlists()) {
2763 Data.ReductionVars.emplace_back(Ref);
2764 Data.ReductionCopies.emplace_back(*IPriv);
2765 Data.ReductionOps.emplace_back(*IRed);
2766 LHSs.emplace_back(*ILHS);
2767 RHSs.emplace_back(*IRHS);
2768 std::advance(IPriv, 1);
2769 std::advance(IRed, 1);
2770 std::advance(ILHS, 1);
2771 std::advance(IRHS, 1);
2772 }
2773 }
2774 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2775 *this, S.getLocStart(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002776 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002777 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2778 for (auto *IRef : C->varlists())
2779 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002780 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs](
Alexey Bataevf93095a2016-05-05 08:46:22 +00002781 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002782 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002783 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002784 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2785 !Data.LastprivateVars.empty()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00002786 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataev48591dd2016-04-20 04:01:36 +00002787 auto *CopyFn = CGF.Builder.CreateLoad(
2788 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2789 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2790 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2791 // Map privates.
2792 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2793 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2794 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002795 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002796 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2797 Address PrivatePtr = CGF.CreateMemTemp(
2798 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2799 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2800 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002801 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002802 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002803 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2804 Address PrivatePtr =
2805 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2806 ".firstpriv.ptr.addr");
2807 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2808 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002809 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002810 for (auto *E : Data.LastprivateVars) {
2811 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2812 Address PrivatePtr =
2813 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2814 ".lastpriv.ptr.addr");
2815 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2816 CallArgs.push_back(PrivatePtr.getPointer());
2817 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00002818 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
2819 CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002820 for (auto &&Pair : LastprivateDstsOrigs) {
2821 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2822 DeclRefExpr DRE(
2823 const_cast<VarDecl *>(OrigVD),
2824 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2825 OrigVD) != nullptr,
2826 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2827 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2828 return CGF.EmitLValue(&DRE).getAddress();
2829 });
2830 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002831 for (auto &&Pair : PrivatePtrs) {
2832 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2833 CGF.getContext().getDeclAlign(Pair.first));
2834 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2835 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002836 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002837 if (Data.Reductions) {
2838 OMPLexicalScope LexScope(CGF, S, /*AsInlined=*/true);
2839 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2840 Data.ReductionOps);
2841 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2842 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2843 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2844 RedCG.emitSharedLValue(CGF, Cnt);
2845 RedCG.emitAggregateType(CGF, Cnt);
2846 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2847 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2848 Replacement =
2849 Address(CGF.EmitScalarConversion(
2850 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2851 CGF.getContext().getPointerType(
2852 Data.ReductionCopies[Cnt]->getType()),
2853 SourceLocation()),
2854 Replacement.getAlignment());
2855 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2856 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2857 [Replacement]() { return Replacement; });
2858 // FIXME: This must removed once the runtime library is fixed.
2859 // Emit required threadprivate variables for
2860 // initilizer/combiner/finalizer.
2861 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2862 RedCG, Cnt);
2863 }
2864 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002865 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002866 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002867 SmallVector<const Expr *, 4> InRedVars;
2868 SmallVector<const Expr *, 4> InRedPrivs;
2869 SmallVector<const Expr *, 4> InRedOps;
2870 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2871 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2872 auto IPriv = C->privates().begin();
2873 auto IRed = C->reduction_ops().begin();
2874 auto ITD = C->taskgroup_descriptors().begin();
2875 for (const auto *Ref : C->varlists()) {
2876 InRedVars.emplace_back(Ref);
2877 InRedPrivs.emplace_back(*IPriv);
2878 InRedOps.emplace_back(*IRed);
2879 TaskgroupDescriptors.emplace_back(*ITD);
2880 std::advance(IPriv, 1);
2881 std::advance(IRed, 1);
2882 std::advance(ITD, 1);
2883 }
2884 }
2885 // Privatize in_reduction items here, because taskgroup descriptors must be
2886 // privatized earlier.
2887 OMPPrivateScope InRedScope(CGF);
2888 if (!InRedVars.empty()) {
2889 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2890 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2891 RedCG.emitSharedLValue(CGF, Cnt);
2892 RedCG.emitAggregateType(CGF, Cnt);
2893 // The taskgroup descriptor variable is always implicit firstprivate and
2894 // privatized already during procoessing of the firstprivates.
2895 llvm::Value *ReductionsPtr = CGF.EmitLoadOfScalar(
2896 CGF.EmitLValue(TaskgroupDescriptors[Cnt]), SourceLocation());
2897 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2898 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2899 Replacement = Address(
2900 CGF.EmitScalarConversion(
2901 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2902 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
2903 SourceLocation()),
2904 Replacement.getAlignment());
2905 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2906 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2907 [Replacement]() { return Replacement; });
2908 // FIXME: This must removed once the runtime library is fixed.
2909 // Emit required threadprivate variables for
2910 // initilizer/combiner/finalizer.
2911 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2912 RedCG, Cnt);
2913 }
2914 }
2915 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00002916
2917 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002918 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002919 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002920 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2921 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2922 Data.NumberOfParts);
2923 OMPLexicalScope Scope(*this, S);
2924 TaskGen(*this, OutlinedFn, Data);
2925}
2926
2927void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2928 // Emit outlined function for task construct.
2929 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2930 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002931 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002932 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002933 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2934 if (C->getNameModifier() == OMPD_unknown ||
2935 C->getNameModifier() == OMPD_task) {
2936 IfCond = C->getCondition();
2937 break;
2938 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002939 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002940
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002941 OMPTaskDataTy Data;
2942 // Check if we should emit tied or untied task.
2943 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00002944 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
2945 CGF.EmitStmt(CS->getCapturedStmt());
2946 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002947 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00002948 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002949 const OMPTaskDataTy &Data) {
2950 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
2951 SharedsTy, CapturedStruct, IfCond,
2952 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00002953 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002954 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002955}
2956
Alexey Bataev9f797f32015-02-05 05:57:51 +00002957void CodeGenFunction::EmitOMPTaskyieldDirective(
2958 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002959 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002960}
2961
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002962void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002963 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002964}
2965
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002966void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2967 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002968}
2969
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002970void CodeGenFunction::EmitOMPTaskgroupDirective(
2971 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002972 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2973 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002974 if (const Expr *E = S.getReductionRef()) {
2975 SmallVector<const Expr *, 4> LHSs;
2976 SmallVector<const Expr *, 4> RHSs;
2977 OMPTaskDataTy Data;
2978 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
2979 auto IPriv = C->privates().begin();
2980 auto IRed = C->reduction_ops().begin();
2981 auto ILHS = C->lhs_exprs().begin();
2982 auto IRHS = C->rhs_exprs().begin();
2983 for (const auto *Ref : C->varlists()) {
2984 Data.ReductionVars.emplace_back(Ref);
2985 Data.ReductionCopies.emplace_back(*IPriv);
2986 Data.ReductionOps.emplace_back(*IRed);
2987 LHSs.emplace_back(*ILHS);
2988 RHSs.emplace_back(*IRHS);
2989 std::advance(IPriv, 1);
2990 std::advance(IRed, 1);
2991 std::advance(ILHS, 1);
2992 std::advance(IRHS, 1);
2993 }
2994 }
2995 llvm::Value *ReductionDesc =
2996 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getLocStart(),
2997 LHSs, RHSs, Data);
2998 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2999 CGF.EmitVarDecl(*VD);
3000 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3001 /*Volatile=*/false, E->getType());
3002 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003003 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003004 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003005 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003006 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
3007}
3008
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003009void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003010 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003011 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003012 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3013 FlushClause->varlist_end());
3014 }
3015 return llvm::None;
3016 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00003017}
3018
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003019void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3020 const CodeGenLoopTy &CodeGenLoop,
3021 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003022 // Emit the loop iteration variable.
3023 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3024 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
3025 EmitVarDecl(*IVDecl);
3026
3027 // Emit the iterations count variable.
3028 // If it is not a variable, Sema decided to calculate iterations count on each
3029 // iteration (e.g., it is foldable into a constant).
3030 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3031 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3032 // Emit calculation of the iterations count.
3033 EmitIgnoredExpr(S.getCalcLastIteration());
3034 }
3035
3036 auto &RT = CGM.getOpenMPRuntime();
3037
Carlo Bertolli962bb802017-01-03 18:24:42 +00003038 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003039 // Check pre-condition.
3040 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003041 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003042 // Skip the entire loop if we don't meet the precondition.
3043 // If the condition constant folds and can be elided, avoid emitting the
3044 // whole loop.
3045 bool CondConstant;
3046 llvm::BasicBlock *ContBlock = nullptr;
3047 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3048 if (!CondConstant)
3049 return;
3050 } else {
3051 auto *ThenBlock = createBasicBlock("omp.precond.then");
3052 ContBlock = createBasicBlock("omp.precond.end");
3053 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3054 getProfileCount(&S));
3055 EmitBlock(ThenBlock);
3056 incrementProfileCounter(&S);
3057 }
3058
Alexey Bataev617db5f2017-12-04 15:38:33 +00003059 emitAlignedClause(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003060 // Emit 'then' code.
3061 {
3062 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003063
3064 LValue LB = EmitOMPHelperVar(
3065 *this, cast<DeclRefExpr>(
3066 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3067 ? S.getCombinedLowerBoundVariable()
3068 : S.getLowerBoundVariable())));
3069 LValue UB = EmitOMPHelperVar(
3070 *this, cast<DeclRefExpr>(
3071 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3072 ? S.getCombinedUpperBoundVariable()
3073 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003074 LValue ST =
3075 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3076 LValue IL =
3077 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3078
3079 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003080 if (EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003081 // Emit implicit barrier to synchronize threads and avoid data races
3082 // on initialization of firstprivate variables and post-update of
Carlo Bertolli962bb802017-01-03 18:24:42 +00003083 // lastprivate variables.
3084 CGM.getOpenMPRuntime().emitBarrierCall(
Alexey Bataev617db5f2017-12-04 15:38:33 +00003085 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3086 /*ForceSimpleCall=*/true);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003087 }
3088 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev617db5f2017-12-04 15:38:33 +00003089 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
Alexey Bataev999277a2017-12-06 14:31:09 +00003090 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3091 !isOpenMPTeamsDirective(S.getDirectiveKind()))
Alexey Bataev617db5f2017-12-04 15:38:33 +00003092 EmitOMPReductionClauseInit(S, LoopScope);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003093 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003094 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003095 (void)LoopScope.Privatize();
3096
3097 // Detect the distribute schedule kind and chunk.
3098 llvm::Value *Chunk = nullptr;
3099 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3100 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3101 ScheduleKind = C->getDistScheduleKind();
3102 if (const auto *Ch = C->getChunkSize()) {
3103 Chunk = EmitScalarExpr(Ch);
3104 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
Alexey Bataev617db5f2017-12-04 15:38:33 +00003105 S.getIterationVariable()->getType(),
3106 S.getLocStart());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003107 }
3108 }
3109 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3110 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3111
3112 // OpenMP [2.10.8, distribute Construct, Description]
3113 // If dist_schedule is specified, kind must be static. If specified,
3114 // iterations are divided into chunks of size chunk_size, chunks are
3115 // assigned to the teams of the league in a round-robin fashion in the
3116 // order of the team number. When no chunk_size is specified, the
3117 // iteration space is divided into chunks that are approximately equal
3118 // in size, and at most one chunk is distributed to each team of the
3119 // league. The size of the chunks is unspecified in this case.
3120 if (RT.isStaticNonchunked(ScheduleKind,
3121 /* Chunked */ Chunk != nullptr)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003122 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3123 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003124 CGOpenMPRuntime::StaticRTInput StaticInit(
3125 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3126 LB.getAddress(), UB.getAddress(), ST.getAddress());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003127 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003128 StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003129 auto LoopExit =
3130 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3131 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003132 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3133 ? S.getCombinedEnsureUpperBound()
3134 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003135 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003136 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3137 ? S.getCombinedInit()
3138 : S.getInit());
3139
3140 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3141 ? S.getCombinedCond()
3142 : S.getCond();
3143
3144 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003145 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003146 // when combined with 'for' (e.g. as in 'distribute parallel for')
3147 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3148 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3149 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3150 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003151 },
3152 [](CodeGenFunction &) {});
3153 EmitBlock(LoopExit.getBlock());
3154 // Tell the runtime we are done.
Alexey Bataevf43f7142017-09-06 16:17:35 +00003155 RT.emitForStaticFinish(*this, S.getLocStart(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003156 } else {
3157 // Emit the outer loop, which requests its work chunk [LB..UB] from
3158 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003159 const OMPLoopArguments LoopArguments = {
3160 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3161 Chunk};
3162 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3163 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003164 }
Alexey Bataev617db5f2017-12-04 15:38:33 +00003165 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3166 EmitOMPSimdFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3167 return CGF.Builder.CreateIsNotNull(
3168 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3169 });
3170 }
3171 OpenMPDirectiveKind ReductionKind = OMPD_unknown;
3172 if (isOpenMPParallelDirective(S.getDirectiveKind()) &&
3173 isOpenMPSimdDirective(S.getDirectiveKind())) {
3174 ReductionKind = OMPD_parallel_for_simd;
3175 } else if (isOpenMPParallelDirective(S.getDirectiveKind())) {
3176 ReductionKind = OMPD_parallel_for;
3177 } else if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3178 ReductionKind = OMPD_simd;
3179 } else if (!isOpenMPTeamsDirective(S.getDirectiveKind()) &&
3180 S.hasClausesOfKind<OMPReductionClause>()) {
3181 llvm_unreachable(
3182 "No reduction clauses is allowed in distribute directive.");
3183 }
3184 EmitOMPReductionClauseFinal(S, ReductionKind);
3185 // Emit post-update of the reduction variables if IsLastIter != 0.
3186 emitPostUpdateForReductionClause(
3187 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3188 return CGF.Builder.CreateIsNotNull(
3189 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3190 });
Carlo Bertolli962bb802017-01-03 18:24:42 +00003191 // Emit final copy of the lastprivate variables if IsLastIter != 0.
Alexey Bataev617db5f2017-12-04 15:38:33 +00003192 if (HasLastprivateClause) {
Carlo Bertolli962bb802017-01-03 18:24:42 +00003193 EmitOMPLastprivateClauseFinal(
3194 S, /*NoFinals=*/false,
Alexey Bataev617db5f2017-12-04 15:38:33 +00003195 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
3196 }
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003197 }
3198
3199 // We're now done with the loop, so jump to the continuation block.
3200 if (ContBlock) {
3201 EmitBranch(ContBlock);
3202 EmitBlock(ContBlock, true);
3203 }
3204 }
3205}
3206
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003207void CodeGenFunction::EmitOMPDistributeDirective(
3208 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003209 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003210
3211 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003212 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003213 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev10a54312017-11-27 16:54:08 +00003214 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003215}
3216
Alexey Bataev5f600d62015-09-29 03:48:57 +00003217static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3218 const CapturedStmt *S) {
3219 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3220 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3221 CGF.CapturedStmtInfo = &CapStmtInfo;
3222 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3223 Fn->addFnAttr(llvm::Attribute::NoInline);
3224 return Fn;
3225}
3226
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003227void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8b427062016-05-25 12:36:08 +00003228 if (!S.getAssociatedStmt()) {
3229 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3230 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003231 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003232 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003233 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003234 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3235 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003236 if (C) {
3237 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3238 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3239 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3240 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Alexey Bataev3c595a62017-08-14 15:01:03 +00003241 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3242 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003243 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003244 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003245 CGF.EmitStmt(
3246 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3247 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003248 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003249 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003250 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003251}
3252
Alexey Bataevb57056f2015-01-22 06:17:56 +00003253static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003254 QualType SrcType, QualType DestType,
3255 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003256 assert(CGF.hasScalarEvaluationKind(DestType) &&
3257 "DestType must have scalar evaluation kind.");
3258 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3259 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003260 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3261 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00003262 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003263 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003264}
3265
3266static CodeGenFunction::ComplexPairTy
3267convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003268 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003269 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3270 "DestType must have complex evaluation kind.");
3271 CodeGenFunction::ComplexPairTy ComplexVal;
3272 if (Val.isScalar()) {
3273 // Convert the input element to the element type of the complex.
3274 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003275 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3276 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003277 ComplexVal = CodeGenFunction::ComplexPairTy(
3278 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3279 } else {
3280 assert(Val.isComplex() && "Must be a scalar or complex.");
3281 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3282 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3283 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003284 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003285 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003286 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003287 }
3288 return ComplexVal;
3289}
3290
Alexey Bataev5e018f92015-04-23 06:35:10 +00003291static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3292 LValue LVal, RValue RVal) {
3293 if (LVal.isGlobalReg()) {
3294 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3295 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003296 CGF.EmitAtomicStore(RVal, LVal,
3297 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3298 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003299 LVal.isVolatile(), /*IsInit=*/false);
3300 }
3301}
3302
Alexey Bataev8524d152016-01-21 12:35:58 +00003303void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3304 QualType RValTy, SourceLocation Loc) {
3305 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003306 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003307 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3308 *this, RVal, RValTy, LVal.getType(), Loc)),
3309 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003310 break;
3311 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003312 EmitStoreOfComplex(
3313 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003314 /*isInit=*/false);
3315 break;
3316 case TEK_Aggregate:
3317 llvm_unreachable("Must be a scalar or complex.");
3318 }
3319}
3320
Alexey Bataevb57056f2015-01-22 06:17:56 +00003321static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3322 const Expr *X, const Expr *V,
3323 SourceLocation Loc) {
3324 // v = x;
3325 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3326 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3327 LValue XLValue = CGF.EmitLValue(X);
3328 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003329 RValue Res = XLValue.isGlobalReg()
3330 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003331 : CGF.EmitAtomicLoad(
3332 XLValue, Loc,
3333 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3334 : llvm::AtomicOrdering::Monotonic,
3335 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003336 // OpenMP, 2.12.6, atomic Construct
3337 // Any atomic construct with a seq_cst clause forces the atomically
3338 // performed operation to include an implicit flush operation without a
3339 // list.
3340 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003341 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003342 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003343}
3344
Alexey Bataevb8329262015-02-27 06:33:30 +00003345static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3346 const Expr *X, const Expr *E,
3347 SourceLocation Loc) {
3348 // x = expr;
3349 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003350 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003351 // OpenMP, 2.12.6, atomic Construct
3352 // Any atomic construct with a seq_cst clause forces the atomically
3353 // performed operation to include an implicit flush operation without a
3354 // list.
3355 if (IsSeqCst)
3356 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3357}
3358
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003359static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3360 RValue Update,
3361 BinaryOperatorKind BO,
3362 llvm::AtomicOrdering AO,
3363 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003364 auto &Context = CGF.CGM.getContext();
3365 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003366 // expression is simple and atomic is allowed for the given type for the
3367 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003368 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003369 !Update.getScalarVal()->getType()->isIntegerTy() ||
3370 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3371 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003372 X.getAddress().getElementType())) ||
3373 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003374 !Context.getTargetInfo().hasBuiltinAtomic(
3375 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003376 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003377
3378 llvm::AtomicRMWInst::BinOp RMWOp;
3379 switch (BO) {
3380 case BO_Add:
3381 RMWOp = llvm::AtomicRMWInst::Add;
3382 break;
3383 case BO_Sub:
3384 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003385 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003386 RMWOp = llvm::AtomicRMWInst::Sub;
3387 break;
3388 case BO_And:
3389 RMWOp = llvm::AtomicRMWInst::And;
3390 break;
3391 case BO_Or:
3392 RMWOp = llvm::AtomicRMWInst::Or;
3393 break;
3394 case BO_Xor:
3395 RMWOp = llvm::AtomicRMWInst::Xor;
3396 break;
3397 case BO_LT:
3398 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3399 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3400 : llvm::AtomicRMWInst::Max)
3401 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3402 : llvm::AtomicRMWInst::UMax);
3403 break;
3404 case BO_GT:
3405 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3406 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3407 : llvm::AtomicRMWInst::Min)
3408 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3409 : llvm::AtomicRMWInst::UMin);
3410 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003411 case BO_Assign:
3412 RMWOp = llvm::AtomicRMWInst::Xchg;
3413 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003414 case BO_Mul:
3415 case BO_Div:
3416 case BO_Rem:
3417 case BO_Shl:
3418 case BO_Shr:
3419 case BO_LAnd:
3420 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003421 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003422 case BO_PtrMemD:
3423 case BO_PtrMemI:
3424 case BO_LE:
3425 case BO_GE:
3426 case BO_EQ:
3427 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003428 case BO_AddAssign:
3429 case BO_SubAssign:
3430 case BO_AndAssign:
3431 case BO_OrAssign:
3432 case BO_XorAssign:
3433 case BO_MulAssign:
3434 case BO_DivAssign:
3435 case BO_RemAssign:
3436 case BO_ShlAssign:
3437 case BO_ShrAssign:
3438 case BO_Comma:
3439 llvm_unreachable("Unsupported atomic update operation");
3440 }
3441 auto *UpdateVal = Update.getScalarVal();
3442 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3443 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003444 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003445 X.getType()->hasSignedIntegerRepresentation());
3446 }
John McCall7f416cc2015-09-08 08:05:57 +00003447 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003448 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003449}
3450
Alexey Bataev5e018f92015-04-23 06:35:10 +00003451std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003452 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3453 llvm::AtomicOrdering AO, SourceLocation Loc,
3454 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3455 // Update expressions are allowed to have the following forms:
3456 // x binop= expr; -> xrval + expr;
3457 // x++, ++x -> xrval + 1;
3458 // x--, --x -> xrval - 1;
3459 // x = x binop expr; -> xrval binop expr
3460 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003461 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3462 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003463 if (X.isGlobalReg()) {
3464 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3465 // 'xrval'.
3466 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3467 } else {
3468 // Perform compare-and-swap procedure.
3469 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003470 }
3471 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003472 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003473}
3474
3475static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3476 const Expr *X, const Expr *E,
3477 const Expr *UE, bool IsXLHSInRHSPart,
3478 SourceLocation Loc) {
3479 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3480 "Update expr in 'atomic update' must be a binary operator.");
3481 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3482 // Update expressions are allowed to have the following forms:
3483 // x binop= expr; -> xrval + expr;
3484 // x++, ++x -> xrval + 1;
3485 // x--, --x -> xrval - 1;
3486 // x = x binop expr; -> xrval binop expr
3487 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003488 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003489 LValue XLValue = CGF.EmitLValue(X);
3490 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003491 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3492 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003493 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3494 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3495 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3496 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3497 auto Gen =
3498 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3499 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3500 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3501 return CGF.EmitAnyExpr(UE);
3502 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003503 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3504 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3505 // OpenMP, 2.12.6, atomic Construct
3506 // Any atomic construct with a seq_cst clause forces the atomically
3507 // performed operation to include an implicit flush operation without a
3508 // list.
3509 if (IsSeqCst)
3510 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3511}
3512
3513static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003514 QualType SourceType, QualType ResType,
3515 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003516 switch (CGF.getEvaluationKind(ResType)) {
3517 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003518 return RValue::get(
3519 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003520 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003521 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003522 return RValue::getComplex(Res.first, Res.second);
3523 }
3524 case TEK_Aggregate:
3525 break;
3526 }
3527 llvm_unreachable("Must be a scalar or complex.");
3528}
3529
3530static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3531 bool IsPostfixUpdate, const Expr *V,
3532 const Expr *X, const Expr *E,
3533 const Expr *UE, bool IsXLHSInRHSPart,
3534 SourceLocation Loc) {
3535 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3536 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3537 RValue NewVVal;
3538 LValue VLValue = CGF.EmitLValue(V);
3539 LValue XLValue = CGF.EmitLValue(X);
3540 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003541 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3542 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003543 QualType NewVValType;
3544 if (UE) {
3545 // 'x' is updated with some additional value.
3546 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3547 "Update expr in 'atomic capture' must be a binary operator.");
3548 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3549 // Update expressions are allowed to have the following forms:
3550 // x binop= expr; -> xrval + expr;
3551 // x++, ++x -> xrval + 1;
3552 // x--, --x -> xrval - 1;
3553 // x = x binop expr; -> xrval binop expr
3554 // x = expr Op x; - > expr binop xrval;
3555 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3556 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3557 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3558 NewVValType = XRValExpr->getType();
3559 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3560 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003561 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003562 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3563 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3564 RValue Res = CGF.EmitAnyExpr(UE);
3565 NewVVal = IsPostfixUpdate ? XRValue : Res;
3566 return Res;
3567 };
3568 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3569 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3570 if (Res.first) {
3571 // 'atomicrmw' instruction was generated.
3572 if (IsPostfixUpdate) {
3573 // Use old value from 'atomicrmw'.
3574 NewVVal = Res.second;
3575 } else {
3576 // 'atomicrmw' does not provide new value, so evaluate it using old
3577 // value of 'x'.
3578 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3579 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3580 NewVVal = CGF.EmitAnyExpr(UE);
3581 }
3582 }
3583 } else {
3584 // 'x' is simply rewritten with some 'expr'.
3585 NewVValType = X->getType().getNonReferenceType();
3586 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003587 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003588 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003589 NewVVal = XRValue;
3590 return ExprRValue;
3591 };
3592 // Try to perform atomicrmw xchg, otherwise simple exchange.
3593 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3594 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3595 Loc, Gen);
3596 if (Res.first) {
3597 // 'atomicrmw' instruction was generated.
3598 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3599 }
3600 }
3601 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003602 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003603 // OpenMP, 2.12.6, atomic Construct
3604 // Any atomic construct with a seq_cst clause forces the atomically
3605 // performed operation to include an implicit flush operation without a
3606 // list.
3607 if (IsSeqCst)
3608 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3609}
3610
Alexey Bataevb57056f2015-01-22 06:17:56 +00003611static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003612 bool IsSeqCst, bool IsPostfixUpdate,
3613 const Expr *X, const Expr *V, const Expr *E,
3614 const Expr *UE, bool IsXLHSInRHSPart,
3615 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003616 switch (Kind) {
3617 case OMPC_read:
3618 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3619 break;
3620 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003621 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3622 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003623 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003624 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003625 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3626 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003627 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003628 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3629 IsXLHSInRHSPart, Loc);
3630 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003631 case OMPC_if:
3632 case OMPC_final:
3633 case OMPC_num_threads:
3634 case OMPC_private:
3635 case OMPC_firstprivate:
3636 case OMPC_lastprivate:
3637 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003638 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003639 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003640 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003641 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003642 case OMPC_collapse:
3643 case OMPC_default:
3644 case OMPC_seq_cst:
3645 case OMPC_shared:
3646 case OMPC_linear:
3647 case OMPC_aligned:
3648 case OMPC_copyin:
3649 case OMPC_copyprivate:
3650 case OMPC_flush:
3651 case OMPC_proc_bind:
3652 case OMPC_schedule:
3653 case OMPC_ordered:
3654 case OMPC_nowait:
3655 case OMPC_untied:
3656 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003657 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003658 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003659 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003660 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003661 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003662 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003663 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003664 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003665 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003666 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003667 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003668 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003669 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003670 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003671 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003672 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003673 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003674 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003675 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003676 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003677 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3678 }
3679}
3680
3681void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003682 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003683 OpenMPClauseKind Kind = OMPC_unknown;
3684 for (auto *C : S.clauses()) {
3685 // Find first clause (skip seq_cst clause, if it is first).
3686 if (C->getClauseKind() != OMPC_seq_cst) {
3687 Kind = C->getClauseKind();
3688 break;
3689 }
3690 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003691
3692 const auto *CS =
3693 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003694 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003695 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003696 }
3697 // Processing for statements under 'atomic capture'.
3698 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3699 for (const auto *C : Compound->body()) {
3700 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3701 enterFullExpression(EWC);
3702 }
3703 }
3704 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003705
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003706 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3707 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003708 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003709 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3710 S.getV(), S.getExpr(), S.getUpdateExpr(),
3711 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003712 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003713 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003714 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003715}
3716
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003717static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3718 const OMPExecutableDirective &S,
3719 const RegionCodeGenTy &CodeGen) {
3720 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3721 CodeGenModule &CGM = CGF.CGM;
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00003722 const CapturedStmt &CS = *S.getCapturedStmt(OMPD_target);
Samuel Antaobed3c462015-10-02 16:14:20 +00003723
Samuel Antaoee8fb302016-01-06 13:42:12 +00003724 llvm::Function *Fn = nullptr;
3725 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003726
Samuel Antaobed3c462015-10-02 16:14:20 +00003727 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003728 // Check for the at most one if clause associated with the target region.
3729 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3730 if (C->getNameModifier() == OMPD_unknown ||
3731 C->getNameModifier() == OMPD_target) {
3732 IfCond = C->getCondition();
3733 break;
3734 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003735 }
3736
3737 // Check if we have any device clause associated with the directive.
3738 const Expr *Device = nullptr;
3739 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3740 Device = C->getDevice();
3741 }
3742
Samuel Antaoee8fb302016-01-06 13:42:12 +00003743 // Check if we have an if clause whose conditional always evaluates to false
3744 // or if we do not have any targets specified. If so the target region is not
3745 // an offload entry point.
3746 bool IsOffloadEntry = true;
3747 if (IfCond) {
3748 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003749 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003750 IsOffloadEntry = false;
3751 }
3752 if (CGM.getLangOpts().OMPTargetTriples.empty())
3753 IsOffloadEntry = false;
3754
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003755 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003756 StringRef ParentName;
3757 // In case we have Ctors/Dtors we use the complete type variant to produce
3758 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003759 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003760 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003761 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003762 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3763 else
3764 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003765 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003766
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003767 // Emit target region as a standalone region.
3768 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3769 IsOffloadEntry, CodeGen);
3770 OMPLexicalScope Scope(CGF, S);
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003771 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3772 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003773 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003774 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003775}
3776
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003777static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3778 PrePostActionTy &Action) {
3779 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3780 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3781 CGF.EmitOMPPrivateClause(S, PrivateScope);
3782 (void)PrivateScope.Privatize();
3783
3784 Action.Enter(CGF);
3785 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3786}
3787
3788void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3789 StringRef ParentName,
3790 const OMPTargetDirective &S) {
3791 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3792 emitTargetRegion(CGF, S, Action);
3793 };
3794 llvm::Function *Fn;
3795 llvm::Constant *Addr;
3796 // Emit target region as a standalone region.
3797 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3798 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3799 assert(Fn && Addr && "Target device function emission failed.");
3800}
3801
3802void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3803 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3804 emitTargetRegion(CGF, S, Action);
3805 };
3806 emitCommonOMPTargetDirective(*this, S, CodeGen);
3807}
3808
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003809static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3810 const OMPExecutableDirective &S,
3811 OpenMPDirectiveKind InnermostKind,
3812 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003813 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
3814 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
3815 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003816
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003817 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
3818 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003819 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003820 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3821 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003822
Carlo Bertollic6872252016-04-04 15:55:02 +00003823 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3824 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003825 }
3826
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003827 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003828 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3829 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003830 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3831 CapturedVars);
3832}
3833
3834void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00003835 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003836 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003837 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003838 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3839 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003840 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003841 (void)PrivateScope.Privatize();
3842 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003843 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003844 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00003845 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003846 emitPostUpdateForReductionClause(
3847 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00003848}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003849
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003850static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
3851 const OMPTargetTeamsDirective &S) {
3852 auto *CS = S.getCapturedStmt(OMPD_teams);
3853 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00003854 // Emit teams region as a standalone region.
3855 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
3856 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3857 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3858 CGF.EmitOMPPrivateClause(S, PrivateScope);
3859 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3860 (void)PrivateScope.Privatize();
3861 Action.Enter(CGF);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003862 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00003863 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003864 };
3865 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00003866 emitPostUpdateForReductionClause(
3867 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003868}
3869
3870void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
3871 CodeGenModule &CGM, StringRef ParentName,
3872 const OMPTargetTeamsDirective &S) {
3873 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3874 emitTargetTeamsRegion(CGF, Action, S);
3875 };
3876 llvm::Function *Fn;
3877 llvm::Constant *Addr;
3878 // Emit target region as a standalone region.
3879 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3880 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3881 assert(Fn && Addr && "Target device function emission failed.");
3882}
3883
3884void CodeGenFunction::EmitOMPTargetTeamsDirective(
3885 const OMPTargetTeamsDirective &S) {
3886 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3887 emitTargetTeamsRegion(CGF, Action, S);
3888 };
3889 emitCommonOMPTargetDirective(*this, S, CodeGen);
3890}
3891
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003892void CodeGenFunction::EmitOMPTeamsDistributeDirective(
3893 const OMPTeamsDistributeDirective &S) {
3894
3895 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3896 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
3897 };
3898
3899 // Emit teams region as a standalone region.
3900 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
3901 PrePostActionTy &) {
3902 OMPPrivateScope PrivateScope(CGF);
3903 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3904 (void)PrivateScope.Privatize();
3905 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
3906 CodeGenDistribute);
3907 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3908 };
Alexey Bataev95c6dd42017-11-29 15:14:16 +00003909 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003910 emitPostUpdateForReductionClause(*this, S,
3911 [](CodeGenFunction &) { return nullptr; });
3912}
3913
Alexey Bataev999277a2017-12-06 14:31:09 +00003914void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
3915 const OMPTeamsDistributeSimdDirective &S) {
3916 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3917 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
3918 };
3919
3920 // Emit teams region as a standalone region.
3921 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
3922 PrePostActionTy &) {
3923 OMPPrivateScope PrivateScope(CGF);
3924 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3925 (void)PrivateScope.Privatize();
3926 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
3927 CodeGenDistribute);
3928 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3929 };
3930 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
3931 emitPostUpdateForReductionClause(*this, S,
3932 [](CodeGenFunction &) { return nullptr; });
3933}
3934
Carlo Bertolli62fae152017-11-20 20:46:39 +00003935void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
3936 const OMPTeamsDistributeParallelForDirective &S) {
3937 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3938 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
3939 S.getDistInc());
3940 };
3941
3942 // Emit teams region as a standalone region.
3943 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
3944 PrePostActionTy &) {
3945 OMPPrivateScope PrivateScope(CGF);
3946 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3947 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00003948 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
3949 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003950 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3951 };
3952 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
3953 emitPostUpdateForReductionClause(*this, S,
3954 [](CodeGenFunction &) { return nullptr; });
3955}
3956
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003957void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
3958 const OMPTeamsDistributeParallelForSimdDirective &S) {
3959 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3960 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
3961 S.getDistInc());
3962 };
3963
3964 // Emit teams region as a standalone region.
3965 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
3966 PrePostActionTy &) {
3967 OMPPrivateScope PrivateScope(CGF);
3968 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3969 (void)PrivateScope.Privatize();
3970 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
3971 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
3972 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3973 };
3974 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
3975 emitPostUpdateForReductionClause(*this, S,
3976 [](CodeGenFunction &) { return nullptr; });
3977}
3978
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003979void CodeGenFunction::EmitOMPCancellationPointDirective(
3980 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00003981 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
3982 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003983}
3984
Alexey Bataev80909872015-07-02 11:25:17 +00003985void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003986 const Expr *IfCond = nullptr;
3987 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3988 if (C->getNameModifier() == OMPD_unknown ||
3989 C->getNameModifier() == OMPD_cancel) {
3990 IfCond = C->getCondition();
3991 break;
3992 }
3993 }
3994 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003995 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00003996}
3997
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003998CodeGenFunction::JumpDest
3999CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00004000 if (Kind == OMPD_parallel || Kind == OMPD_task ||
4001 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004002 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004003 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00004004 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
4005 Kind == OMPD_distribute_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004006 Kind == OMPD_target_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004007 Kind == OMPD_teams_distribute_parallel_for ||
4008 Kind == OMPD_target_teams_distribute_parallel_for);
Alexey Bataev957d8562016-11-17 15:12:05 +00004009 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004010}
Michael Wong65f367f2015-07-21 13:44:28 +00004011
Samuel Antaocc10b852016-07-28 14:23:26 +00004012void CodeGenFunction::EmitOMPUseDevicePtrClause(
4013 const OMPClause &NC, OMPPrivateScope &PrivateScope,
4014 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
4015 const auto &C = cast<OMPUseDevicePtrClause>(NC);
4016 auto OrigVarIt = C.varlist_begin();
4017 auto InitIt = C.inits().begin();
4018 for (auto PvtVarIt : C.private_copies()) {
4019 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
4020 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
4021 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
4022
4023 // In order to identify the right initializer we need to match the
4024 // declaration used by the mapping logic. In some cases we may get
4025 // OMPCapturedExprDecl that refers to the original declaration.
4026 const ValueDecl *MatchingVD = OrigVD;
4027 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
4028 // OMPCapturedExprDecl are used to privative fields of the current
4029 // structure.
4030 auto *ME = cast<MemberExpr>(OED->getInit());
4031 assert(isa<CXXThisExpr>(ME->getBase()) &&
4032 "Base should be the current struct!");
4033 MatchingVD = ME->getMemberDecl();
4034 }
4035
4036 // If we don't have information about the current list item, move on to
4037 // the next one.
4038 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
4039 if (InitAddrIt == CaptureDeviceAddrMap.end())
4040 continue;
4041
4042 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
4043 // Initialize the temporary initialization variable with the address we
4044 // get from the runtime library. We have to cast the source address
4045 // because it is always a void *. References are materialized in the
4046 // privatization scope, so the initialization here disregards the fact
4047 // the original variable is a reference.
4048 QualType AddrQTy =
4049 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
4050 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
4051 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
4052 setAddrOfLocalVar(InitVD, InitAddr);
4053
4054 // Emit private declaration, it will be initialized by the value we
4055 // declaration we just added to the local declarations map.
4056 EmitDecl(*PvtVD);
4057
4058 // The initialization variables reached its purpose in the emission
4059 // ofthe previous declaration, so we don't need it anymore.
4060 LocalDeclMap.erase(InitVD);
4061
4062 // Return the address of the private variable.
4063 return GetAddrOfLocalVar(PvtVD);
4064 });
4065 assert(IsRegistered && "firstprivate var already registered as private");
4066 // Silence the warning about unused variable.
4067 (void)IsRegistered;
4068
4069 ++OrigVarIt;
4070 ++InitIt;
4071 }
4072}
4073
Michael Wong65f367f2015-07-21 13:44:28 +00004074// Generate the instructions for '#pragma omp target data' directive.
4075void CodeGenFunction::EmitOMPTargetDataDirective(
4076 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004077 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4078
4079 // Create a pre/post action to signal the privatization of the device pointer.
4080 // This action can be replaced by the OpenMP runtime code generation to
4081 // deactivate privatization.
4082 bool PrivatizeDevicePointers = false;
4083 class DevicePointerPrivActionTy : public PrePostActionTy {
4084 bool &PrivatizeDevicePointers;
4085
4086 public:
4087 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4088 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4089 void Enter(CodeGenFunction &CGF) override {
4090 PrivatizeDevicePointers = true;
4091 }
Samuel Antaodf158d52016-04-27 22:58:19 +00004092 };
Samuel Antaocc10b852016-07-28 14:23:26 +00004093 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4094
4095 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
4096 CodeGenFunction &CGF, PrePostActionTy &Action) {
4097 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4098 CGF.EmitStmt(
4099 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
4100 };
4101
4102 // Codegen that selects wheather to generate the privatization code or not.
4103 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4104 &InnermostCodeGen](CodeGenFunction &CGF,
4105 PrePostActionTy &Action) {
4106 RegionCodeGenTy RCG(InnermostCodeGen);
4107 PrivatizeDevicePointers = false;
4108
4109 // Call the pre-action to change the status of PrivatizeDevicePointers if
4110 // needed.
4111 Action.Enter(CGF);
4112
4113 if (PrivatizeDevicePointers) {
4114 OMPPrivateScope PrivateScope(CGF);
4115 // Emit all instances of the use_device_ptr clause.
4116 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4117 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4118 Info.CaptureDeviceAddrMap);
4119 (void)PrivateScope.Privatize();
4120 RCG(CGF);
4121 } else
4122 RCG(CGF);
4123 };
4124
4125 // Forward the provided action to the privatization codegen.
4126 RegionCodeGenTy PrivRCG(PrivCodeGen);
4127 PrivRCG.setAction(Action);
4128
4129 // Notwithstanding the body of the region is emitted as inlined directive,
4130 // we don't use an inline scope as changes in the references inside the
4131 // region are expected to be visible outside, so we do not privative them.
4132 OMPLexicalScope Scope(CGF, S);
4133 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4134 PrivRCG);
4135 };
4136
4137 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004138
4139 // If we don't have target devices, don't bother emitting the data mapping
4140 // code.
4141 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004142 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004143 return;
4144 }
4145
4146 // Check if we have any if clause associated with the directive.
4147 const Expr *IfCond = nullptr;
4148 if (auto *C = S.getSingleClause<OMPIfClause>())
4149 IfCond = C->getCondition();
4150
4151 // Check if we have any device clause associated with the directive.
4152 const Expr *Device = nullptr;
4153 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4154 Device = C->getDevice();
4155
Samuel Antaocc10b852016-07-28 14:23:26 +00004156 // Set the action to signal privatization of device pointers.
4157 RCG.setAction(PrivAction);
4158
4159 // Emit region code.
4160 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4161 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004162}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004163
Samuel Antaodf67fc42016-01-19 19:15:56 +00004164void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4165 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004166 // If we don't have target devices, don't bother emitting the data mapping
4167 // code.
4168 if (CGM.getLangOpts().OMPTargetTriples.empty())
4169 return;
4170
4171 // Check if we have any if clause associated with the directive.
4172 const Expr *IfCond = nullptr;
4173 if (auto *C = S.getSingleClause<OMPIfClause>())
4174 IfCond = C->getCondition();
4175
4176 // Check if we have any device clause associated with the directive.
4177 const Expr *Device = nullptr;
4178 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4179 Device = C->getDevice();
4180
Alexey Bataev7828b252017-11-21 17:08:48 +00004181 auto &&CodeGen = [&S, IfCond, Device](CodeGenFunction &CGF,
4182 PrePostActionTy &) {
4183 CGF.CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(CGF, S, IfCond,
4184 Device);
4185 };
4186 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
4187 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_target_enter_data,
4188 CodeGen);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004189}
4190
Samuel Antao72590762016-01-19 20:04:50 +00004191void CodeGenFunction::EmitOMPTargetExitDataDirective(
4192 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004193 // If we don't have target devices, don't bother emitting the data mapping
4194 // code.
4195 if (CGM.getLangOpts().OMPTargetTriples.empty())
4196 return;
4197
4198 // Check if we have any if clause associated with the directive.
4199 const Expr *IfCond = nullptr;
4200 if (auto *C = S.getSingleClause<OMPIfClause>())
4201 IfCond = C->getCondition();
4202
4203 // Check if we have any device clause associated with the directive.
4204 const Expr *Device = nullptr;
4205 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4206 Device = C->getDevice();
4207
Alexey Bataev7828b252017-11-21 17:08:48 +00004208 auto &&CodeGen = [&S, IfCond, Device](CodeGenFunction &CGF,
4209 PrePostActionTy &) {
4210 CGF.CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(CGF, S, IfCond,
4211 Device);
4212 };
4213 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
4214 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_target_exit_data,
4215 CodeGen);
Samuel Antao72590762016-01-19 20:04:50 +00004216}
4217
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004218static void emitTargetParallelRegion(CodeGenFunction &CGF,
4219 const OMPTargetParallelDirective &S,
4220 PrePostActionTy &Action) {
4221 // Get the captured statement associated with the 'parallel' region.
4222 auto *CS = S.getCapturedStmt(OMPD_parallel);
4223 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004224 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
4225 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4226 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4227 CGF.EmitOMPPrivateClause(S, PrivateScope);
4228 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4229 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004230 // TODO: Add support for clauses.
4231 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004232 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004233 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004234 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4235 emitEmptyBoundParameters);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004236 emitPostUpdateForReductionClause(
4237 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004238}
4239
4240void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4241 CodeGenModule &CGM, StringRef ParentName,
4242 const OMPTargetParallelDirective &S) {
4243 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4244 emitTargetParallelRegion(CGF, S, Action);
4245 };
4246 llvm::Function *Fn;
4247 llvm::Constant *Addr;
4248 // Emit target region as a standalone region.
4249 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4250 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4251 assert(Fn && Addr && "Target device function emission failed.");
4252}
4253
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004254void CodeGenFunction::EmitOMPTargetParallelDirective(
4255 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004256 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4257 emitTargetParallelRegion(CGF, S, Action);
4258 };
4259 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004260}
4261
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004262static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4263 const OMPTargetParallelForDirective &S,
4264 PrePostActionTy &Action) {
4265 Action.Enter(CGF);
4266 // Emit directive as a combined directive that consists of two implicit
4267 // directives: 'parallel' with 'for' directive.
4268 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev2139ed62017-11-16 18:20:21 +00004269 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4270 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004271 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4272 emitDispatchForLoopBounds);
4273 };
4274 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4275 emitEmptyBoundParameters);
4276}
4277
4278void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4279 CodeGenModule &CGM, StringRef ParentName,
4280 const OMPTargetParallelForDirective &S) {
4281 // Emit SPMD target parallel for region as a standalone region.
4282 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4283 emitTargetParallelForRegion(CGF, S, Action);
4284 };
4285 llvm::Function *Fn;
4286 llvm::Constant *Addr;
4287 // Emit target region as a standalone region.
4288 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4289 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4290 assert(Fn && Addr && "Target device function emission failed.");
4291}
4292
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004293void CodeGenFunction::EmitOMPTargetParallelForDirective(
4294 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004295 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4296 emitTargetParallelForRegion(CGF, S, Action);
4297 };
4298 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004299}
4300
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004301static void
4302emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4303 const OMPTargetParallelForSimdDirective &S,
4304 PrePostActionTy &Action) {
4305 Action.Enter(CGF);
4306 // Emit directive as a combined directive that consists of two implicit
4307 // directives: 'parallel' with 'for' directive.
4308 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4309 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4310 emitDispatchForLoopBounds);
4311 };
4312 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4313 emitEmptyBoundParameters);
4314}
4315
4316void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4317 CodeGenModule &CGM, StringRef ParentName,
4318 const OMPTargetParallelForSimdDirective &S) {
4319 // Emit SPMD target parallel for region as a standalone region.
4320 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4321 emitTargetParallelForSimdRegion(CGF, S, Action);
4322 };
4323 llvm::Function *Fn;
4324 llvm::Constant *Addr;
4325 // Emit target region as a standalone region.
4326 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4327 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4328 assert(Fn && Addr && "Target device function emission failed.");
4329}
4330
4331void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4332 const OMPTargetParallelForSimdDirective &S) {
4333 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4334 emitTargetParallelForSimdRegion(CGF, S, Action);
4335 };
4336 emitCommonOMPTargetDirective(*this, S, CodeGen);
4337}
4338
Alexey Bataev7292c292016-04-25 12:22:29 +00004339/// Emit a helper variable and return corresponding lvalue.
4340static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4341 const ImplicitParamDecl *PVD,
4342 CodeGenFunction::OMPPrivateScope &Privates) {
4343 auto *VDecl = cast<VarDecl>(Helper->getDecl());
4344 Privates.addPrivate(
4345 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
4346}
4347
4348void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4349 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4350 // Emit outlined function for task construct.
4351 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
4352 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
4353 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4354 const Expr *IfCond = nullptr;
4355 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4356 if (C->getNameModifier() == OMPD_unknown ||
4357 C->getNameModifier() == OMPD_taskloop) {
4358 IfCond = C->getCondition();
4359 break;
4360 }
4361 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004362
4363 OMPTaskDataTy Data;
4364 // Check if taskloop must be emitted without taskgroup.
4365 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004366 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004367 Data.Tied = true;
4368 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004369 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4370 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004371 Data.Schedule.setInt(/*IntVal=*/false);
4372 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004373 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4374 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004375 Data.Schedule.setInt(/*IntVal=*/true);
4376 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004377 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004378
4379 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4380 // if (PreCond) {
4381 // for (IV in 0..LastIteration) BODY;
4382 // <Final counter/linear vars updates>;
4383 // }
4384 //
4385
4386 // Emit: if (PreCond) - begin.
4387 // If the condition constant folds and can be elided, avoid emitting the
4388 // whole loop.
4389 bool CondConstant;
4390 llvm::BasicBlock *ContBlock = nullptr;
4391 OMPLoopScope PreInitScope(CGF, S);
4392 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4393 if (!CondConstant)
4394 return;
4395 } else {
4396 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4397 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4398 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4399 CGF.getProfileCount(&S));
4400 CGF.EmitBlock(ThenBlock);
4401 CGF.incrementProfileCounter(&S);
4402 }
4403
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004404 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4405 CGF.EmitOMPSimdInit(S);
4406
Alexey Bataev7292c292016-04-25 12:22:29 +00004407 OMPPrivateScope LoopScope(CGF);
4408 // Emit helper vars inits.
4409 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4410 auto *I = CS->getCapturedDecl()->param_begin();
4411 auto *LBP = std::next(I, LowerBound);
4412 auto *UBP = std::next(I, UpperBound);
4413 auto *STP = std::next(I, Stride);
4414 auto *LIP = std::next(I, LastIter);
4415 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4416 LoopScope);
4417 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4418 LoopScope);
4419 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4420 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4421 LoopScope);
4422 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004423 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004424 (void)LoopScope.Privatize();
4425 // Emit the loop iteration variable.
4426 const Expr *IVExpr = S.getIterationVariable();
4427 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4428 CGF.EmitVarDecl(*IVDecl);
4429 CGF.EmitIgnoredExpr(S.getInit());
4430
4431 // Emit the iterations count variable.
4432 // If it is not a variable, Sema decided to calculate iterations count on
4433 // each iteration (e.g., it is foldable into a constant).
4434 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4435 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4436 // Emit calculation of the iterations count.
4437 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4438 }
4439
4440 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4441 S.getInc(),
4442 [&S](CodeGenFunction &CGF) {
4443 CGF.EmitOMPLoopBody(S, JumpDest());
4444 CGF.EmitStopPoint(&S);
4445 },
4446 [](CodeGenFunction &) {});
4447 // Emit: if (PreCond) - end.
4448 if (ContBlock) {
4449 CGF.EmitBranch(ContBlock);
4450 CGF.EmitBlock(ContBlock, true);
4451 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004452 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4453 if (HasLastprivateClause) {
4454 CGF.EmitOMPLastprivateClauseFinal(
4455 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4456 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4457 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4458 (*LIP)->getType(), S.getLocStart())));
4459 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004460 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004461 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4462 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4463 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004464 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4465 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004466 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4467 OutlinedFn, SharedsTy,
4468 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004469 };
4470 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4471 CodeGen);
4472 };
Alexey Bataev33446032017-07-12 18:09:32 +00004473 if (Data.Nogroup)
4474 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4475 else {
4476 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4477 *this,
4478 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4479 PrePostActionTy &Action) {
4480 Action.Enter(CGF);
4481 CGF.EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4482 },
4483 S.getLocStart());
4484 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004485}
4486
Alexey Bataev49f6e782015-12-01 04:18:41 +00004487void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004488 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004489}
4490
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004491void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4492 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004493 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004494}
Samuel Antao686c70c2016-05-26 17:30:50 +00004495
4496// Generate the instructions for '#pragma omp target update' directive.
4497void CodeGenFunction::EmitOMPTargetUpdateDirective(
4498 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00004499 // If we don't have target devices, don't bother emitting the data mapping
4500 // code.
4501 if (CGM.getLangOpts().OMPTargetTriples.empty())
4502 return;
4503
4504 // Check if we have any if clause associated with the directive.
4505 const Expr *IfCond = nullptr;
4506 if (auto *C = S.getSingleClause<OMPIfClause>())
4507 IfCond = C->getCondition();
4508
4509 // Check if we have any device clause associated with the directive.
4510 const Expr *Device = nullptr;
4511 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4512 Device = C->getDevice();
4513
Alexey Bataev7828b252017-11-21 17:08:48 +00004514 auto &&CodeGen = [&S, IfCond, Device](CodeGenFunction &CGF,
4515 PrePostActionTy &) {
4516 CGF.CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(CGF, S, IfCond,
4517 Device);
4518 };
4519 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
4520 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_target_update,
4521 CodeGen);
Samuel Antao686c70c2016-05-26 17:30:50 +00004522}