blob: c8027e67a78bf625e48e22c5bb66e7716b29a9ce [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) {
124 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
125 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
126 for (const auto *I : PreInits->decls())
127 CGF.EmitVarDecl(cast<VarDecl>(*I));
128 }
129 }
130 }
131
132public:
133 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
134 : CodeGenFunction::RunCleanupsScope(CGF) {
135 emitPreInitStmt(CGF, S);
136 }
137};
138
Alexey Bataev3392d762016-02-16 11:18:12 +0000139} // namespace
140
Alexey Bataevf8365372017-11-17 17:57:25 +0000141static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
142 const OMPExecutableDirective &S,
143 const RegionCodeGenTy &CodeGen);
144
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000145LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
146 if (auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
147 if (auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
148 OrigVD = OrigVD->getCanonicalDecl();
149 bool IsCaptured =
150 LambdaCaptureFields.lookup(OrigVD) ||
151 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
152 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
153 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), IsCaptured,
154 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
155 return EmitLValue(&DRE);
156 }
157 }
158 return EmitLValue(E);
159}
160
Alexey Bataev1189bd02016-01-26 12:20:39 +0000161llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
162 auto &C = getContext();
163 llvm::Value *Size = nullptr;
164 auto SizeInChars = C.getTypeSizeInChars(Ty);
165 if (SizeInChars.isZero()) {
166 // getTypeSizeInChars() returns 0 for a VLA.
167 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
168 llvm::Value *ArraySize;
169 std::tie(ArraySize, Ty) = getVLASize(VAT);
170 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
171 }
172 SizeInChars = C.getTypeSizeInChars(Ty);
173 if (SizeInChars.isZero())
174 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
175 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
176 } else
177 Size = CGM.getSize(SizeInChars);
178 return Size;
179}
180
Alexey Bataev2377fe92015-09-10 08:12:02 +0000181void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000182 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000183 const RecordDecl *RD = S.getCapturedRecordDecl();
184 auto CurField = RD->field_begin();
185 auto CurCap = S.captures().begin();
186 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
187 E = S.capture_init_end();
188 I != E; ++I, ++CurField, ++CurCap) {
189 if (CurField->hasCapturedVLAType()) {
190 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000191 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000192 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000193 } else if (CurCap->capturesThis())
194 CapturedVars.push_back(CXXThisValue);
Samuel Antao6d004262016-06-16 18:39:34 +0000195 else if (CurCap->capturesVariableByCopy()) {
196 llvm::Value *CV =
197 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal();
198
199 // If the field is not a pointer, we need to save the actual value
200 // and load it as a void pointer.
201 if (!CurField->getType()->isAnyPointerType()) {
202 auto &Ctx = getContext();
203 auto DstAddr = CreateMemTemp(
204 Ctx.getUIntPtrType(),
205 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
206 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
207
208 auto *SrcAddrVal = EmitScalarConversion(
209 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
210 Ctx.getPointerType(CurField->getType()), SourceLocation());
211 LValue SrcLV =
212 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
213
214 // Store the value using the source type pointer.
215 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
216
217 // Load the value using the destination type pointer.
218 CV = EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
219 }
220 CapturedVars.push_back(CV);
221 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000222 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000223 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000224 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000225 }
226}
227
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000228static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
229 StringRef Name, LValue AddrLV,
230 bool isReferenceType = false) {
231 ASTContext &Ctx = CGF.getContext();
232
233 auto *CastedPtr = CGF.EmitScalarConversion(
234 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
235 Ctx.getPointerType(DstType), SourceLocation());
236 auto TmpAddr =
237 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
238 .getAddress();
239
240 // If we are dealing with references we need to return the address of the
241 // reference instead of the reference of the value.
242 if (isReferenceType) {
243 QualType RefType = Ctx.getLValueReferenceType(DstType);
244 auto *RefVal = TmpAddr.getPointer();
245 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
246 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
Akira Hatanaka642f7992016-10-18 19:05:41 +0000247 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000248 }
249
250 return TmpAddr;
251}
252
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000253static QualType getCanonicalParamType(ASTContext &C, QualType T) {
254 if (T->isLValueReferenceType()) {
255 return C.getLValueReferenceType(
256 getCanonicalParamType(C, T.getNonReferenceType()),
257 /*SpelledAsLValue=*/false);
258 }
259 if (T->isPointerType())
260 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000261 if (auto *A = T->getAsArrayTypeUnsafe()) {
262 if (auto *VLA = dyn_cast<VariableArrayType>(A))
263 return getCanonicalParamType(C, VLA->getElementType());
264 else if (!A->isVariablyModifiedType())
265 return C.getCanonicalType(T);
266 }
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000267 return C.getCanonicalParamType(T);
268}
269
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000270namespace {
271 /// Contains required data for proper outlined function codegen.
272 struct FunctionOptions {
273 /// Captured statement for which the function is generated.
274 const CapturedStmt *S = nullptr;
275 /// true if cast to/from UIntPtr is required for variables captured by
276 /// value.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000277 const bool UIntPtrCastRequired = true;
Alexey Bataeve754b182017-08-09 19:38:53 +0000278 /// true if only casted arguments must be registered as local args or VLA
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000279 /// sizes.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000280 const bool RegisterCastedArgsOnly = false;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000281 /// Name of the generated function.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000282 const StringRef FunctionName;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000283 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
284 bool RegisterCastedArgsOnly,
Alexey Bataev4aa19052017-08-08 16:45:36 +0000285 StringRef FunctionName)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000286 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
287 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
Alexey Bataev4aa19052017-08-08 16:45:36 +0000288 FunctionName(FunctionName) {}
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000289 };
290}
291
Alexey Bataeve754b182017-08-09 19:38:53 +0000292static llvm::Function *emitOutlinedFunctionPrologue(
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000293 CodeGenFunction &CGF, FunctionArgList &Args,
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000294 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000295 &LocalAddrs,
296 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
297 &VLASizes,
298 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
299 const CapturedDecl *CD = FO.S->getCapturedDecl();
300 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000301 assert(CD->hasBody() && "missing CapturedDecl body");
302
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000303 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000304 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000305 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000306 ASTContext &Ctx = CGM.getContext();
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000307 FunctionArgList TargetArgs;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000308 Args.append(CD->param_begin(),
309 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000310 TargetArgs.append(
311 CD->param_begin(),
312 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000313 auto I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000314 for (auto *FD : RD->fields()) {
315 QualType ArgType = FD->getType();
316 IdentifierInfo *II = nullptr;
317 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000318
319 // If this is a capture by copy and the type is not a pointer, the outlined
320 // function argument type should be uintptr and the value properly casted to
321 // uintptr. This is necessary given that the runtime library is only able to
322 // deal with pointers. We can pass in the same way the VLA type sizes to the
323 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000324 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000325 I->capturesVariableArrayType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000326 if (FO.UIntPtrCastRequired)
327 ArgType = Ctx.getUIntPtrType();
328 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000329
330 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000331 CapVar = I->getCapturedVar();
332 II = CapVar->getIdentifier();
333 } else if (I->capturesThis())
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000334 II = &Ctx.Idents.get("this");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000335 else {
336 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000337 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000338 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000339 if (ArgType->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000340 ArgType = getCanonicalParamType(Ctx, ArgType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000341 auto *Arg =
342 ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(), II,
343 ArgType, ImplicitParamDecl::Other);
344 Args.emplace_back(Arg);
345 // Do not cast arguments if we emit function with non-original types.
346 TargetArgs.emplace_back(
347 FO.UIntPtrCastRequired
348 ? Arg
349 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000350 ++I;
351 }
352 Args.append(
353 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
354 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000355 TargetArgs.append(
356 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
357 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000358
359 // Create the function declaration.
Alexey Bataev2377fe92015-09-10 08:12:02 +0000360 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000361 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000362 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
363
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000364 llvm::Function *F =
365 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
366 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000367 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
368 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000369 F->setDoesNotThrow();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000370
371 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000372 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
373 FO.S->getLocStart(), CD->getBody()->getLocStart());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000374 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000375 I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000376 for (auto *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000377 // Do not map arguments if we emit function with non-original types.
378 Address LocalAddr(Address::invalid());
379 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
380 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
381 TargetArgs[Cnt]);
382 } else {
383 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
384 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000385 // If we are capturing a pointer by copy we don't need to do anything, just
386 // use the value that we get from the arguments.
387 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000388 const VarDecl *CurVD = I->getCapturedVar();
Samuel Antao403ffd42016-07-27 22:49:49 +0000389 // If the variable is a reference we need to materialize it here.
390 if (CurVD->getType()->isReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000391 Address RefAddr = CGF.CreateMemTemp(
392 CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
393 CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
394 /*Volatile=*/false, CurVD->getType());
Samuel Antao403ffd42016-07-27 22:49:49 +0000395 LocalAddr = RefAddr;
396 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000397 if (!FO.RegisterCastedArgsOnly)
398 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000399 ++Cnt;
400 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000401 continue;
402 }
403
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000404 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
405 AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000406 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000407 if (FO.UIntPtrCastRequired) {
408 ArgLVal = CGF.MakeAddrLValue(castValueFromUintptr(CGF, FD->getType(),
409 Args[Cnt]->getName(),
410 ArgLVal),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000411 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000412 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000413 auto *ExprArg =
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000414 CGF.EmitLoadOfLValue(ArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000415 auto VAT = FD->getCapturedVLAType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000416 VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000417 } else if (I->capturesVariable()) {
418 auto *Var = I->getCapturedVar();
419 QualType VarTy = Var->getType();
420 Address ArgAddr = ArgLVal.getAddress();
421 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000422 if (ArgLVal.getType()->isLValueReferenceType()) {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +0000423 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000424 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000425 assert(ArgLVal.getType()->isPointerType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000426 ArgAddr = CGF.EmitLoadOfPointer(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000427 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
428 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000429 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000430 if (!FO.RegisterCastedArgsOnly) {
431 LocalAddrs.insert(
432 {Args[Cnt],
433 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
434 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000435 } else if (I->capturesVariableByCopy()) {
436 assert(!FD->getType()->isAnyPointerType() &&
437 "Not expecting a captured pointer.");
438 auto *Var = I->getCapturedVar();
439 QualType VarTy = Var->getType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000440 LocalAddrs.insert(
441 {Args[Cnt],
442 {Var,
443 FO.UIntPtrCastRequired
444 ? castValueFromUintptr(CGF, FD->getType(), Args[Cnt]->getName(),
445 ArgLVal, VarTy->isReferenceType())
446 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000447 } else {
448 // If 'this' is captured, load it into CXXThisValue.
449 assert(I->capturesThis());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000450 CXXThisValue = CGF.EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation())
451 .getScalarVal();
452 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000453 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000454 ++Cnt;
455 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000456 }
457
Alexey Bataeve754b182017-08-09 19:38:53 +0000458 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000459}
460
461llvm::Function *
462CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
463 assert(
464 CapturedStmtInfo &&
465 "CapturedStmtInfo should be set when generating the captured function");
466 const CapturedDecl *CD = S.getCapturedDecl();
467 // Build the argument list.
468 bool NeedWrapperFunction =
469 getDebugInfo() &&
470 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
471 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000472 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000473 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000474 SmallString<256> Buffer;
475 llvm::raw_svector_ostream Out(Buffer);
476 Out << CapturedStmtInfo->getHelperName();
477 if (NeedWrapperFunction)
478 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000479 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataeve754b182017-08-09 19:38:53 +0000480 Out.str());
481 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
482 VLASizes, CXXThisValue, FO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000483 for (const auto &LocalAddrPair : LocalAddrs) {
484 if (LocalAddrPair.second.first) {
485 setAddrOfLocalVar(LocalAddrPair.second.first,
486 LocalAddrPair.second.second);
487 }
488 }
489 for (const auto &VLASizePair : VLASizes)
490 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000491 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000492 CapturedStmtInfo->EmitBody(*this, CD->getBody());
493 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000494 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000495 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000496
Alexey Bataevefd884d2017-08-04 21:26:25 +0000497 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000498 /*RegisterCastedArgsOnly=*/true,
499 CapturedStmtInfo->getHelperName());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000500 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000501 Args.clear();
502 LocalAddrs.clear();
503 VLASizes.clear();
504 llvm::Function *WrapperF =
505 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000506 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000507 llvm::SmallVector<llvm::Value *, 4> CallArgs;
508 for (const auto *Arg : Args) {
509 llvm::Value *CallArg;
510 auto I = LocalAddrs.find(Arg);
511 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000512 LValue LV = WrapperCGF.MakeAddrLValue(
513 I->second.second,
514 I->second.first ? I->second.first->getType() : Arg->getType(),
515 AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000516 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
517 } else {
518 auto EI = VLASizes.find(Arg);
519 if (EI != VLASizes.end())
520 CallArg = EI->second.second;
521 else {
522 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000523 Arg->getType(),
524 AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000525 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
526 }
527 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000528 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000529 }
Alexey Bataev3c595a62017-08-14 15:01:03 +0000530 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getLocStart(),
531 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000532 WrapperCGF.FinishFunction();
533 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000534}
535
Alexey Bataev9959db52014-05-06 10:08:46 +0000536//===----------------------------------------------------------------------===//
537// OpenMP Directive Emission
538//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000539void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000540 Address DestAddr, Address SrcAddr, QualType OriginalType,
541 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000542 // Perform element-by-element initialization.
543 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000544
545 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000546 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000547 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
548 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
549
550 auto SrcBegin = SrcAddr.getPointer();
551 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000552 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000553 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
554 // The basic structure here is a while-do loop.
555 auto BodyBB = createBasicBlock("omp.arraycpy.body");
556 auto DoneBB = createBasicBlock("omp.arraycpy.done");
557 auto IsEmpty =
558 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
559 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000560
Alexey Bataev420d45b2015-04-14 05:11:24 +0000561 // Enter the loop body, making that address the current address.
562 auto EntryBB = Builder.GetInsertBlock();
563 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000564
565 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
566
567 llvm::PHINode *SrcElementPHI =
568 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
569 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
570 Address SrcElementCurrent =
571 Address(SrcElementPHI,
572 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
573
574 llvm::PHINode *DestElementPHI =
575 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
576 DestElementPHI->addIncoming(DestBegin, EntryBB);
577 Address DestElementCurrent =
578 Address(DestElementPHI,
579 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000580
Alexey Bataev420d45b2015-04-14 05:11:24 +0000581 // Emit copy.
582 CopyGen(DestElementCurrent, SrcElementCurrent);
583
584 // Shift the address forward by one element.
585 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000586 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000587 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000588 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000589 // Check whether we've reached the end.
590 auto Done =
591 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
592 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000593 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
594 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000595
596 // Done.
597 EmitBlock(DoneBB, /*IsFinished=*/true);
598}
599
John McCall7f416cc2015-09-08 08:05:57 +0000600void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
601 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000602 const VarDecl *SrcVD, const Expr *Copy) {
603 if (OriginalType->isArrayType()) {
604 auto *BO = dyn_cast<BinaryOperator>(Copy);
605 if (BO && BO->getOpcode() == BO_Assign) {
606 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000607 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000608 } else {
609 // For arrays with complex element types perform element by element
610 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000611 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000612 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000613 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000614 // Working with the single array element, so have to remap
615 // destination and source variables to corresponding array
616 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000617 CodeGenFunction::OMPPrivateScope Remap(*this);
618 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000619 return DestElement;
620 });
621 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000622 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000623 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000624 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000625 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000626 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000627 } else {
628 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000629 CodeGenFunction::OMPPrivateScope Remap(*this);
630 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
631 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000632 (void)Remap.Privatize();
633 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000634 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000635 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000636}
637
Alexey Bataev69c62a92015-04-15 04:52:20 +0000638bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
639 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000640 if (!HaveInsertPoint())
641 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000642 bool FirstprivateIsLastprivate = false;
643 llvm::DenseSet<const VarDecl *> Lastprivates;
644 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
645 for (const auto *D : C->varlists())
646 Lastprivates.insert(
647 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
648 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000649 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000650 CGCapturedStmtInfo CapturesInfo(cast<CapturedStmt>(*D.getAssociatedStmt()));
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000651 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000652 auto IRef = C->varlist_begin();
653 auto InitsRef = C->inits().begin();
654 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000655 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000656 bool ThisFirstprivateIsLastprivate =
657 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000658 auto *CapFD = CapturesInfo.lookup(OrigVD);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000659 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9afe5752016-05-24 07:40:12 +0000660 if (!ThisFirstprivateIsLastprivate && FD && (FD == CapFD) &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000661 !FD->getType()->isReferenceType()) {
662 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
663 ++IRef;
664 ++InitsRef;
665 continue;
666 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000667 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000668 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000669 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000670 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
671 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
672 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000673 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
674 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
675 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000676 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000677 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000678 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000679 // Emit VarDecl with copy init for arrays.
680 // Get the address of the original variable captured in current
681 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000682 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000683 auto Emission = EmitAutoVarAlloca(*VD);
684 auto *Init = VD->getInit();
685 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
686 // Perform simple memcpy.
687 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000688 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000689 } else {
690 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000691 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000692 [this, VDInit, Init](Address DestElement,
693 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000694 // Clean up any temporaries needed by the initialization.
695 RunCleanupsScope InitScope(*this);
696 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000697 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000698 EmitAnyExprToMem(Init, DestElement,
699 Init->getType().getQualifiers(),
700 /*IsInitializer*/ false);
701 LocalDeclMap.erase(VDInit);
702 });
703 }
704 EmitAutoVarCleanups(Emission);
705 return Emission.getAllocatedAddress();
706 });
707 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000708 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000709 // Emit private VarDecl with copy init.
710 // Remap temp VDInit variable to the address of the original
711 // variable
712 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000713 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000714 EmitDecl(*VD);
715 LocalDeclMap.erase(VDInit);
716 return GetAddrOfLocalVar(VD);
717 });
718 }
719 assert(IsRegistered &&
720 "firstprivate var already registered as private");
721 // Silence the warning about unused variable.
722 (void)IsRegistered;
723 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000724 ++IRef;
725 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000726 }
727 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000728 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000729}
730
Alexey Bataev03b340a2014-10-21 03:16:40 +0000731void CodeGenFunction::EmitOMPPrivateClause(
732 const OMPExecutableDirective &D,
733 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000734 if (!HaveInsertPoint())
735 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000736 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000737 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000738 auto IRef = C->varlist_begin();
739 for (auto IInit : C->private_copies()) {
740 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000741 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
742 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
743 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000744 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000745 // Emit private VarDecl with copy init.
746 EmitDecl(*VD);
747 return GetAddrOfLocalVar(VD);
748 });
749 assert(IsRegistered && "private var already registered as private");
750 // Silence the warning about unused variable.
751 (void)IsRegistered;
752 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000753 ++IRef;
754 }
755 }
756}
757
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000758bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000759 if (!HaveInsertPoint())
760 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000761 // threadprivate_var1 = master_threadprivate_var1;
762 // operator=(threadprivate_var2, master_threadprivate_var2);
763 // ...
764 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000765 llvm::DenseSet<const VarDecl *> CopiedVars;
766 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000767 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000768 auto IRef = C->varlist_begin();
769 auto ISrcRef = C->source_exprs().begin();
770 auto IDestRef = C->destination_exprs().begin();
771 for (auto *AssignOp : C->assignment_ops()) {
772 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000773 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000774 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000775 // Get the address of the master variable. If we are emitting code with
776 // TLS support, the address is passed from the master as field in the
777 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000778 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000779 if (getLangOpts().OpenMPUseTLS &&
780 getContext().getTargetInfo().isTLSSupported()) {
781 assert(CapturedStmtInfo->lookup(VD) &&
782 "Copyin threadprivates should have been captured!");
783 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
784 VK_LValue, (*IRef)->getExprLoc());
785 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000786 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000787 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000788 MasterAddr =
789 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
790 : CGM.GetAddrOfGlobal(VD),
791 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000792 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000793 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000794 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000795 if (CopiedVars.size() == 1) {
796 // At first check if current thread is a master thread. If it is, no
797 // need to copy data.
798 CopyBegin = createBasicBlock("copyin.not.master");
799 CopyEnd = createBasicBlock("copyin.not.master.end");
800 Builder.CreateCondBr(
801 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000802 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
803 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000804 CopyBegin, CopyEnd);
805 EmitBlock(CopyBegin);
806 }
807 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
808 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000809 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000810 }
811 ++IRef;
812 ++ISrcRef;
813 ++IDestRef;
814 }
815 }
816 if (CopyEnd) {
817 // Exit out of copying procedure for non-master thread.
818 EmitBlock(CopyEnd, /*IsFinished=*/true);
819 return true;
820 }
821 return false;
822}
823
Alexey Bataev38e89532015-04-16 04:54:05 +0000824bool CodeGenFunction::EmitOMPLastprivateClauseInit(
825 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000826 if (!HaveInsertPoint())
827 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000828 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000829 llvm::DenseSet<const VarDecl *> SIMDLCVs;
830 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
831 auto *LoopDirective = cast<OMPLoopDirective>(&D);
832 for (auto *C : LoopDirective->counters()) {
833 SIMDLCVs.insert(
834 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
835 }
836 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000837 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000838 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000839 HasAtLeastOneLastprivate = true;
Alexey Bataevf93095a2016-05-05 08:46:22 +0000840 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()))
841 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000842 auto IRef = C->varlist_begin();
843 auto IDestRef = C->destination_exprs().begin();
844 for (auto *IInit : C->private_copies()) {
845 // Keep the address of the original variable for future update at the end
846 // of the loop.
847 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000848 // Taskloops do not require additional initialization, it is done in
849 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000850 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
851 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000852 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000853 DeclRefExpr DRE(
854 const_cast<VarDecl *>(OrigVD),
855 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
856 OrigVD) != nullptr,
857 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
858 return EmitLValue(&DRE).getAddress();
859 });
860 // Check if the variable is also a firstprivate: in this case IInit is
861 // not generated. Initialization of this variable will happen in codegen
862 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000863 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000864 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000865 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
866 // Emit private VarDecl with copy init.
867 EmitDecl(*VD);
868 return GetAddrOfLocalVar(VD);
869 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000870 assert(IsRegistered &&
871 "lastprivate var already registered as private");
872 (void)IsRegistered;
873 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000874 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000875 ++IRef;
876 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000877 }
878 }
879 return HasAtLeastOneLastprivate;
880}
881
882void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000883 const OMPExecutableDirective &D, bool NoFinals,
884 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000885 if (!HaveInsertPoint())
886 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000887 // Emit following code:
888 // if (<IsLastIterCond>) {
889 // orig_var1 = private_orig_var1;
890 // ...
891 // orig_varn = private_orig_varn;
892 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000893 llvm::BasicBlock *ThenBB = nullptr;
894 llvm::BasicBlock *DoneBB = nullptr;
895 if (IsLastIterCond) {
896 ThenBB = createBasicBlock(".omp.lastprivate.then");
897 DoneBB = createBasicBlock(".omp.lastprivate.done");
898 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
899 EmitBlock(ThenBB);
900 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000901 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
902 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000903 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000904 auto IC = LoopDirective->counters().begin();
905 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000906 auto *D =
907 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
908 if (NoFinals)
909 AlreadyEmittedVars.insert(D);
910 else
911 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000912 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000913 }
914 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000915 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
916 auto IRef = C->varlist_begin();
917 auto ISrcRef = C->source_exprs().begin();
918 auto IDestRef = C->destination_exprs().begin();
919 for (auto *AssignOp : C->assignment_ops()) {
920 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
921 QualType Type = PrivateVD->getType();
922 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
923 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
924 // If lastprivate variable is a loop control variable for loop-based
925 // directive, update its value before copyin back to original
926 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000927 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
928 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000929 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
930 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
931 // Get the address of the original variable.
932 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
933 // Get the address of the private variable.
934 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
935 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
936 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000937 Address(Builder.CreateLoad(PrivateAddr),
938 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000939 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000940 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000941 ++IRef;
942 ++ISrcRef;
943 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000944 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000945 if (auto *PostUpdate = C->getPostUpdateExpr())
946 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000947 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000948 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000949 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000950}
951
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000952void CodeGenFunction::EmitOMPReductionClauseInit(
953 const OMPExecutableDirective &D,
954 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000955 if (!HaveInsertPoint())
956 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000957 SmallVector<const Expr *, 4> Shareds;
958 SmallVector<const Expr *, 4> Privates;
959 SmallVector<const Expr *, 4> ReductionOps;
960 SmallVector<const Expr *, 4> LHSs;
961 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000962 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000963 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000964 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000965 auto ILHS = C->lhs_exprs().begin();
966 auto IRHS = C->rhs_exprs().begin();
967 for (const auto *Ref : C->varlists()) {
968 Shareds.emplace_back(Ref);
969 Privates.emplace_back(*IPriv);
970 ReductionOps.emplace_back(*IRed);
971 LHSs.emplace_back(*ILHS);
972 RHSs.emplace_back(*IRHS);
973 std::advance(IPriv, 1);
974 std::advance(IRed, 1);
975 std::advance(ILHS, 1);
976 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000977 }
978 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000979 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
980 unsigned Count = 0;
981 auto ILHS = LHSs.begin();
982 auto IRHS = RHSs.begin();
983 auto IPriv = Privates.begin();
984 for (const auto *IRef : Shareds) {
985 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
986 // Emit private VarDecl with reduction init.
987 RedCG.emitSharedLValue(*this, Count);
988 RedCG.emitAggregateType(*this, Count);
989 auto Emission = EmitAutoVarAlloca(*PrivateVD);
990 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
991 RedCG.getSharedLValue(Count),
992 [&Emission](CodeGenFunction &CGF) {
993 CGF.EmitAutoVarInit(Emission);
994 return true;
995 });
996 EmitAutoVarCleanups(Emission);
997 Address BaseAddr = RedCG.adjustPrivateAddress(
998 *this, Count, Emission.getAllocatedAddress());
999 bool IsRegistered = PrivateScope.addPrivate(
1000 RedCG.getBaseDecl(Count), [BaseAddr]() -> Address { return BaseAddr; });
1001 assert(IsRegistered && "private var already registered as private");
1002 // Silence the warning about unused variable.
1003 (void)IsRegistered;
1004
1005 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1006 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001007 QualType Type = PrivateVD->getType();
1008 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1009 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001010 // Store the address of the original variable associated with the LHS
1011 // implicit variable.
1012 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1013 return RedCG.getSharedLValue(Count).getAddress();
1014 });
1015 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1016 return GetAddrOfLocalVar(PrivateVD);
1017 });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001018 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1019 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001020 // Store the address of the original variable associated with the LHS
1021 // implicit variable.
1022 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1023 return RedCG.getSharedLValue(Count).getAddress();
1024 });
1025 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1026 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1027 ConvertTypeForMem(RHSVD->getType()),
1028 "rhs.begin");
1029 });
1030 } else {
1031 QualType Type = PrivateVD->getType();
1032 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1033 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1034 // Store the address of the original variable associated with the LHS
1035 // implicit variable.
1036 if (IsArray) {
1037 OriginalAddr = Builder.CreateElementBitCast(
1038 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1039 }
1040 PrivateScope.addPrivate(
1041 LHSVD, [OriginalAddr]() -> Address { return OriginalAddr; });
1042 PrivateScope.addPrivate(
1043 RHSVD, [this, PrivateVD, RHSVD, IsArray]() -> Address {
1044 return IsArray
1045 ? Builder.CreateElementBitCast(
1046 GetAddrOfLocalVar(PrivateVD),
1047 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1048 : GetAddrOfLocalVar(PrivateVD);
1049 });
1050 }
1051 ++ILHS;
1052 ++IRHS;
1053 ++IPriv;
1054 ++Count;
1055 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001056}
1057
1058void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001059 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001060 if (!HaveInsertPoint())
1061 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001062 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001063 llvm::SmallVector<const Expr *, 8> LHSExprs;
1064 llvm::SmallVector<const Expr *, 8> RHSExprs;
1065 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001066 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001067 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001068 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001069 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001070 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1071 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1072 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1073 }
1074 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001075 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1076 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1077 D.getDirectiveKind() == OMPD_simd;
1078 bool SimpleReduction = D.getDirectiveKind() == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001079 // Emit nowait reduction if nowait clause is present or directive is a
1080 // parallel directive (it always has implicit barrier).
1081 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001082 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001083 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001084 }
1085}
1086
Alexey Bataev61205072016-03-02 04:57:40 +00001087static void emitPostUpdateForReductionClause(
1088 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1089 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1090 if (!CGF.HaveInsertPoint())
1091 return;
1092 llvm::BasicBlock *DoneBB = nullptr;
1093 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1094 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1095 if (!DoneBB) {
1096 if (auto *Cond = CondGen(CGF)) {
1097 // If the first post-update expression is found, emit conditional
1098 // block if it was requested.
1099 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1100 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1101 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1102 CGF.EmitBlock(ThenBB);
1103 }
1104 }
1105 CGF.EmitIgnoredExpr(PostUpdate);
1106 }
1107 }
1108 if (DoneBB)
1109 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1110}
1111
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001112namespace {
1113/// Codegen lambda for appending distribute lower and upper bounds to outlined
1114/// parallel function. This is necessary for combined constructs such as
1115/// 'distribute parallel for'
1116typedef llvm::function_ref<void(CodeGenFunction &,
1117 const OMPExecutableDirective &,
1118 llvm::SmallVectorImpl<llvm::Value *> &)>
1119 CodeGenBoundParametersTy;
1120} // anonymous namespace
1121
1122static void emitCommonOMPParallelDirective(
1123 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1124 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1125 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001126 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1127 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1128 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001129 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001130 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001131 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1132 /*IgnoreResultAssign*/ true);
1133 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1134 CGF, NumThreads, NumThreadsClause->getLocStart());
1135 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001136 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001137 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001138 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1139 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1140 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001141 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001142 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1143 if (C->getNameModifier() == OMPD_unknown ||
1144 C->getNameModifier() == OMPD_parallel) {
1145 IfCond = C->getCondition();
1146 break;
1147 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001148 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001149
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001150 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001151 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001152 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1153 // lower and upper bounds with the pragma 'for' chunking mechanism.
1154 // The following lambda takes care of appending the lower and upper bound
1155 // parameters when necessary
1156 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001157 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001158 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001159 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001160}
1161
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001162static void emitEmptyBoundParameters(CodeGenFunction &,
1163 const OMPExecutableDirective &,
1164 llvm::SmallVectorImpl<llvm::Value *> &) {}
1165
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001166void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001167 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001168 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001169 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001170 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001171 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1172 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001173 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001174 // propagation master's thread values of threadprivate variables to local
1175 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001176 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1177 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1178 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001179 }
1180 CGF.EmitOMPPrivateClause(S, PrivateScope);
1181 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1182 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001183 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001184 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001185 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001186 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1187 emitEmptyBoundParameters);
Alexey Bataev61205072016-03-02 04:57:40 +00001188 emitPostUpdateForReductionClause(
1189 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001190}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001191
Alexey Bataev0f34da12015-07-02 04:17:07 +00001192void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1193 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001194 RunCleanupsScope BodyScope(*this);
1195 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001196 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001197 EmitIgnoredExpr(I);
1198 }
Alexander Musman3276a272015-03-21 10:12:56 +00001199 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001200 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001201 for (auto *U : C->updates())
Alexander Musman3276a272015-03-21 10:12:56 +00001202 EmitIgnoredExpr(U);
Alexander Musman3276a272015-03-21 10:12:56 +00001203 }
1204
Alexander Musmana5f070a2014-10-01 06:03:56 +00001205 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001206 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001207 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001208 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001209 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001210 // The end (updates/cleanups).
1211 EmitBlock(Continue.getBlock());
1212 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001213}
1214
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001215void CodeGenFunction::EmitOMPInnerLoop(
1216 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1217 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001218 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1219 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001220 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001221
1222 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001223 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001224 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001225 const SourceRange &R = S.getSourceRange();
1226 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1227 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001228
1229 // If there are any cleanups between here and the loop-exit scope,
1230 // create a block to stage a loop exit along.
1231 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001232 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001233 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001234
Alexander Musmand196ef22014-10-07 08:57:09 +00001235 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001236
Alexey Bataev2df54a02015-03-12 08:53:29 +00001237 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001238 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001239 if (ExitBlock != LoopExit.getBlock()) {
1240 EmitBlock(ExitBlock);
1241 EmitBranchThroughCleanup(LoopExit);
1242 }
1243
1244 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001245 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001246
1247 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001248 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001249 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1250
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001251 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001252
1253 // Emit "IV = IV + 1" and a back-edge to the condition block.
1254 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001255 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001256 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001257 BreakContinueStack.pop_back();
1258 EmitBranch(CondBlock);
1259 LoopStack.pop();
1260 // Emit the fall-through block.
1261 EmitBlock(LoopExit.getBlock());
1262}
1263
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001264bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001265 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001266 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001267 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001268 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001269 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001270 for (auto *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001271 HasLinears = true;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001272 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001273 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1274 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1275 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1276 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1277 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1278 VD->getInit()->getType(), VK_LValue,
1279 VD->getInit()->getExprLoc());
1280 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1281 VD->getType()),
1282 /*capturedByInit=*/false);
1283 EmitAutoVarCleanups(Emission);
1284 } else
1285 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001286 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001287 // Emit the linear steps for the linear clauses.
1288 // If a step is not constant, it is pre-calculated before the loop.
1289 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1290 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001291 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001292 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001293 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001294 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001295 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001296 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001297}
1298
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001299void CodeGenFunction::EmitOMPLinearClauseFinal(
1300 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001301 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001302 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001303 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001304 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001305 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001306 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001307 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001308 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001309 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001310 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001311 // If the first post-update expression is found, emit conditional
1312 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001313 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1314 DoneBB = createBasicBlock(".omp.linear.pu.done");
1315 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1316 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001317 }
1318 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001319 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1320 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001321 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001322 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001323 Address OrigAddr = EmitLValue(&DRE).getAddress();
1324 CodeGenFunction::OMPPrivateScope VarScope(*this);
1325 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001326 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001327 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001328 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001329 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001330 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001331 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001332 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001333 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001334 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001335}
1336
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001337static void emitAlignedClause(CodeGenFunction &CGF,
1338 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001339 if (!CGF.HaveInsertPoint())
1340 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001341 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001342 unsigned ClauseAlignment = 0;
1343 if (auto AlignmentExpr = Clause->getAlignment()) {
1344 auto AlignmentCI =
1345 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1346 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001347 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001348 for (auto E : Clause->varlists()) {
1349 unsigned Alignment = ClauseAlignment;
1350 if (Alignment == 0) {
1351 // OpenMP [2.8.1, Description]
1352 // If no optional parameter is specified, implementation-defined default
1353 // alignments for SIMD instructions on the target platforms are assumed.
1354 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001355 CGF.getContext()
1356 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1357 E->getType()->getPointeeType()))
1358 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001359 }
1360 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1361 "alignment is not power of 2");
1362 if (Alignment != 0) {
1363 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1364 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1365 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001366 }
1367 }
1368}
1369
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001370void CodeGenFunction::EmitOMPPrivateLoopCounters(
1371 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1372 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001373 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001374 auto I = S.private_counters().begin();
1375 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001376 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1377 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001378 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001379 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001380 if (!LocalDeclMap.count(PrivateVD)) {
1381 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1382 EmitAutoVarCleanups(VarEmission);
1383 }
1384 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1385 /*RefersToEnclosingVariableOrCapture=*/false,
1386 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1387 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001388 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001389 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1390 VD->hasGlobalStorage()) {
1391 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1392 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1393 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1394 E->getType(), VK_LValue, E->getExprLoc());
1395 return EmitLValue(&DRE).getAddress();
1396 });
1397 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001398 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001399 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001400}
1401
Alexey Bataev62dbb972015-04-22 11:59:37 +00001402static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1403 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1404 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001405 if (!CGF.HaveInsertPoint())
1406 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001407 {
1408 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001409 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001410 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001411 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001412 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001413 CGF.EmitIgnoredExpr(I);
1414 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001415 }
1416 // Check that loop is executed at least one time.
1417 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1418}
1419
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001420void CodeGenFunction::EmitOMPLinearClause(
1421 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1422 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001423 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001424 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1425 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1426 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1427 for (auto *C : LoopDirective->counters()) {
1428 SIMDLCVs.insert(
1429 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1430 }
1431 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001432 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001433 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001434 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001435 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1436 auto *PrivateVD =
1437 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001438 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1439 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1440 // Emit private VarDecl with copy init.
1441 EmitVarDecl(*PrivateVD);
1442 return GetAddrOfLocalVar(PrivateVD);
1443 });
1444 assert(IsRegistered && "linear var already registered as private");
1445 // Silence the warning about unused variable.
1446 (void)IsRegistered;
1447 } else
1448 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001449 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001450 }
1451 }
1452}
1453
Alexey Bataev45bfad52015-08-21 12:19:04 +00001454static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001455 const OMPExecutableDirective &D,
1456 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001457 if (!CGF.HaveInsertPoint())
1458 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001459 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001460 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1461 /*ignoreResult=*/true);
1462 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1463 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1464 // In presence of finite 'safelen', it may be unsafe to mark all
1465 // the memory instructions parallel, because loop-carried
1466 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001467 if (!IsMonotonic)
1468 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001469 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001470 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1471 /*ignoreResult=*/true);
1472 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001473 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001474 // In presence of finite 'safelen', it may be unsafe to mark all
1475 // the memory instructions parallel, because loop-carried
1476 // dependences of 'safelen' iterations are possible.
1477 CGF.LoopStack.setParallel(false);
1478 }
1479}
1480
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001481void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1482 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001483 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001484 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001485 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001486 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001487}
1488
Alexey Bataevef549a82016-03-09 09:49:09 +00001489void CodeGenFunction::EmitOMPSimdFinal(
1490 const OMPLoopDirective &D,
1491 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001492 if (!HaveInsertPoint())
1493 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001494 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001495 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001496 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001497 for (auto F : D.finals()) {
1498 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001499 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1500 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1501 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1502 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001503 if (!DoneBB) {
1504 if (auto *Cond = CondGen(*this)) {
1505 // If the first post-update expression is found, emit conditional
1506 // block if it was requested.
1507 auto *ThenBB = createBasicBlock(".omp.final.then");
1508 DoneBB = createBasicBlock(".omp.final.done");
1509 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1510 EmitBlock(ThenBB);
1511 }
1512 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001513 Address OrigAddr = Address::invalid();
1514 if (CED)
1515 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1516 else {
1517 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1518 /*RefersToEnclosingVariableOrCapture=*/false,
1519 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1520 OrigAddr = EmitLValue(&DRE).getAddress();
1521 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001522 OMPPrivateScope VarScope(*this);
1523 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001524 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001525 (void)VarScope.Privatize();
1526 EmitIgnoredExpr(F);
1527 }
1528 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001529 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001530 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001531 if (DoneBB)
1532 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001533}
1534
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001535static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1536 const OMPLoopDirective &S,
1537 CodeGenFunction::JumpDest LoopExit) {
1538 CGF.EmitOMPLoopBody(S, LoopExit);
1539 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001540}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001541
Alexey Bataevf8365372017-11-17 17:57:25 +00001542static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1543 PrePostActionTy &Action) {
1544 Action.Enter(CGF);
1545 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1546 "Expected simd directive");
1547 OMPLoopScope PreInitScope(CGF, S);
1548 // if (PreCond) {
1549 // for (IV in 0..LastIteration) BODY;
1550 // <Final counter/linear vars updates>;
1551 // }
1552 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001553
Alexey Bataevf8365372017-11-17 17:57:25 +00001554 // Emit: if (PreCond) - begin.
1555 // If the condition constant folds and can be elided, avoid emitting the
1556 // whole loop.
1557 bool CondConstant;
1558 llvm::BasicBlock *ContBlock = nullptr;
1559 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1560 if (!CondConstant)
1561 return;
1562 } else {
1563 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1564 ContBlock = CGF.createBasicBlock("simd.if.end");
1565 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1566 CGF.getProfileCount(&S));
1567 CGF.EmitBlock(ThenBlock);
1568 CGF.incrementProfileCounter(&S);
1569 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001570
Alexey Bataevf8365372017-11-17 17:57:25 +00001571 // Emit the loop iteration variable.
1572 const Expr *IVExpr = S.getIterationVariable();
1573 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1574 CGF.EmitVarDecl(*IVDecl);
1575 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001576
Alexey Bataevf8365372017-11-17 17:57:25 +00001577 // Emit the iterations count variable.
1578 // If it is not a variable, Sema decided to calculate iterations count on
1579 // each iteration (e.g., it is foldable into a constant).
1580 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1581 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1582 // Emit calculation of the iterations count.
1583 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1584 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001585
Alexey Bataevf8365372017-11-17 17:57:25 +00001586 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001587
Alexey Bataevf8365372017-11-17 17:57:25 +00001588 emitAlignedClause(CGF, S);
1589 (void)CGF.EmitOMPLinearClauseInit(S);
1590 {
1591 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1592 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1593 CGF.EmitOMPLinearClause(S, LoopScope);
1594 CGF.EmitOMPPrivateClause(S, LoopScope);
1595 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1596 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1597 (void)LoopScope.Privatize();
1598 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1599 S.getInc(),
1600 [&S](CodeGenFunction &CGF) {
1601 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1602 CGF.EmitStopPoint(&S);
1603 },
1604 [](CodeGenFunction &) {});
1605 CGF.EmitOMPSimdFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001606 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001607 // Emit final copy of the lastprivate variables at the end of loops.
1608 if (HasLastprivateClause)
1609 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1610 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
1611 emitPostUpdateForReductionClause(
1612 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1613 }
1614 CGF.EmitOMPLinearClauseFinal(
1615 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1616 // Emit: if (PreCond) - end.
1617 if (ContBlock) {
1618 CGF.EmitBranch(ContBlock);
1619 CGF.EmitBlock(ContBlock, true);
1620 }
1621}
1622
1623void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1624 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1625 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001626 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00001627 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001628 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001629}
1630
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001631void CodeGenFunction::EmitOMPOuterLoop(
1632 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1633 CodeGenFunction::OMPPrivateScope &LoopScope,
1634 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1635 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1636 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001637 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001638
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001639 const Expr *IVExpr = S.getIterationVariable();
1640 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1641 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1642
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001643 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1644
1645 // Start the loop with a block that tests the condition.
1646 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1647 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001648 const SourceRange &R = S.getSourceRange();
1649 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1650 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001651
1652 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001653 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001654 // UB = min(UB, GlobalUB) or
1655 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1656 // 'distribute parallel for')
1657 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001658 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001659 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001660 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001661 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001662 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001663 BoolCondVal =
1664 RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1665 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001666 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001667
1668 // If there are any cleanups between here and the loop-exit scope,
1669 // create a block to stage a loop exit along.
1670 auto ExitBlock = LoopExit.getBlock();
1671 if (LoopScope.requiresCleanups())
1672 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1673
1674 auto LoopBody = createBasicBlock("omp.dispatch.body");
1675 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1676 if (ExitBlock != LoopExit.getBlock()) {
1677 EmitBlock(ExitBlock);
1678 EmitBranchThroughCleanup(LoopExit);
1679 }
1680 EmitBlock(LoopBody);
1681
Alexander Musman92bdaab2015-03-12 13:37:50 +00001682 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1683 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001684 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001685 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001686
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001687 // Create a block for the increment.
1688 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1689 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1690
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001691 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1692 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001693 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1694 LoopStack.setParallel(!IsMonotonic);
1695 else
1696 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001697
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001698 SourceLocation Loc = S.getLocStart();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001699
1700 // when 'distribute' is not combined with a 'for':
1701 // while (idx <= UB) { BODY; ++idx; }
1702 // when 'distribute' is combined with a 'for'
1703 // (e.g. 'distribute parallel for')
1704 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1705 EmitOMPInnerLoop(
1706 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1707 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1708 CodeGenLoop(CGF, S, LoopExit);
1709 },
1710 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1711 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1712 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001713
1714 EmitBlock(Continue.getBlock());
1715 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001716 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001717 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001718 EmitIgnoredExpr(LoopArgs.NextLB);
1719 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001720 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001721
1722 EmitBranch(CondBlock);
1723 LoopStack.pop();
1724 // Emit the fall-through block.
1725 EmitBlock(LoopExit.getBlock());
1726
1727 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001728 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1729 if (!DynamicOrOrdered)
Alexey Bataevf43f7142017-09-06 16:17:35 +00001730 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
1731 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00001732 };
1733 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001734}
1735
1736void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001737 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001738 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001739 const OMPLoopArguments &LoopArgs,
1740 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001741 auto &RT = CGM.getOpenMPRuntime();
1742
1743 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001744 const bool DynamicOrOrdered =
1745 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001746
1747 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001748 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001749 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001750 "static non-chunked schedule does not need outer loop");
1751
1752 // Emit outer loop.
1753 //
1754 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1755 // When schedule(dynamic,chunk_size) is specified, the iterations are
1756 // distributed to threads in the team in chunks as the threads request them.
1757 // Each thread executes a chunk of iterations, then requests another chunk,
1758 // until no chunks remain to be distributed. Each chunk contains chunk_size
1759 // iterations, except for the last chunk to be distributed, which may have
1760 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1761 //
1762 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1763 // to threads in the team in chunks as the executing threads request them.
1764 // Each thread executes a chunk of iterations, then requests another chunk,
1765 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1766 // each chunk is proportional to the number of unassigned iterations divided
1767 // by the number of threads in the team, decreasing to 1. For a chunk_size
1768 // with value k (greater than 1), the size of each chunk is determined in the
1769 // same way, with the restriction that the chunks do not contain fewer than k
1770 // iterations (except for the last chunk to be assigned, which may have fewer
1771 // than k iterations).
1772 //
1773 // When schedule(auto) is specified, the decision regarding scheduling is
1774 // delegated to the compiler and/or runtime system. The programmer gives the
1775 // implementation the freedom to choose any possible mapping of iterations to
1776 // threads in the team.
1777 //
1778 // When schedule(runtime) is specified, the decision regarding scheduling is
1779 // deferred until run time, and the schedule and chunk size are taken from the
1780 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1781 // implementation defined
1782 //
1783 // while(__kmpc_dispatch_next(&LB, &UB)) {
1784 // idx = LB;
1785 // while (idx <= UB) { BODY; ++idx;
1786 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1787 // } // inner loop
1788 // }
1789 //
1790 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1791 // When schedule(static, chunk_size) is specified, iterations are divided into
1792 // chunks of size chunk_size, and the chunks are assigned to the threads in
1793 // the team in a round-robin fashion in the order of the thread number.
1794 //
1795 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1796 // while (idx <= UB) { BODY; ++idx; } // inner loop
1797 // LB = LB + ST;
1798 // UB = UB + ST;
1799 // }
1800 //
1801
1802 const Expr *IVExpr = S.getIterationVariable();
1803 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1804 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1805
1806 if (DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001807 auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1808 llvm::Value *LBVal = DispatchBounds.first;
1809 llvm::Value *UBVal = DispatchBounds.second;
1810 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1811 LoopArgs.Chunk};
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001812 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001813 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001814 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001815 CGOpenMPRuntime::StaticRTInput StaticInit(
1816 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1817 LoopArgs.ST, LoopArgs.Chunk);
1818 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
1819 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001820 }
1821
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001822 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1823 const unsigned IVSize,
1824 const bool IVSigned) {
1825 if (Ordered) {
1826 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1827 IVSigned);
1828 }
1829 };
1830
1831 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1832 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1833 OuterLoopArgs.IncExpr = S.getInc();
1834 OuterLoopArgs.Init = S.getInit();
1835 OuterLoopArgs.Cond = S.getCond();
1836 OuterLoopArgs.NextLB = S.getNextLowerBound();
1837 OuterLoopArgs.NextUB = S.getNextUpperBound();
1838 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1839 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001840}
1841
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001842static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1843 const unsigned IVSize, const bool IVSigned) {}
1844
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001845void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001846 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1847 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1848 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001849
1850 auto &RT = CGM.getOpenMPRuntime();
1851
1852 // Emit outer loop.
1853 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1854 // dynamic
1855 //
1856
1857 const Expr *IVExpr = S.getIterationVariable();
1858 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1859 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1860
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001861 CGOpenMPRuntime::StaticRTInput StaticInit(
1862 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
1863 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
1864 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001865
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001866 // for combined 'distribute' and 'for' the increment expression of distribute
1867 // is store in DistInc. For 'distribute' alone, it is in Inc.
1868 Expr *IncExpr;
1869 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1870 IncExpr = S.getDistInc();
1871 else
1872 IncExpr = S.getInc();
1873
1874 // this routine is shared by 'omp distribute parallel for' and
1875 // 'omp distribute': select the right EUB expression depending on the
1876 // directive
1877 OMPLoopArguments OuterLoopArgs;
1878 OuterLoopArgs.LB = LoopArgs.LB;
1879 OuterLoopArgs.UB = LoopArgs.UB;
1880 OuterLoopArgs.ST = LoopArgs.ST;
1881 OuterLoopArgs.IL = LoopArgs.IL;
1882 OuterLoopArgs.Chunk = LoopArgs.Chunk;
1883 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1884 ? S.getCombinedEnsureUpperBound()
1885 : S.getEnsureUpperBound();
1886 OuterLoopArgs.IncExpr = IncExpr;
1887 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1888 ? S.getCombinedInit()
1889 : S.getInit();
1890 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1891 ? S.getCombinedCond()
1892 : S.getCond();
1893 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1894 ? S.getCombinedNextLowerBound()
1895 : S.getNextLowerBound();
1896 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1897 ? S.getCombinedNextUpperBound()
1898 : S.getNextUpperBound();
1899
1900 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
1901 LoopScope, OuterLoopArgs, CodeGenLoopContent,
1902 emitEmptyOrdered);
1903}
1904
1905/// Emit a helper variable and return corresponding lvalue.
1906static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1907 const DeclRefExpr *Helper) {
1908 auto VDecl = cast<VarDecl>(Helper->getDecl());
1909 CGF.EmitVarDecl(*VDecl);
1910 return CGF.EmitLValue(Helper);
1911}
1912
1913static std::pair<LValue, LValue>
1914emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
1915 const OMPExecutableDirective &S) {
1916 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1917 LValue LB =
1918 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
1919 LValue UB =
1920 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
1921
1922 // When composing 'distribute' with 'for' (e.g. as in 'distribute
1923 // parallel for') we need to use the 'distribute'
1924 // chunk lower and upper bounds rather than the whole loop iteration
1925 // space. These are parameters to the outlined function for 'parallel'
1926 // and we copy the bounds of the previous schedule into the
1927 // the current ones.
1928 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
1929 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
1930 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(PrevLB, SourceLocation());
1931 PrevLBVal = CGF.EmitScalarConversion(
1932 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
1933 LS.getIterationVariable()->getType(), SourceLocation());
1934 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(PrevUB, SourceLocation());
1935 PrevUBVal = CGF.EmitScalarConversion(
1936 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
1937 LS.getIterationVariable()->getType(), SourceLocation());
1938
1939 CGF.EmitStoreOfScalar(PrevLBVal, LB);
1940 CGF.EmitStoreOfScalar(PrevUBVal, UB);
1941
1942 return {LB, UB};
1943}
1944
1945/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
1946/// we need to use the LB and UB expressions generated by the worksharing
1947/// code generation support, whereas in non combined situations we would
1948/// just emit 0 and the LastIteration expression
1949/// This function is necessary due to the difference of the LB and UB
1950/// types for the RT emission routines for 'for_static_init' and
1951/// 'for_dispatch_init'
1952static std::pair<llvm::Value *, llvm::Value *>
1953emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
1954 const OMPExecutableDirective &S,
1955 Address LB, Address UB) {
1956 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1957 const Expr *IVExpr = LS.getIterationVariable();
1958 // when implementing a dynamic schedule for a 'for' combined with a
1959 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
1960 // is not normalized as each team only executes its own assigned
1961 // distribute chunk
1962 QualType IteratorTy = IVExpr->getType();
1963 llvm::Value *LBVal = CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy,
1964 SourceLocation());
1965 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy,
1966 SourceLocation());
1967 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00001968}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001969
1970static void emitDistributeParallelForDistributeInnerBoundParams(
1971 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1972 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
1973 const auto &Dir = cast<OMPLoopDirective>(S);
1974 LValue LB =
1975 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
1976 auto LBCast = CGF.Builder.CreateIntCast(
1977 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
1978 CapturedVars.push_back(LBCast);
1979 LValue UB =
1980 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
1981
1982 auto UBCast = CGF.Builder.CreateIntCast(
1983 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
1984 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00001985}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001986
1987static void
1988emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
1989 const OMPLoopDirective &S,
1990 CodeGenFunction::JumpDest LoopExit) {
1991 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
1992 PrePostActionTy &) {
1993 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
1994 emitDistributeParallelForInnerBounds,
1995 emitDistributeParallelForDispatchBounds);
1996 };
1997
1998 emitCommonOMPParallelDirective(
1999 CGF, S, OMPD_for, CGInlinedWorksharingLoop,
2000 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002001}
2002
Carlo Bertolli9925f152016-06-27 14:55:37 +00002003void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2004 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002005 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2006 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2007 S.getDistInc());
2008 };
Carlo Bertolli9925f152016-06-27 14:55:37 +00002009 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002010 OMPCancelStackRAII CancelRegion(*this, OMPD_distribute_parallel_for,
2011 /*HasCancel=*/false);
2012 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
2013 /*HasCancel=*/false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002014}
2015
Kelvin Li4a39add2016-07-05 05:00:15 +00002016void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2017 const OMPDistributeParallelForSimdDirective &S) {
2018 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2019 CGM.getOpenMPRuntime().emitInlinedDirective(
2020 *this, OMPD_distribute_parallel_for_simd,
2021 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2022 OMPLoopScope PreInitScope(CGF, S);
2023 CGF.EmitStmt(
2024 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2025 });
2026}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002027
2028void CodeGenFunction::EmitOMPDistributeSimdDirective(
2029 const OMPDistributeSimdDirective &S) {
2030 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2031 CGM.getOpenMPRuntime().emitInlinedDirective(
2032 *this, OMPD_distribute_simd,
2033 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2034 OMPLoopScope PreInitScope(CGF, S);
2035 CGF.EmitStmt(
2036 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2037 });
2038}
2039
Alexey Bataevf8365372017-11-17 17:57:25 +00002040void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2041 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2042 // Emit SPMD target parallel for region as a standalone region.
2043 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2044 emitOMPSimdRegion(CGF, S, Action);
2045 };
2046 llvm::Function *Fn;
2047 llvm::Constant *Addr;
2048 // Emit target region as a standalone region.
2049 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2050 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2051 assert(Fn && Addr && "Target device function emission failed.");
2052}
2053
Kelvin Li986330c2016-07-20 22:57:10 +00002054void CodeGenFunction::EmitOMPTargetSimdDirective(
2055 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002056 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2057 emitOMPSimdRegion(CGF, S, Action);
2058 };
2059 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002060}
2061
Kelvin Li4e325f72016-10-25 12:50:55 +00002062void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
2063 const OMPTeamsDistributeSimdDirective &S) {
2064 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2065 CGM.getOpenMPRuntime().emitInlinedDirective(
2066 *this, OMPD_teams_distribute_simd,
2067 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2068 OMPLoopScope PreInitScope(CGF, S);
2069 CGF.EmitStmt(
2070 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2071 });
2072}
2073
Kelvin Li579e41c2016-11-30 23:51:03 +00002074void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
2075 const OMPTeamsDistributeParallelForSimdDirective &S) {
2076 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2077 CGM.getOpenMPRuntime().emitInlinedDirective(
2078 *this, OMPD_teams_distribute_parallel_for_simd,
2079 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2080 OMPLoopScope PreInitScope(CGF, S);
2081 CGF.EmitStmt(
2082 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2083 });
2084}
Kelvin Li4e325f72016-10-25 12:50:55 +00002085
Kelvin Li83c451e2016-12-25 04:52:54 +00002086void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
2087 const OMPTargetTeamsDistributeDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002088 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Li26fd21a2016-12-28 17:57:07 +00002089 CGM.getOpenMPRuntime().emitInlinedDirective(
2090 *this, OMPD_target_teams_distribute,
Kelvin Li83c451e2016-12-25 04:52:54 +00002091 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002092 CGF.EmitStmt(
2093 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Kelvin Li83c451e2016-12-25 04:52:54 +00002094 });
2095}
2096
Kelvin Li80e8f562016-12-29 22:16:30 +00002097void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
2098 const OMPTargetTeamsDistributeParallelForDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002099 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Li80e8f562016-12-29 22:16:30 +00002100 CGM.getOpenMPRuntime().emitInlinedDirective(
2101 *this, OMPD_target_teams_distribute_parallel_for,
2102 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2103 CGF.EmitStmt(
2104 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2105 });
2106}
2107
Kelvin Li1851df52017-01-03 05:23:48 +00002108void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2109 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002110 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Li1851df52017-01-03 05:23:48 +00002111 CGM.getOpenMPRuntime().emitInlinedDirective(
2112 *this, OMPD_target_teams_distribute_parallel_for_simd,
2113 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2114 CGF.EmitStmt(
2115 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2116 });
2117}
2118
Kelvin Lida681182017-01-10 18:08:18 +00002119void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
2120 const OMPTargetTeamsDistributeSimdDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002121 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Lida681182017-01-10 18:08:18 +00002122 CGM.getOpenMPRuntime().emitInlinedDirective(
2123 *this, OMPD_target_teams_distribute_simd,
2124 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2125 CGF.EmitStmt(
2126 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2127 });
2128}
2129
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002130namespace {
2131 struct ScheduleKindModifiersTy {
2132 OpenMPScheduleClauseKind Kind;
2133 OpenMPScheduleClauseModifier M1;
2134 OpenMPScheduleClauseModifier M2;
2135 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2136 OpenMPScheduleClauseModifier M1,
2137 OpenMPScheduleClauseModifier M2)
2138 : Kind(Kind), M1(M1), M2(M2) {}
2139 };
2140} // namespace
2141
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002142bool CodeGenFunction::EmitOMPWorksharingLoop(
2143 const OMPLoopDirective &S, Expr *EUB,
2144 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2145 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002146 // Emit the loop iteration variable.
2147 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2148 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2149 EmitVarDecl(*IVDecl);
2150
2151 // Emit the iterations count variable.
2152 // If it is not a variable, Sema decided to calculate iterations count on each
2153 // iteration (e.g., it is foldable into a constant).
2154 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2155 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2156 // Emit calculation of the iterations count.
2157 EmitIgnoredExpr(S.getCalcLastIteration());
2158 }
2159
2160 auto &RT = CGM.getOpenMPRuntime();
2161
Alexey Bataev38e89532015-04-16 04:54:05 +00002162 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002163 // Check pre-condition.
2164 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002165 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002166 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002167 // If the condition constant folds and can be elided, avoid emitting the
2168 // whole loop.
2169 bool CondConstant;
2170 llvm::BasicBlock *ContBlock = nullptr;
2171 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2172 if (!CondConstant)
2173 return false;
2174 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002175 auto *ThenBlock = createBasicBlock("omp.precond.then");
2176 ContBlock = createBasicBlock("omp.precond.end");
2177 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002178 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002179 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002180 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002181 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002182
Alexey Bataev8b427062016-05-25 12:36:08 +00002183 bool Ordered = false;
2184 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2185 if (OrderedClause->getNumForLoops())
2186 RT.emitDoacrossInit(*this, S);
2187 else
2188 Ordered = true;
2189 }
2190
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002191 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002192 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002193 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002194 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002195
2196 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2197 LValue LB = Bounds.first;
2198 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002199 LValue ST =
2200 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2201 LValue IL =
2202 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2203
Alexander Musmanc6388682014-12-15 07:07:06 +00002204 // Emit 'then' code.
2205 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002206 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002207 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002208 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002209 // initialization of firstprivate variables and post-update of
2210 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002211 CGM.getOpenMPRuntime().emitBarrierCall(
2212 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2213 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002214 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002215 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002216 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002217 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002218 EmitOMPPrivateLoopCounters(S, LoopScope);
2219 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002220 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002221
2222 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002223 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002224 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002225 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002226 ScheduleKind.Schedule = C->getScheduleKind();
2227 ScheduleKind.M1 = C->getFirstScheduleModifier();
2228 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002229 if (const auto *Ch = C->getChunkSize()) {
2230 Chunk = EmitScalarExpr(Ch);
2231 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2232 S.getIterationVariable()->getType(),
2233 S.getLocStart());
2234 }
2235 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002236 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2237 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002238 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2239 // If the static schedule kind is specified or if the ordered clause is
2240 // specified, and if no monotonic modifier is specified, the effect will
2241 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002242 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002243 /* Chunked */ Chunk != nullptr) &&
2244 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002245 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2246 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002247 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2248 // When no chunk_size is specified, the iteration space is divided into
2249 // chunks that are approximately equal in size, and at most one chunk is
2250 // distributed to each thread. Note that the size of the chunks is
2251 // unspecified in this case.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002252 CGOpenMPRuntime::StaticRTInput StaticInit(
2253 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
2254 UB.getAddress(), ST.getAddress());
2255 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
2256 ScheduleKind, StaticInit);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002257 auto LoopExit =
2258 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002259 // UB = min(UB, GlobalUB);
2260 EmitIgnoredExpr(S.getEnsureUpperBound());
2261 // IV = LB;
2262 EmitIgnoredExpr(S.getInit());
2263 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002264 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2265 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002266 [&S, LoopExit](CodeGenFunction &CGF) {
2267 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002268 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002269 },
2270 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002271 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002272 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002273 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002274 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2275 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002276 };
2277 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002278 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002279 const bool IsMonotonic =
2280 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2281 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2282 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2283 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002284 // Emit the outer loop, which requests its work chunk [LB..UB] from
2285 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002286 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2287 ST.getAddress(), IL.getAddress(),
2288 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002289 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002290 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002291 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002292 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2293 EmitOMPSimdFinal(S,
2294 [&](CodeGenFunction &CGF) -> llvm::Value * {
2295 return CGF.Builder.CreateIsNotNull(
2296 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2297 });
2298 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002299 EmitOMPReductionClauseFinal(
2300 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2301 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2302 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002303 // Emit post-update of the reduction variables if IsLastIter != 0.
2304 emitPostUpdateForReductionClause(
2305 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2306 return CGF.Builder.CreateIsNotNull(
2307 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2308 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002309 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2310 if (HasLastprivateClause)
2311 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002312 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2313 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002314 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002315 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002316 return CGF.Builder.CreateIsNotNull(
2317 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2318 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002319 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002320 if (ContBlock) {
2321 EmitBranch(ContBlock);
2322 EmitBlock(ContBlock, true);
2323 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002324 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002325 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002326}
2327
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002328/// The following two functions generate expressions for the loop lower
2329/// and upper bounds in case of static and dynamic (dispatch) schedule
2330/// of the associated 'for' or 'distribute' loop.
2331static std::pair<LValue, LValue>
2332emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2333 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2334 LValue LB =
2335 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2336 LValue UB =
2337 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2338 return {LB, UB};
2339}
2340
2341/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2342/// consider the lower and upper bound expressions generated by the
2343/// worksharing loop support, but we use 0 and the iteration space size as
2344/// constants
2345static std::pair<llvm::Value *, llvm::Value *>
2346emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2347 Address LB, Address UB) {
2348 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2349 const Expr *IVExpr = LS.getIterationVariable();
2350 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2351 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2352 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2353 return {LBVal, UBVal};
2354}
2355
Alexander Musmanc6388682014-12-15 07:07:06 +00002356void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002357 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002358 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2359 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002360 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002361 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2362 emitForLoopBounds,
2363 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002364 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002365 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002366 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002367 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2368 S.hasCancel());
2369 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002370
2371 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002372 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002373 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2374 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002375}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002376
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002377void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002378 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002379 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2380 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002381 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2382 emitForLoopBounds,
2383 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002384 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002385 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002386 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002387 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2388 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002389
2390 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002391 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002392 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2393 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002394}
2395
Alexey Bataev2df54a02015-03-12 08:53:29 +00002396static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2397 const Twine &Name,
2398 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002399 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002400 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002401 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002402 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002403}
2404
Alexey Bataev3392d762016-02-16 11:18:12 +00002405void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00002406 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2407 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002408 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002409 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2410 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002411 auto &C = CGF.CGM.getContext();
2412 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2413 // Emit helper vars inits.
2414 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2415 CGF.Builder.getInt32(0));
2416 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2417 : CGF.Builder.getInt32(0);
2418 LValue UB =
2419 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2420 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2421 CGF.Builder.getInt32(1));
2422 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2423 CGF.Builder.getInt32(0));
2424 // Loop counter.
2425 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2426 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2427 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2428 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2429 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2430 // Generate condition for loop.
2431 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002432 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002433 // Increment for loop counter.
2434 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2435 S.getLocStart());
2436 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2437 // Iterate through all sections and emit a switch construct:
2438 // switch (IV) {
2439 // case 0:
2440 // <SectionStmt[0]>;
2441 // break;
2442 // ...
2443 // case <NumSection> - 1:
2444 // <SectionStmt[<NumSection> - 1]>;
2445 // break;
2446 // }
2447 // .omp.sections.exit:
2448 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2449 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2450 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2451 CS == nullptr ? 1 : CS->size());
2452 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002453 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002454 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002455 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2456 CGF.EmitBlock(CaseBB);
2457 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002458 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002459 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002460 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002461 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002462 } else {
2463 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2464 CGF.EmitBlock(CaseBB);
2465 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2466 CGF.EmitStmt(Stmt);
2467 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002468 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002469 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002470 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002471
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002472 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2473 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002474 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002475 // initialization of firstprivate variables and post-update of lastprivate
2476 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002477 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2478 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2479 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002480 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002481 CGF.EmitOMPPrivateClause(S, LoopScope);
2482 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2483 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2484 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002485
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002486 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002487 OpenMPScheduleTy ScheduleKind;
2488 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002489 CGOpenMPRuntime::StaticRTInput StaticInit(
2490 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2491 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002492 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002493 CGF, S.getLocStart(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002494 // UB = min(UB, GlobalUB);
2495 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2496 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2497 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2498 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2499 // IV = LB;
2500 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2501 // while (idx <= UB) { BODY; ++idx; }
2502 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2503 [](CodeGenFunction &) {});
2504 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002505 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002506 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2507 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002508 };
2509 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002510 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002511 // Emit post-update of the reduction variables if IsLastIter != 0.
2512 emitPostUpdateForReductionClause(
2513 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2514 return CGF.Builder.CreateIsNotNull(
2515 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2516 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002517
2518 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2519 if (HasLastprivates)
2520 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002521 S, /*NoFinals=*/false,
2522 CGF.Builder.CreateIsNotNull(
2523 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002524 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002525
2526 bool HasCancel = false;
2527 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2528 HasCancel = OSD->hasCancel();
2529 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2530 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002531 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002532 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2533 HasCancel);
2534 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2535 // clause. Otherwise the barrier will be generated by the codegen for the
2536 // directive.
2537 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002538 // Emit implicit barrier to synchronize threads and avoid data races on
2539 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002540 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2541 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002542 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002543}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002544
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002545void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002546 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002547 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002548 EmitSections(S);
2549 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002550 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002551 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002552 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2553 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002554 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002555}
2556
2557void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002558 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002559 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002560 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002561 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002562 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2563 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002564}
2565
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002566void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002567 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002568 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002569 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002570 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002571 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002572 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002573 // Build a list of copyprivate variables along with helper expressions
2574 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002575 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002576 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002577 DestExprs.append(C->destination_exprs().begin(),
2578 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002579 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002580 AssignmentOps.append(C->assignment_ops().begin(),
2581 C->assignment_ops().end());
2582 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002583 // Emit code for 'single' region along with 'copyprivate' clauses
2584 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2585 Action.Enter(CGF);
2586 OMPPrivateScope SingleScope(CGF);
2587 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2588 CGF.EmitOMPPrivateClause(S, SingleScope);
2589 (void)SingleScope.Privatize();
2590 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2591 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002592 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002593 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002594 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2595 CopyprivateVars, DestExprs,
2596 SrcExprs, AssignmentOps);
2597 }
2598 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2599 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002600 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002601 CGM.getOpenMPRuntime().emitBarrierCall(
2602 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002603 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002604 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002605}
2606
Alexey Bataev8d690652014-12-04 07:23:53 +00002607void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002608 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2609 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002610 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002611 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002612 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002613 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002614}
2615
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002616void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002617 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2618 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002619 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002620 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002621 Expr *Hint = nullptr;
2622 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2623 Hint = HintClause->getHint();
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002624 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002625 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2626 S.getDirectiveName().getAsString(),
2627 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002628}
2629
Alexey Bataev671605e2015-04-13 05:28:11 +00002630void CodeGenFunction::EmitOMPParallelForDirective(
2631 const OMPParallelForDirective &S) {
2632 // Emit directive as a combined directive that consists of two implicit
2633 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002634 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002635 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002636 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2637 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002638 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002639 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2640 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002641}
2642
Alexander Musmane4e893b2014-09-23 09:33:00 +00002643void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002644 const OMPParallelForSimdDirective &S) {
2645 // Emit directive as a combined directive that consists of two implicit
2646 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002647 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002648 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2649 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002650 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002651 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2652 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002653}
2654
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002655void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002656 const OMPParallelSectionsDirective &S) {
2657 // Emit directive as a combined directive that consists of two implicit
2658 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002659 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2660 CGF.EmitSections(S);
2661 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002662 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2663 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002664}
2665
Alexey Bataev7292c292016-04-25 12:22:29 +00002666void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2667 const RegionCodeGenTy &BodyGen,
2668 const TaskGenTy &TaskGen,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002669 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002670 // Emit outlined function for task construct.
2671 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002672 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002673 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002674 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002675 // Check if the task is final
2676 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2677 // If the condition constant folds and can be elided, try to avoid emitting
2678 // the condition and the dead arm of the if/else.
2679 auto *Cond = Clause->getCondition();
2680 bool CondConstant;
2681 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2682 Data.Final.setInt(CondConstant);
2683 else
2684 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2685 } else {
2686 // By default the task is not final.
2687 Data.Final.setInt(/*IntVal=*/false);
2688 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002689 // Check if the task has 'priority' clause.
2690 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002691 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002692 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002693 Data.Priority.setPointer(EmitScalarConversion(
2694 EmitScalarExpr(Prio), Prio->getType(),
2695 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2696 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002697 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002698 // The first function argument for tasks is a thread id, the second one is a
2699 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002700 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2701 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002702 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002703 auto IRef = C->varlist_begin();
2704 for (auto *IInit : C->private_copies()) {
2705 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2706 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002707 Data.PrivateVars.push_back(*IRef);
2708 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002709 }
2710 ++IRef;
2711 }
2712 }
2713 EmittedAsPrivate.clear();
2714 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002715 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002716 auto IRef = C->varlist_begin();
2717 auto IElemInitRef = C->inits().begin();
2718 for (auto *IInit : C->private_copies()) {
2719 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2720 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002721 Data.FirstprivateVars.push_back(*IRef);
2722 Data.FirstprivateCopies.push_back(IInit);
2723 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002724 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002725 ++IRef;
2726 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002727 }
2728 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002729 // Get list of lastprivate variables (for taskloops).
2730 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2731 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2732 auto IRef = C->varlist_begin();
2733 auto ID = C->destination_exprs().begin();
2734 for (auto *IInit : C->private_copies()) {
2735 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2736 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2737 Data.LastprivateVars.push_back(*IRef);
2738 Data.LastprivateCopies.push_back(IInit);
2739 }
2740 LastprivateDstsOrigs.insert(
2741 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2742 cast<DeclRefExpr>(*IRef)});
2743 ++IRef;
2744 ++ID;
2745 }
2746 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002747 SmallVector<const Expr *, 4> LHSs;
2748 SmallVector<const Expr *, 4> RHSs;
2749 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2750 auto IPriv = C->privates().begin();
2751 auto IRed = C->reduction_ops().begin();
2752 auto ILHS = C->lhs_exprs().begin();
2753 auto IRHS = C->rhs_exprs().begin();
2754 for (const auto *Ref : C->varlists()) {
2755 Data.ReductionVars.emplace_back(Ref);
2756 Data.ReductionCopies.emplace_back(*IPriv);
2757 Data.ReductionOps.emplace_back(*IRed);
2758 LHSs.emplace_back(*ILHS);
2759 RHSs.emplace_back(*IRHS);
2760 std::advance(IPriv, 1);
2761 std::advance(IRed, 1);
2762 std::advance(ILHS, 1);
2763 std::advance(IRHS, 1);
2764 }
2765 }
2766 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2767 *this, S.getLocStart(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002768 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002769 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2770 for (auto *IRef : C->varlists())
2771 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002772 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs](
Alexey Bataevf93095a2016-05-05 08:46:22 +00002773 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002774 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002775 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002776 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2777 !Data.LastprivateVars.empty()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00002778 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataev48591dd2016-04-20 04:01:36 +00002779 auto *CopyFn = CGF.Builder.CreateLoad(
2780 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2781 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2782 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2783 // Map privates.
2784 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2785 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2786 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002787 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002788 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2789 Address PrivatePtr = CGF.CreateMemTemp(
2790 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2791 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2792 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002793 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002794 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002795 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2796 Address PrivatePtr =
2797 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2798 ".firstpriv.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 Bataevf93095a2016-05-05 08:46:22 +00002802 for (auto *E : Data.LastprivateVars) {
2803 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2804 Address PrivatePtr =
2805 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2806 ".lastpriv.ptr.addr");
2807 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2808 CallArgs.push_back(PrivatePtr.getPointer());
2809 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00002810 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
2811 CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002812 for (auto &&Pair : LastprivateDstsOrigs) {
2813 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2814 DeclRefExpr DRE(
2815 const_cast<VarDecl *>(OrigVD),
2816 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2817 OrigVD) != nullptr,
2818 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2819 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2820 return CGF.EmitLValue(&DRE).getAddress();
2821 });
2822 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002823 for (auto &&Pair : PrivatePtrs) {
2824 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2825 CGF.getContext().getDeclAlign(Pair.first));
2826 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2827 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002828 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002829 if (Data.Reductions) {
2830 OMPLexicalScope LexScope(CGF, S, /*AsInlined=*/true);
2831 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2832 Data.ReductionOps);
2833 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2834 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2835 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2836 RedCG.emitSharedLValue(CGF, Cnt);
2837 RedCG.emitAggregateType(CGF, Cnt);
2838 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2839 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2840 Replacement =
2841 Address(CGF.EmitScalarConversion(
2842 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2843 CGF.getContext().getPointerType(
2844 Data.ReductionCopies[Cnt]->getType()),
2845 SourceLocation()),
2846 Replacement.getAlignment());
2847 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2848 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2849 [Replacement]() { return Replacement; });
2850 // FIXME: This must removed once the runtime library is fixed.
2851 // Emit required threadprivate variables for
2852 // initilizer/combiner/finalizer.
2853 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2854 RedCG, Cnt);
2855 }
2856 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002857 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002858 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002859 SmallVector<const Expr *, 4> InRedVars;
2860 SmallVector<const Expr *, 4> InRedPrivs;
2861 SmallVector<const Expr *, 4> InRedOps;
2862 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2863 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2864 auto IPriv = C->privates().begin();
2865 auto IRed = C->reduction_ops().begin();
2866 auto ITD = C->taskgroup_descriptors().begin();
2867 for (const auto *Ref : C->varlists()) {
2868 InRedVars.emplace_back(Ref);
2869 InRedPrivs.emplace_back(*IPriv);
2870 InRedOps.emplace_back(*IRed);
2871 TaskgroupDescriptors.emplace_back(*ITD);
2872 std::advance(IPriv, 1);
2873 std::advance(IRed, 1);
2874 std::advance(ITD, 1);
2875 }
2876 }
2877 // Privatize in_reduction items here, because taskgroup descriptors must be
2878 // privatized earlier.
2879 OMPPrivateScope InRedScope(CGF);
2880 if (!InRedVars.empty()) {
2881 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2882 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2883 RedCG.emitSharedLValue(CGF, Cnt);
2884 RedCG.emitAggregateType(CGF, Cnt);
2885 // The taskgroup descriptor variable is always implicit firstprivate and
2886 // privatized already during procoessing of the firstprivates.
2887 llvm::Value *ReductionsPtr = CGF.EmitLoadOfScalar(
2888 CGF.EmitLValue(TaskgroupDescriptors[Cnt]), SourceLocation());
2889 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2890 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2891 Replacement = Address(
2892 CGF.EmitScalarConversion(
2893 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2894 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
2895 SourceLocation()),
2896 Replacement.getAlignment());
2897 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2898 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2899 [Replacement]() { return Replacement; });
2900 // FIXME: This must removed once the runtime library is fixed.
2901 // Emit required threadprivate variables for
2902 // initilizer/combiner/finalizer.
2903 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2904 RedCG, Cnt);
2905 }
2906 }
2907 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00002908
2909 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002910 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002911 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002912 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2913 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2914 Data.NumberOfParts);
2915 OMPLexicalScope Scope(*this, S);
2916 TaskGen(*this, OutlinedFn, Data);
2917}
2918
2919void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2920 // Emit outlined function for task construct.
2921 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2922 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002923 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002924 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002925 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2926 if (C->getNameModifier() == OMPD_unknown ||
2927 C->getNameModifier() == OMPD_task) {
2928 IfCond = C->getCondition();
2929 break;
2930 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002931 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002932
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002933 OMPTaskDataTy Data;
2934 // Check if we should emit tied or untied task.
2935 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00002936 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
2937 CGF.EmitStmt(CS->getCapturedStmt());
2938 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002939 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00002940 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002941 const OMPTaskDataTy &Data) {
2942 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
2943 SharedsTy, CapturedStruct, IfCond,
2944 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00002945 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002946 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002947}
2948
Alexey Bataev9f797f32015-02-05 05:57:51 +00002949void CodeGenFunction::EmitOMPTaskyieldDirective(
2950 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002951 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002952}
2953
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002954void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002955 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002956}
2957
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002958void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2959 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002960}
2961
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002962void CodeGenFunction::EmitOMPTaskgroupDirective(
2963 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002964 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2965 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002966 if (const Expr *E = S.getReductionRef()) {
2967 SmallVector<const Expr *, 4> LHSs;
2968 SmallVector<const Expr *, 4> RHSs;
2969 OMPTaskDataTy Data;
2970 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
2971 auto IPriv = C->privates().begin();
2972 auto IRed = C->reduction_ops().begin();
2973 auto ILHS = C->lhs_exprs().begin();
2974 auto IRHS = C->rhs_exprs().begin();
2975 for (const auto *Ref : C->varlists()) {
2976 Data.ReductionVars.emplace_back(Ref);
2977 Data.ReductionCopies.emplace_back(*IPriv);
2978 Data.ReductionOps.emplace_back(*IRed);
2979 LHSs.emplace_back(*ILHS);
2980 RHSs.emplace_back(*IRHS);
2981 std::advance(IPriv, 1);
2982 std::advance(IRed, 1);
2983 std::advance(ILHS, 1);
2984 std::advance(IRHS, 1);
2985 }
2986 }
2987 llvm::Value *ReductionDesc =
2988 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getLocStart(),
2989 LHSs, RHSs, Data);
2990 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2991 CGF.EmitVarDecl(*VD);
2992 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
2993 /*Volatile=*/false, E->getType());
2994 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002995 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002996 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002997 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002998 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2999}
3000
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003001void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003002 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003003 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003004 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3005 FlushClause->varlist_end());
3006 }
3007 return llvm::None;
3008 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00003009}
3010
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003011void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3012 const CodeGenLoopTy &CodeGenLoop,
3013 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003014 // Emit the loop iteration variable.
3015 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3016 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
3017 EmitVarDecl(*IVDecl);
3018
3019 // Emit the iterations count variable.
3020 // If it is not a variable, Sema decided to calculate iterations count on each
3021 // iteration (e.g., it is foldable into a constant).
3022 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3023 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3024 // Emit calculation of the iterations count.
3025 EmitIgnoredExpr(S.getCalcLastIteration());
3026 }
3027
3028 auto &RT = CGM.getOpenMPRuntime();
3029
Carlo Bertolli962bb802017-01-03 18:24:42 +00003030 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003031 // Check pre-condition.
3032 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003033 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003034 // Skip the entire loop if we don't meet the precondition.
3035 // If the condition constant folds and can be elided, avoid emitting the
3036 // whole loop.
3037 bool CondConstant;
3038 llvm::BasicBlock *ContBlock = nullptr;
3039 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3040 if (!CondConstant)
3041 return;
3042 } else {
3043 auto *ThenBlock = createBasicBlock("omp.precond.then");
3044 ContBlock = createBasicBlock("omp.precond.end");
3045 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3046 getProfileCount(&S));
3047 EmitBlock(ThenBlock);
3048 incrementProfileCounter(&S);
3049 }
3050
3051 // Emit 'then' code.
3052 {
3053 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003054
3055 LValue LB = EmitOMPHelperVar(
3056 *this, cast<DeclRefExpr>(
3057 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3058 ? S.getCombinedLowerBoundVariable()
3059 : S.getLowerBoundVariable())));
3060 LValue UB = EmitOMPHelperVar(
3061 *this, cast<DeclRefExpr>(
3062 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3063 ? S.getCombinedUpperBoundVariable()
3064 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003065 LValue ST =
3066 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3067 LValue IL =
3068 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3069
3070 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003071 if (EmitOMPFirstprivateClause(S, LoopScope)) {
3072 // Emit implicit barrier to synchronize threads and avoid data races on
3073 // initialization of firstprivate variables and post-update of
3074 // lastprivate variables.
3075 CGM.getOpenMPRuntime().emitBarrierCall(
3076 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3077 /*ForceSimpleCall=*/true);
3078 }
3079 EmitOMPPrivateClause(S, LoopScope);
3080 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003081 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003082 (void)LoopScope.Privatize();
3083
3084 // Detect the distribute schedule kind and chunk.
3085 llvm::Value *Chunk = nullptr;
3086 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3087 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3088 ScheduleKind = C->getDistScheduleKind();
3089 if (const auto *Ch = C->getChunkSize()) {
3090 Chunk = EmitScalarExpr(Ch);
3091 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
3092 S.getIterationVariable()->getType(),
3093 S.getLocStart());
3094 }
3095 }
3096 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3097 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3098
3099 // OpenMP [2.10.8, distribute Construct, Description]
3100 // If dist_schedule is specified, kind must be static. If specified,
3101 // iterations are divided into chunks of size chunk_size, chunks are
3102 // assigned to the teams of the league in a round-robin fashion in the
3103 // order of the team number. When no chunk_size is specified, the
3104 // iteration space is divided into chunks that are approximately equal
3105 // in size, and at most one chunk is distributed to each team of the
3106 // league. The size of the chunks is unspecified in this case.
3107 if (RT.isStaticNonchunked(ScheduleKind,
3108 /* Chunked */ Chunk != nullptr)) {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003109 CGOpenMPRuntime::StaticRTInput StaticInit(
3110 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3111 LB.getAddress(), UB.getAddress(), ST.getAddress());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003112 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003113 StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003114 auto LoopExit =
3115 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3116 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003117 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3118 ? S.getCombinedEnsureUpperBound()
3119 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003120 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003121 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3122 ? S.getCombinedInit()
3123 : S.getInit());
3124
3125 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3126 ? S.getCombinedCond()
3127 : S.getCond();
3128
3129 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003130 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003131 // when combined with 'for' (e.g. as in 'distribute parallel for')
3132 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3133 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3134 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3135 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003136 },
3137 [](CodeGenFunction &) {});
3138 EmitBlock(LoopExit.getBlock());
3139 // Tell the runtime we are done.
Alexey Bataevf43f7142017-09-06 16:17:35 +00003140 RT.emitForStaticFinish(*this, S.getLocStart(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003141 } else {
3142 // Emit the outer loop, which requests its work chunk [LB..UB] from
3143 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003144 const OMPLoopArguments LoopArguments = {
3145 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3146 Chunk};
3147 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3148 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003149 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00003150
3151 // Emit final copy of the lastprivate variables if IsLastIter != 0.
3152 if (HasLastprivateClause)
3153 EmitOMPLastprivateClauseFinal(
3154 S, /*NoFinals=*/false,
3155 Builder.CreateIsNotNull(
3156 EmitLoadOfScalar(IL, S.getLocStart())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003157 }
3158
3159 // We're now done with the loop, so jump to the continuation block.
3160 if (ContBlock) {
3161 EmitBranch(ContBlock);
3162 EmitBlock(ContBlock, true);
3163 }
3164 }
3165}
3166
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003167void CodeGenFunction::EmitOMPDistributeDirective(
3168 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003169 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003170
3171 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003172 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003173 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003174 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
3175 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003176}
3177
Alexey Bataev5f600d62015-09-29 03:48:57 +00003178static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3179 const CapturedStmt *S) {
3180 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3181 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3182 CGF.CapturedStmtInfo = &CapStmtInfo;
3183 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3184 Fn->addFnAttr(llvm::Attribute::NoInline);
3185 return Fn;
3186}
3187
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003188void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8b427062016-05-25 12:36:08 +00003189 if (!S.getAssociatedStmt()) {
3190 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3191 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003192 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003193 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003194 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003195 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3196 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003197 if (C) {
3198 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3199 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3200 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3201 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Alexey Bataev3c595a62017-08-14 15:01:03 +00003202 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3203 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003204 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003205 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003206 CGF.EmitStmt(
3207 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3208 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003209 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003210 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003211 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003212}
3213
Alexey Bataevb57056f2015-01-22 06:17:56 +00003214static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003215 QualType SrcType, QualType DestType,
3216 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003217 assert(CGF.hasScalarEvaluationKind(DestType) &&
3218 "DestType must have scalar evaluation kind.");
3219 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3220 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003221 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3222 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00003223 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003224 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003225}
3226
3227static CodeGenFunction::ComplexPairTy
3228convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003229 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003230 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3231 "DestType must have complex evaluation kind.");
3232 CodeGenFunction::ComplexPairTy ComplexVal;
3233 if (Val.isScalar()) {
3234 // Convert the input element to the element type of the complex.
3235 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003236 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3237 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003238 ComplexVal = CodeGenFunction::ComplexPairTy(
3239 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3240 } else {
3241 assert(Val.isComplex() && "Must be a scalar or complex.");
3242 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3243 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3244 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003245 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003246 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003247 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003248 }
3249 return ComplexVal;
3250}
3251
Alexey Bataev5e018f92015-04-23 06:35:10 +00003252static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3253 LValue LVal, RValue RVal) {
3254 if (LVal.isGlobalReg()) {
3255 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3256 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003257 CGF.EmitAtomicStore(RVal, LVal,
3258 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3259 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003260 LVal.isVolatile(), /*IsInit=*/false);
3261 }
3262}
3263
Alexey Bataev8524d152016-01-21 12:35:58 +00003264void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3265 QualType RValTy, SourceLocation Loc) {
3266 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003267 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003268 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3269 *this, RVal, RValTy, LVal.getType(), Loc)),
3270 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003271 break;
3272 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003273 EmitStoreOfComplex(
3274 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003275 /*isInit=*/false);
3276 break;
3277 case TEK_Aggregate:
3278 llvm_unreachable("Must be a scalar or complex.");
3279 }
3280}
3281
Alexey Bataevb57056f2015-01-22 06:17:56 +00003282static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3283 const Expr *X, const Expr *V,
3284 SourceLocation Loc) {
3285 // v = x;
3286 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3287 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3288 LValue XLValue = CGF.EmitLValue(X);
3289 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003290 RValue Res = XLValue.isGlobalReg()
3291 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003292 : CGF.EmitAtomicLoad(
3293 XLValue, Loc,
3294 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3295 : llvm::AtomicOrdering::Monotonic,
3296 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003297 // OpenMP, 2.12.6, atomic Construct
3298 // Any atomic construct with a seq_cst clause forces the atomically
3299 // performed operation to include an implicit flush operation without a
3300 // list.
3301 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003302 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003303 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003304}
3305
Alexey Bataevb8329262015-02-27 06:33:30 +00003306static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3307 const Expr *X, const Expr *E,
3308 SourceLocation Loc) {
3309 // x = expr;
3310 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003311 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003312 // OpenMP, 2.12.6, atomic Construct
3313 // Any atomic construct with a seq_cst clause forces the atomically
3314 // performed operation to include an implicit flush operation without a
3315 // list.
3316 if (IsSeqCst)
3317 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3318}
3319
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003320static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3321 RValue Update,
3322 BinaryOperatorKind BO,
3323 llvm::AtomicOrdering AO,
3324 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003325 auto &Context = CGF.CGM.getContext();
3326 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003327 // expression is simple and atomic is allowed for the given type for the
3328 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003329 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003330 !Update.getScalarVal()->getType()->isIntegerTy() ||
3331 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3332 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003333 X.getAddress().getElementType())) ||
3334 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003335 !Context.getTargetInfo().hasBuiltinAtomic(
3336 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003337 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003338
3339 llvm::AtomicRMWInst::BinOp RMWOp;
3340 switch (BO) {
3341 case BO_Add:
3342 RMWOp = llvm::AtomicRMWInst::Add;
3343 break;
3344 case BO_Sub:
3345 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003346 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003347 RMWOp = llvm::AtomicRMWInst::Sub;
3348 break;
3349 case BO_And:
3350 RMWOp = llvm::AtomicRMWInst::And;
3351 break;
3352 case BO_Or:
3353 RMWOp = llvm::AtomicRMWInst::Or;
3354 break;
3355 case BO_Xor:
3356 RMWOp = llvm::AtomicRMWInst::Xor;
3357 break;
3358 case BO_LT:
3359 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3360 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3361 : llvm::AtomicRMWInst::Max)
3362 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3363 : llvm::AtomicRMWInst::UMax);
3364 break;
3365 case BO_GT:
3366 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3367 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3368 : llvm::AtomicRMWInst::Min)
3369 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3370 : llvm::AtomicRMWInst::UMin);
3371 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003372 case BO_Assign:
3373 RMWOp = llvm::AtomicRMWInst::Xchg;
3374 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003375 case BO_Mul:
3376 case BO_Div:
3377 case BO_Rem:
3378 case BO_Shl:
3379 case BO_Shr:
3380 case BO_LAnd:
3381 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003382 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003383 case BO_PtrMemD:
3384 case BO_PtrMemI:
3385 case BO_LE:
3386 case BO_GE:
3387 case BO_EQ:
3388 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003389 case BO_AddAssign:
3390 case BO_SubAssign:
3391 case BO_AndAssign:
3392 case BO_OrAssign:
3393 case BO_XorAssign:
3394 case BO_MulAssign:
3395 case BO_DivAssign:
3396 case BO_RemAssign:
3397 case BO_ShlAssign:
3398 case BO_ShrAssign:
3399 case BO_Comma:
3400 llvm_unreachable("Unsupported atomic update operation");
3401 }
3402 auto *UpdateVal = Update.getScalarVal();
3403 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3404 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003405 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003406 X.getType()->hasSignedIntegerRepresentation());
3407 }
John McCall7f416cc2015-09-08 08:05:57 +00003408 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003409 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003410}
3411
Alexey Bataev5e018f92015-04-23 06:35:10 +00003412std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003413 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3414 llvm::AtomicOrdering AO, SourceLocation Loc,
3415 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3416 // Update expressions are allowed to have the following forms:
3417 // x binop= expr; -> xrval + expr;
3418 // x++, ++x -> xrval + 1;
3419 // x--, --x -> xrval - 1;
3420 // x = x binop expr; -> xrval binop expr
3421 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003422 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3423 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003424 if (X.isGlobalReg()) {
3425 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3426 // 'xrval'.
3427 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3428 } else {
3429 // Perform compare-and-swap procedure.
3430 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003431 }
3432 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003433 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003434}
3435
3436static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3437 const Expr *X, const Expr *E,
3438 const Expr *UE, bool IsXLHSInRHSPart,
3439 SourceLocation Loc) {
3440 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3441 "Update expr in 'atomic update' must be a binary operator.");
3442 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3443 // Update expressions are allowed to have the following forms:
3444 // x binop= expr; -> xrval + expr;
3445 // x++, ++x -> xrval + 1;
3446 // x--, --x -> xrval - 1;
3447 // x = x binop expr; -> xrval binop expr
3448 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003449 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003450 LValue XLValue = CGF.EmitLValue(X);
3451 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003452 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3453 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003454 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3455 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3456 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3457 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3458 auto Gen =
3459 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3460 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3461 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3462 return CGF.EmitAnyExpr(UE);
3463 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003464 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3465 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3466 // OpenMP, 2.12.6, atomic Construct
3467 // Any atomic construct with a seq_cst clause forces the atomically
3468 // performed operation to include an implicit flush operation without a
3469 // list.
3470 if (IsSeqCst)
3471 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3472}
3473
3474static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003475 QualType SourceType, QualType ResType,
3476 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003477 switch (CGF.getEvaluationKind(ResType)) {
3478 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003479 return RValue::get(
3480 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003481 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003482 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003483 return RValue::getComplex(Res.first, Res.second);
3484 }
3485 case TEK_Aggregate:
3486 break;
3487 }
3488 llvm_unreachable("Must be a scalar or complex.");
3489}
3490
3491static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3492 bool IsPostfixUpdate, const Expr *V,
3493 const Expr *X, const Expr *E,
3494 const Expr *UE, bool IsXLHSInRHSPart,
3495 SourceLocation Loc) {
3496 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3497 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3498 RValue NewVVal;
3499 LValue VLValue = CGF.EmitLValue(V);
3500 LValue XLValue = CGF.EmitLValue(X);
3501 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003502 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3503 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003504 QualType NewVValType;
3505 if (UE) {
3506 // 'x' is updated with some additional value.
3507 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3508 "Update expr in 'atomic capture' must be a binary operator.");
3509 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3510 // Update expressions are allowed to have the following forms:
3511 // x binop= expr; -> xrval + expr;
3512 // x++, ++x -> xrval + 1;
3513 // x--, --x -> xrval - 1;
3514 // x = x binop expr; -> xrval binop expr
3515 // x = expr Op x; - > expr binop xrval;
3516 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3517 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3518 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3519 NewVValType = XRValExpr->getType();
3520 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3521 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003522 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003523 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3524 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3525 RValue Res = CGF.EmitAnyExpr(UE);
3526 NewVVal = IsPostfixUpdate ? XRValue : Res;
3527 return Res;
3528 };
3529 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3530 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3531 if (Res.first) {
3532 // 'atomicrmw' instruction was generated.
3533 if (IsPostfixUpdate) {
3534 // Use old value from 'atomicrmw'.
3535 NewVVal = Res.second;
3536 } else {
3537 // 'atomicrmw' does not provide new value, so evaluate it using old
3538 // value of 'x'.
3539 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3540 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3541 NewVVal = CGF.EmitAnyExpr(UE);
3542 }
3543 }
3544 } else {
3545 // 'x' is simply rewritten with some 'expr'.
3546 NewVValType = X->getType().getNonReferenceType();
3547 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003548 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003549 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003550 NewVVal = XRValue;
3551 return ExprRValue;
3552 };
3553 // Try to perform atomicrmw xchg, otherwise simple exchange.
3554 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3555 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3556 Loc, Gen);
3557 if (Res.first) {
3558 // 'atomicrmw' instruction was generated.
3559 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3560 }
3561 }
3562 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003563 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003564 // OpenMP, 2.12.6, atomic Construct
3565 // Any atomic construct with a seq_cst clause forces the atomically
3566 // performed operation to include an implicit flush operation without a
3567 // list.
3568 if (IsSeqCst)
3569 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3570}
3571
Alexey Bataevb57056f2015-01-22 06:17:56 +00003572static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003573 bool IsSeqCst, bool IsPostfixUpdate,
3574 const Expr *X, const Expr *V, const Expr *E,
3575 const Expr *UE, bool IsXLHSInRHSPart,
3576 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003577 switch (Kind) {
3578 case OMPC_read:
3579 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3580 break;
3581 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003582 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3583 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003584 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003585 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003586 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3587 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003588 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003589 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3590 IsXLHSInRHSPart, Loc);
3591 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003592 case OMPC_if:
3593 case OMPC_final:
3594 case OMPC_num_threads:
3595 case OMPC_private:
3596 case OMPC_firstprivate:
3597 case OMPC_lastprivate:
3598 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003599 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003600 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003601 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003602 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003603 case OMPC_collapse:
3604 case OMPC_default:
3605 case OMPC_seq_cst:
3606 case OMPC_shared:
3607 case OMPC_linear:
3608 case OMPC_aligned:
3609 case OMPC_copyin:
3610 case OMPC_copyprivate:
3611 case OMPC_flush:
3612 case OMPC_proc_bind:
3613 case OMPC_schedule:
3614 case OMPC_ordered:
3615 case OMPC_nowait:
3616 case OMPC_untied:
3617 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003618 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003619 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003620 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003621 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003622 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003623 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003624 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003625 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003626 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003627 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003628 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003629 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003630 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003631 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003632 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003633 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003634 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003635 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003636 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003637 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003638 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3639 }
3640}
3641
3642void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003643 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003644 OpenMPClauseKind Kind = OMPC_unknown;
3645 for (auto *C : S.clauses()) {
3646 // Find first clause (skip seq_cst clause, if it is first).
3647 if (C->getClauseKind() != OMPC_seq_cst) {
3648 Kind = C->getClauseKind();
3649 break;
3650 }
3651 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003652
3653 const auto *CS =
3654 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003655 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003656 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003657 }
3658 // Processing for statements under 'atomic capture'.
3659 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3660 for (const auto *C : Compound->body()) {
3661 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3662 enterFullExpression(EWC);
3663 }
3664 }
3665 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003666
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003667 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3668 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003669 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003670 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3671 S.getV(), S.getExpr(), S.getUpdateExpr(),
3672 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003673 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003674 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003675 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003676}
3677
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003678static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3679 const OMPExecutableDirective &S,
3680 const RegionCodeGenTy &CodeGen) {
3681 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3682 CodeGenModule &CGM = CGF.CGM;
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00003683 const CapturedStmt &CS = *S.getCapturedStmt(OMPD_target);
Samuel Antaobed3c462015-10-02 16:14:20 +00003684
Samuel Antaoee8fb302016-01-06 13:42:12 +00003685 llvm::Function *Fn = nullptr;
3686 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003687
Samuel Antaobed3c462015-10-02 16:14:20 +00003688 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003689 // Check for the at most one if clause associated with the target region.
3690 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3691 if (C->getNameModifier() == OMPD_unknown ||
3692 C->getNameModifier() == OMPD_target) {
3693 IfCond = C->getCondition();
3694 break;
3695 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003696 }
3697
3698 // Check if we have any device clause associated with the directive.
3699 const Expr *Device = nullptr;
3700 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3701 Device = C->getDevice();
3702 }
3703
Samuel Antaoee8fb302016-01-06 13:42:12 +00003704 // Check if we have an if clause whose conditional always evaluates to false
3705 // or if we do not have any targets specified. If so the target region is not
3706 // an offload entry point.
3707 bool IsOffloadEntry = true;
3708 if (IfCond) {
3709 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003710 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003711 IsOffloadEntry = false;
3712 }
3713 if (CGM.getLangOpts().OMPTargetTriples.empty())
3714 IsOffloadEntry = false;
3715
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003716 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003717 StringRef ParentName;
3718 // In case we have Ctors/Dtors we use the complete type variant to produce
3719 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003720 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003721 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003722 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003723 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3724 else
3725 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003726 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003727
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003728 // Emit target region as a standalone region.
3729 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3730 IsOffloadEntry, CodeGen);
3731 OMPLexicalScope Scope(CGF, S);
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003732 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3733 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003734 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003735 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003736}
3737
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003738static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3739 PrePostActionTy &Action) {
3740 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3741 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3742 CGF.EmitOMPPrivateClause(S, PrivateScope);
3743 (void)PrivateScope.Privatize();
3744
3745 Action.Enter(CGF);
3746 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3747}
3748
3749void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3750 StringRef ParentName,
3751 const OMPTargetDirective &S) {
3752 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3753 emitTargetRegion(CGF, S, Action);
3754 };
3755 llvm::Function *Fn;
3756 llvm::Constant *Addr;
3757 // Emit target region as a standalone region.
3758 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3759 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3760 assert(Fn && Addr && "Target device function emission failed.");
3761}
3762
3763void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3764 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3765 emitTargetRegion(CGF, S, Action);
3766 };
3767 emitCommonOMPTargetDirective(*this, S, CodeGen);
3768}
3769
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003770static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3771 const OMPExecutableDirective &S,
3772 OpenMPDirectiveKind InnermostKind,
3773 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003774 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
3775 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
3776 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003777
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003778 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
3779 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003780 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003781 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3782 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003783
Carlo Bertollic6872252016-04-04 15:55:02 +00003784 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3785 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003786 }
3787
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003788 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003789 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3790 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003791 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3792 CapturedVars);
3793}
3794
3795void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00003796 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003797 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003798 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003799 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3800 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003801 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003802 (void)PrivateScope.Privatize();
3803 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003804 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003805 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00003806 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003807 emitPostUpdateForReductionClause(
3808 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00003809}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003810
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003811static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
3812 const OMPTargetTeamsDirective &S) {
3813 auto *CS = S.getCapturedStmt(OMPD_teams);
3814 Action.Enter(CGF);
3815 auto &&CodeGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3816 // TODO: Add support for clauses.
3817 CGF.EmitStmt(CS->getCapturedStmt());
3818 };
3819 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
3820}
3821
3822void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
3823 CodeGenModule &CGM, StringRef ParentName,
3824 const OMPTargetTeamsDirective &S) {
3825 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3826 emitTargetTeamsRegion(CGF, Action, S);
3827 };
3828 llvm::Function *Fn;
3829 llvm::Constant *Addr;
3830 // Emit target region as a standalone region.
3831 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3832 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3833 assert(Fn && Addr && "Target device function emission failed.");
3834}
3835
3836void CodeGenFunction::EmitOMPTargetTeamsDirective(
3837 const OMPTargetTeamsDirective &S) {
3838 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3839 emitTargetTeamsRegion(CGF, Action, S);
3840 };
3841 emitCommonOMPTargetDirective(*this, S, CodeGen);
3842}
3843
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003844void CodeGenFunction::EmitOMPTeamsDistributeDirective(
3845 const OMPTeamsDistributeDirective &S) {
3846
3847 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3848 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
3849 };
3850
3851 // Emit teams region as a standalone region.
3852 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
3853 PrePostActionTy &) {
3854 OMPPrivateScope PrivateScope(CGF);
3855 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3856 (void)PrivateScope.Privatize();
3857 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
3858 CodeGenDistribute);
3859 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3860 };
3861 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
3862 emitPostUpdateForReductionClause(*this, S,
3863 [](CodeGenFunction &) { return nullptr; });
3864}
3865
Carlo Bertolli62fae152017-11-20 20:46:39 +00003866void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
3867 const OMPTeamsDistributeParallelForDirective &S) {
3868 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3869 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
3870 S.getDistInc());
3871 };
3872
3873 // Emit teams region as a standalone region.
3874 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
3875 PrePostActionTy &) {
3876 OMPPrivateScope PrivateScope(CGF);
3877 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3878 (void)PrivateScope.Privatize();
3879 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
3880 CodeGenDistribute);
3881 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3882 };
3883 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
3884 emitPostUpdateForReductionClause(*this, S,
3885 [](CodeGenFunction &) { return nullptr; });
3886}
3887
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003888void CodeGenFunction::EmitOMPCancellationPointDirective(
3889 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00003890 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
3891 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003892}
3893
Alexey Bataev80909872015-07-02 11:25:17 +00003894void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003895 const Expr *IfCond = nullptr;
3896 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3897 if (C->getNameModifier() == OMPD_unknown ||
3898 C->getNameModifier() == OMPD_cancel) {
3899 IfCond = C->getCondition();
3900 break;
3901 }
3902 }
3903 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003904 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00003905}
3906
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003907CodeGenFunction::JumpDest
3908CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00003909 if (Kind == OMPD_parallel || Kind == OMPD_task ||
3910 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003911 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003912 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00003913 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
3914 Kind == OMPD_distribute_parallel_for ||
3915 Kind == OMPD_target_parallel_for);
3916 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003917}
Michael Wong65f367f2015-07-21 13:44:28 +00003918
Samuel Antaocc10b852016-07-28 14:23:26 +00003919void CodeGenFunction::EmitOMPUseDevicePtrClause(
3920 const OMPClause &NC, OMPPrivateScope &PrivateScope,
3921 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
3922 const auto &C = cast<OMPUseDevicePtrClause>(NC);
3923 auto OrigVarIt = C.varlist_begin();
3924 auto InitIt = C.inits().begin();
3925 for (auto PvtVarIt : C.private_copies()) {
3926 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
3927 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
3928 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
3929
3930 // In order to identify the right initializer we need to match the
3931 // declaration used by the mapping logic. In some cases we may get
3932 // OMPCapturedExprDecl that refers to the original declaration.
3933 const ValueDecl *MatchingVD = OrigVD;
3934 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
3935 // OMPCapturedExprDecl are used to privative fields of the current
3936 // structure.
3937 auto *ME = cast<MemberExpr>(OED->getInit());
3938 assert(isa<CXXThisExpr>(ME->getBase()) &&
3939 "Base should be the current struct!");
3940 MatchingVD = ME->getMemberDecl();
3941 }
3942
3943 // If we don't have information about the current list item, move on to
3944 // the next one.
3945 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
3946 if (InitAddrIt == CaptureDeviceAddrMap.end())
3947 continue;
3948
3949 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
3950 // Initialize the temporary initialization variable with the address we
3951 // get from the runtime library. We have to cast the source address
3952 // because it is always a void *. References are materialized in the
3953 // privatization scope, so the initialization here disregards the fact
3954 // the original variable is a reference.
3955 QualType AddrQTy =
3956 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
3957 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
3958 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
3959 setAddrOfLocalVar(InitVD, InitAddr);
3960
3961 // Emit private declaration, it will be initialized by the value we
3962 // declaration we just added to the local declarations map.
3963 EmitDecl(*PvtVD);
3964
3965 // The initialization variables reached its purpose in the emission
3966 // ofthe previous declaration, so we don't need it anymore.
3967 LocalDeclMap.erase(InitVD);
3968
3969 // Return the address of the private variable.
3970 return GetAddrOfLocalVar(PvtVD);
3971 });
3972 assert(IsRegistered && "firstprivate var already registered as private");
3973 // Silence the warning about unused variable.
3974 (void)IsRegistered;
3975
3976 ++OrigVarIt;
3977 ++InitIt;
3978 }
3979}
3980
Michael Wong65f367f2015-07-21 13:44:28 +00003981// Generate the instructions for '#pragma omp target data' directive.
3982void CodeGenFunction::EmitOMPTargetDataDirective(
3983 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00003984 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
3985
3986 // Create a pre/post action to signal the privatization of the device pointer.
3987 // This action can be replaced by the OpenMP runtime code generation to
3988 // deactivate privatization.
3989 bool PrivatizeDevicePointers = false;
3990 class DevicePointerPrivActionTy : public PrePostActionTy {
3991 bool &PrivatizeDevicePointers;
3992
3993 public:
3994 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
3995 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
3996 void Enter(CodeGenFunction &CGF) override {
3997 PrivatizeDevicePointers = true;
3998 }
Samuel Antaodf158d52016-04-27 22:58:19 +00003999 };
Samuel Antaocc10b852016-07-28 14:23:26 +00004000 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4001
4002 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
4003 CodeGenFunction &CGF, PrePostActionTy &Action) {
4004 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4005 CGF.EmitStmt(
4006 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
4007 };
4008
4009 // Codegen that selects wheather to generate the privatization code or not.
4010 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4011 &InnermostCodeGen](CodeGenFunction &CGF,
4012 PrePostActionTy &Action) {
4013 RegionCodeGenTy RCG(InnermostCodeGen);
4014 PrivatizeDevicePointers = false;
4015
4016 // Call the pre-action to change the status of PrivatizeDevicePointers if
4017 // needed.
4018 Action.Enter(CGF);
4019
4020 if (PrivatizeDevicePointers) {
4021 OMPPrivateScope PrivateScope(CGF);
4022 // Emit all instances of the use_device_ptr clause.
4023 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4024 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4025 Info.CaptureDeviceAddrMap);
4026 (void)PrivateScope.Privatize();
4027 RCG(CGF);
4028 } else
4029 RCG(CGF);
4030 };
4031
4032 // Forward the provided action to the privatization codegen.
4033 RegionCodeGenTy PrivRCG(PrivCodeGen);
4034 PrivRCG.setAction(Action);
4035
4036 // Notwithstanding the body of the region is emitted as inlined directive,
4037 // we don't use an inline scope as changes in the references inside the
4038 // region are expected to be visible outside, so we do not privative them.
4039 OMPLexicalScope Scope(CGF, S);
4040 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4041 PrivRCG);
4042 };
4043
4044 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004045
4046 // If we don't have target devices, don't bother emitting the data mapping
4047 // code.
4048 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004049 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004050 return;
4051 }
4052
4053 // Check if we have any if clause associated with the directive.
4054 const Expr *IfCond = nullptr;
4055 if (auto *C = S.getSingleClause<OMPIfClause>())
4056 IfCond = C->getCondition();
4057
4058 // Check if we have any device clause associated with the directive.
4059 const Expr *Device = nullptr;
4060 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4061 Device = C->getDevice();
4062
Samuel Antaocc10b852016-07-28 14:23:26 +00004063 // Set the action to signal privatization of device pointers.
4064 RCG.setAction(PrivAction);
4065
4066 // Emit region code.
4067 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4068 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004069}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004070
Samuel Antaodf67fc42016-01-19 19:15:56 +00004071void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4072 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004073 // If we don't have target devices, don't bother emitting the data mapping
4074 // code.
4075 if (CGM.getLangOpts().OMPTargetTriples.empty())
4076 return;
4077
4078 // Check if we have any if clause associated with the directive.
4079 const Expr *IfCond = nullptr;
4080 if (auto *C = S.getSingleClause<OMPIfClause>())
4081 IfCond = C->getCondition();
4082
4083 // Check if we have any device clause associated with the directive.
4084 const Expr *Device = nullptr;
4085 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4086 Device = C->getDevice();
4087
Samuel Antao8d2d7302016-05-26 18:30:22 +00004088 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004089}
4090
Samuel Antao72590762016-01-19 20:04:50 +00004091void CodeGenFunction::EmitOMPTargetExitDataDirective(
4092 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004093 // If we don't have target devices, don't bother emitting the data mapping
4094 // code.
4095 if (CGM.getLangOpts().OMPTargetTriples.empty())
4096 return;
4097
4098 // Check if we have any if clause associated with the directive.
4099 const Expr *IfCond = nullptr;
4100 if (auto *C = S.getSingleClause<OMPIfClause>())
4101 IfCond = C->getCondition();
4102
4103 // Check if we have any device clause associated with the directive.
4104 const Expr *Device = nullptr;
4105 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4106 Device = C->getDevice();
4107
Samuel Antao8d2d7302016-05-26 18:30:22 +00004108 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004109}
4110
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004111static void emitTargetParallelRegion(CodeGenFunction &CGF,
4112 const OMPTargetParallelDirective &S,
4113 PrePostActionTy &Action) {
4114 // Get the captured statement associated with the 'parallel' region.
4115 auto *CS = S.getCapturedStmt(OMPD_parallel);
4116 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004117 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
4118 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4119 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4120 CGF.EmitOMPPrivateClause(S, PrivateScope);
4121 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4122 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004123 // TODO: Add support for clauses.
4124 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004125 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004126 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004127 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4128 emitEmptyBoundParameters);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004129 emitPostUpdateForReductionClause(
4130 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004131}
4132
4133void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4134 CodeGenModule &CGM, StringRef ParentName,
4135 const OMPTargetParallelDirective &S) {
4136 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4137 emitTargetParallelRegion(CGF, S, Action);
4138 };
4139 llvm::Function *Fn;
4140 llvm::Constant *Addr;
4141 // Emit target region as a standalone region.
4142 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4143 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4144 assert(Fn && Addr && "Target device function emission failed.");
4145}
4146
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004147void CodeGenFunction::EmitOMPTargetParallelDirective(
4148 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004149 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4150 emitTargetParallelRegion(CGF, S, Action);
4151 };
4152 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004153}
4154
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004155static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4156 const OMPTargetParallelForDirective &S,
4157 PrePostActionTy &Action) {
4158 Action.Enter(CGF);
4159 // Emit directive as a combined directive that consists of two implicit
4160 // directives: 'parallel' with 'for' directive.
4161 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev2139ed62017-11-16 18:20:21 +00004162 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4163 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004164 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4165 emitDispatchForLoopBounds);
4166 };
4167 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4168 emitEmptyBoundParameters);
4169}
4170
4171void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4172 CodeGenModule &CGM, StringRef ParentName,
4173 const OMPTargetParallelForDirective &S) {
4174 // Emit SPMD target parallel for region as a standalone region.
4175 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4176 emitTargetParallelForRegion(CGF, S, Action);
4177 };
4178 llvm::Function *Fn;
4179 llvm::Constant *Addr;
4180 // Emit target region as a standalone region.
4181 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4182 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4183 assert(Fn && Addr && "Target device function emission failed.");
4184}
4185
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004186void CodeGenFunction::EmitOMPTargetParallelForDirective(
4187 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004188 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4189 emitTargetParallelForRegion(CGF, S, Action);
4190 };
4191 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004192}
4193
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004194static void
4195emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4196 const OMPTargetParallelForSimdDirective &S,
4197 PrePostActionTy &Action) {
4198 Action.Enter(CGF);
4199 // Emit directive as a combined directive that consists of two implicit
4200 // directives: 'parallel' with 'for' directive.
4201 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4202 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4203 emitDispatchForLoopBounds);
4204 };
4205 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4206 emitEmptyBoundParameters);
4207}
4208
4209void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4210 CodeGenModule &CGM, StringRef ParentName,
4211 const OMPTargetParallelForSimdDirective &S) {
4212 // Emit SPMD target parallel for region as a standalone region.
4213 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4214 emitTargetParallelForSimdRegion(CGF, S, Action);
4215 };
4216 llvm::Function *Fn;
4217 llvm::Constant *Addr;
4218 // Emit target region as a standalone region.
4219 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4220 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4221 assert(Fn && Addr && "Target device function emission failed.");
4222}
4223
4224void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4225 const OMPTargetParallelForSimdDirective &S) {
4226 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4227 emitTargetParallelForSimdRegion(CGF, S, Action);
4228 };
4229 emitCommonOMPTargetDirective(*this, S, CodeGen);
4230}
4231
Alexey Bataev7292c292016-04-25 12:22:29 +00004232/// Emit a helper variable and return corresponding lvalue.
4233static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4234 const ImplicitParamDecl *PVD,
4235 CodeGenFunction::OMPPrivateScope &Privates) {
4236 auto *VDecl = cast<VarDecl>(Helper->getDecl());
4237 Privates.addPrivate(
4238 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
4239}
4240
4241void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4242 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4243 // Emit outlined function for task construct.
4244 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
4245 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
4246 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4247 const Expr *IfCond = nullptr;
4248 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4249 if (C->getNameModifier() == OMPD_unknown ||
4250 C->getNameModifier() == OMPD_taskloop) {
4251 IfCond = C->getCondition();
4252 break;
4253 }
4254 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004255
4256 OMPTaskDataTy Data;
4257 // Check if taskloop must be emitted without taskgroup.
4258 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004259 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004260 Data.Tied = true;
4261 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004262 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4263 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004264 Data.Schedule.setInt(/*IntVal=*/false);
4265 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004266 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4267 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004268 Data.Schedule.setInt(/*IntVal=*/true);
4269 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004270 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004271
4272 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4273 // if (PreCond) {
4274 // for (IV in 0..LastIteration) BODY;
4275 // <Final counter/linear vars updates>;
4276 // }
4277 //
4278
4279 // Emit: if (PreCond) - begin.
4280 // If the condition constant folds and can be elided, avoid emitting the
4281 // whole loop.
4282 bool CondConstant;
4283 llvm::BasicBlock *ContBlock = nullptr;
4284 OMPLoopScope PreInitScope(CGF, S);
4285 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4286 if (!CondConstant)
4287 return;
4288 } else {
4289 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4290 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4291 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4292 CGF.getProfileCount(&S));
4293 CGF.EmitBlock(ThenBlock);
4294 CGF.incrementProfileCounter(&S);
4295 }
4296
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004297 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4298 CGF.EmitOMPSimdInit(S);
4299
Alexey Bataev7292c292016-04-25 12:22:29 +00004300 OMPPrivateScope LoopScope(CGF);
4301 // Emit helper vars inits.
4302 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4303 auto *I = CS->getCapturedDecl()->param_begin();
4304 auto *LBP = std::next(I, LowerBound);
4305 auto *UBP = std::next(I, UpperBound);
4306 auto *STP = std::next(I, Stride);
4307 auto *LIP = std::next(I, LastIter);
4308 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4309 LoopScope);
4310 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4311 LoopScope);
4312 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4313 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4314 LoopScope);
4315 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004316 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004317 (void)LoopScope.Privatize();
4318 // Emit the loop iteration variable.
4319 const Expr *IVExpr = S.getIterationVariable();
4320 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4321 CGF.EmitVarDecl(*IVDecl);
4322 CGF.EmitIgnoredExpr(S.getInit());
4323
4324 // Emit the iterations count variable.
4325 // If it is not a variable, Sema decided to calculate iterations count on
4326 // each iteration (e.g., it is foldable into a constant).
4327 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4328 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4329 // Emit calculation of the iterations count.
4330 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4331 }
4332
4333 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4334 S.getInc(),
4335 [&S](CodeGenFunction &CGF) {
4336 CGF.EmitOMPLoopBody(S, JumpDest());
4337 CGF.EmitStopPoint(&S);
4338 },
4339 [](CodeGenFunction &) {});
4340 // Emit: if (PreCond) - end.
4341 if (ContBlock) {
4342 CGF.EmitBranch(ContBlock);
4343 CGF.EmitBlock(ContBlock, true);
4344 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004345 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4346 if (HasLastprivateClause) {
4347 CGF.EmitOMPLastprivateClauseFinal(
4348 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4349 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4350 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4351 (*LIP)->getType(), S.getLocStart())));
4352 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004353 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004354 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4355 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4356 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004357 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4358 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004359 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4360 OutlinedFn, SharedsTy,
4361 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004362 };
4363 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4364 CodeGen);
4365 };
Alexey Bataev33446032017-07-12 18:09:32 +00004366 if (Data.Nogroup)
4367 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4368 else {
4369 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4370 *this,
4371 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4372 PrePostActionTy &Action) {
4373 Action.Enter(CGF);
4374 CGF.EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4375 },
4376 S.getLocStart());
4377 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004378}
4379
Alexey Bataev49f6e782015-12-01 04:18:41 +00004380void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004381 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004382}
4383
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004384void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4385 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004386 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004387}
Samuel Antao686c70c2016-05-26 17:30:50 +00004388
4389// Generate the instructions for '#pragma omp target update' directive.
4390void CodeGenFunction::EmitOMPTargetUpdateDirective(
4391 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00004392 // If we don't have target devices, don't bother emitting the data mapping
4393 // code.
4394 if (CGM.getLangOpts().OMPTargetTriples.empty())
4395 return;
4396
4397 // Check if we have any if clause associated with the directive.
4398 const Expr *IfCond = nullptr;
4399 if (auto *C = S.getSingleClause<OMPIfClause>())
4400 IfCond = C->getCondition();
4401
4402 // Check if we have any device clause associated with the directive.
4403 const Expr *Device = nullptr;
4404 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4405 Device = C->getDevice();
4406
4407 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00004408}