blob: 873c7525830ce1a8b68a00cbdecc3dafbb43876a [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 Bataevf47c4b42017-09-26 13:47:31 +0000141LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
142 if (auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
143 if (auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
144 OrigVD = OrigVD->getCanonicalDecl();
145 bool IsCaptured =
146 LambdaCaptureFields.lookup(OrigVD) ||
147 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
148 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
149 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), IsCaptured,
150 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
151 return EmitLValue(&DRE);
152 }
153 }
154 return EmitLValue(E);
155}
156
Alexey Bataev1189bd02016-01-26 12:20:39 +0000157llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
158 auto &C = getContext();
159 llvm::Value *Size = nullptr;
160 auto SizeInChars = C.getTypeSizeInChars(Ty);
161 if (SizeInChars.isZero()) {
162 // getTypeSizeInChars() returns 0 for a VLA.
163 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
164 llvm::Value *ArraySize;
165 std::tie(ArraySize, Ty) = getVLASize(VAT);
166 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
167 }
168 SizeInChars = C.getTypeSizeInChars(Ty);
169 if (SizeInChars.isZero())
170 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
171 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
172 } else
173 Size = CGM.getSize(SizeInChars);
174 return Size;
175}
176
Alexey Bataev2377fe92015-09-10 08:12:02 +0000177void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000178 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000179 const RecordDecl *RD = S.getCapturedRecordDecl();
180 auto CurField = RD->field_begin();
181 auto CurCap = S.captures().begin();
182 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
183 E = S.capture_init_end();
184 I != E; ++I, ++CurField, ++CurCap) {
185 if (CurField->hasCapturedVLAType()) {
186 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000187 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000188 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000189 } else if (CurCap->capturesThis())
190 CapturedVars.push_back(CXXThisValue);
Samuel Antao6d004262016-06-16 18:39:34 +0000191 else if (CurCap->capturesVariableByCopy()) {
192 llvm::Value *CV =
193 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal();
194
195 // If the field is not a pointer, we need to save the actual value
196 // and load it as a void pointer.
197 if (!CurField->getType()->isAnyPointerType()) {
198 auto &Ctx = getContext();
199 auto DstAddr = CreateMemTemp(
200 Ctx.getUIntPtrType(),
201 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
202 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
203
204 auto *SrcAddrVal = EmitScalarConversion(
205 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
206 Ctx.getPointerType(CurField->getType()), SourceLocation());
207 LValue SrcLV =
208 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
209
210 // Store the value using the source type pointer.
211 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
212
213 // Load the value using the destination type pointer.
214 CV = EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
215 }
216 CapturedVars.push_back(CV);
217 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000218 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000219 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000220 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000221 }
222}
223
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000224static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
225 StringRef Name, LValue AddrLV,
226 bool isReferenceType = false) {
227 ASTContext &Ctx = CGF.getContext();
228
229 auto *CastedPtr = CGF.EmitScalarConversion(
230 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
231 Ctx.getPointerType(DstType), SourceLocation());
232 auto TmpAddr =
233 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
234 .getAddress();
235
236 // If we are dealing with references we need to return the address of the
237 // reference instead of the reference of the value.
238 if (isReferenceType) {
239 QualType RefType = Ctx.getLValueReferenceType(DstType);
240 auto *RefVal = TmpAddr.getPointer();
241 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
242 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
Akira Hatanaka642f7992016-10-18 19:05:41 +0000243 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000244 }
245
246 return TmpAddr;
247}
248
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000249static QualType getCanonicalParamType(ASTContext &C, QualType T) {
250 if (T->isLValueReferenceType()) {
251 return C.getLValueReferenceType(
252 getCanonicalParamType(C, T.getNonReferenceType()),
253 /*SpelledAsLValue=*/false);
254 }
255 if (T->isPointerType())
256 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000257 if (auto *A = T->getAsArrayTypeUnsafe()) {
258 if (auto *VLA = dyn_cast<VariableArrayType>(A))
259 return getCanonicalParamType(C, VLA->getElementType());
260 else if (!A->isVariablyModifiedType())
261 return C.getCanonicalType(T);
262 }
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000263 return C.getCanonicalParamType(T);
264}
265
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000266namespace {
267 /// Contains required data for proper outlined function codegen.
268 struct FunctionOptions {
269 /// Captured statement for which the function is generated.
270 const CapturedStmt *S = nullptr;
271 /// true if cast to/from UIntPtr is required for variables captured by
272 /// value.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000273 const bool UIntPtrCastRequired = true;
Alexey Bataeve754b182017-08-09 19:38:53 +0000274 /// true if only casted arguments must be registered as local args or VLA
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000275 /// sizes.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000276 const bool RegisterCastedArgsOnly = false;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000277 /// Name of the generated function.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000278 const StringRef FunctionName;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000279 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
280 bool RegisterCastedArgsOnly,
Alexey Bataev4aa19052017-08-08 16:45:36 +0000281 StringRef FunctionName)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000282 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
283 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
Alexey Bataev4aa19052017-08-08 16:45:36 +0000284 FunctionName(FunctionName) {}
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000285 };
286}
287
Alexey Bataeve754b182017-08-09 19:38:53 +0000288static llvm::Function *emitOutlinedFunctionPrologue(
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000289 CodeGenFunction &CGF, FunctionArgList &Args,
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000290 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000291 &LocalAddrs,
292 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
293 &VLASizes,
294 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
295 const CapturedDecl *CD = FO.S->getCapturedDecl();
296 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000297 assert(CD->hasBody() && "missing CapturedDecl body");
298
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000299 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000300 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000301 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000302 ASTContext &Ctx = CGM.getContext();
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000303 FunctionArgList TargetArgs;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000304 Args.append(CD->param_begin(),
305 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000306 TargetArgs.append(
307 CD->param_begin(),
308 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000309 auto I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000310 for (auto *FD : RD->fields()) {
311 QualType ArgType = FD->getType();
312 IdentifierInfo *II = nullptr;
313 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000314
315 // If this is a capture by copy and the type is not a pointer, the outlined
316 // function argument type should be uintptr and the value properly casted to
317 // uintptr. This is necessary given that the runtime library is only able to
318 // deal with pointers. We can pass in the same way the VLA type sizes to the
319 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000320 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000321 I->capturesVariableArrayType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000322 if (FO.UIntPtrCastRequired)
323 ArgType = Ctx.getUIntPtrType();
324 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000325
326 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000327 CapVar = I->getCapturedVar();
328 II = CapVar->getIdentifier();
329 } else if (I->capturesThis())
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000330 II = &Ctx.Idents.get("this");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000331 else {
332 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000333 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000334 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000335 if (ArgType->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000336 ArgType = getCanonicalParamType(Ctx, ArgType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000337 auto *Arg =
338 ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(), II,
339 ArgType, ImplicitParamDecl::Other);
340 Args.emplace_back(Arg);
341 // Do not cast arguments if we emit function with non-original types.
342 TargetArgs.emplace_back(
343 FO.UIntPtrCastRequired
344 ? Arg
345 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000346 ++I;
347 }
348 Args.append(
349 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
350 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000351 TargetArgs.append(
352 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
353 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000354
355 // Create the function declaration.
356 FunctionType::ExtInfo ExtInfo;
357 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000358 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000359 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
360
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000361 llvm::Function *F =
362 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
363 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000364 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
365 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000366 F->setDoesNotThrow();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000367
368 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000369 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
370 FO.S->getLocStart(), CD->getBody()->getLocStart());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000371 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000372 I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000373 for (auto *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000374 // Do not map arguments if we emit function with non-original types.
375 Address LocalAddr(Address::invalid());
376 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
377 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
378 TargetArgs[Cnt]);
379 } else {
380 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
381 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000382 // If we are capturing a pointer by copy we don't need to do anything, just
383 // use the value that we get from the arguments.
384 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000385 const VarDecl *CurVD = I->getCapturedVar();
Samuel Antao403ffd42016-07-27 22:49:49 +0000386 // If the variable is a reference we need to materialize it here.
387 if (CurVD->getType()->isReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000388 Address RefAddr = CGF.CreateMemTemp(
389 CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
390 CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
391 /*Volatile=*/false, CurVD->getType());
Samuel Antao403ffd42016-07-27 22:49:49 +0000392 LocalAddr = RefAddr;
393 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000394 if (!FO.RegisterCastedArgsOnly)
395 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000396 ++Cnt;
397 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000398 continue;
399 }
400
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000401 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
402 AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000403 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000404 if (FO.UIntPtrCastRequired) {
405 ArgLVal = CGF.MakeAddrLValue(castValueFromUintptr(CGF, FD->getType(),
406 Args[Cnt]->getName(),
407 ArgLVal),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000408 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000409 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000410 auto *ExprArg =
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000411 CGF.EmitLoadOfLValue(ArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000412 auto VAT = FD->getCapturedVLAType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000413 VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000414 } else if (I->capturesVariable()) {
415 auto *Var = I->getCapturedVar();
416 QualType VarTy = Var->getType();
417 Address ArgAddr = ArgLVal.getAddress();
418 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000419 if (ArgLVal.getType()->isLValueReferenceType()) {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +0000420 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000421 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000422 assert(ArgLVal.getType()->isPointerType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000423 ArgAddr = CGF.EmitLoadOfPointer(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000424 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
425 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000426 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000427 if (!FO.RegisterCastedArgsOnly) {
428 LocalAddrs.insert(
429 {Args[Cnt],
430 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
431 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000432 } else if (I->capturesVariableByCopy()) {
433 assert(!FD->getType()->isAnyPointerType() &&
434 "Not expecting a captured pointer.");
435 auto *Var = I->getCapturedVar();
436 QualType VarTy = Var->getType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000437 LocalAddrs.insert(
438 {Args[Cnt],
439 {Var,
440 FO.UIntPtrCastRequired
441 ? castValueFromUintptr(CGF, FD->getType(), Args[Cnt]->getName(),
442 ArgLVal, VarTy->isReferenceType())
443 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000444 } else {
445 // If 'this' is captured, load it into CXXThisValue.
446 assert(I->capturesThis());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000447 CXXThisValue = CGF.EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation())
448 .getScalarVal();
449 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000450 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000451 ++Cnt;
452 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000453 }
454
Alexey Bataeve754b182017-08-09 19:38:53 +0000455 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000456}
457
458llvm::Function *
459CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
460 assert(
461 CapturedStmtInfo &&
462 "CapturedStmtInfo should be set when generating the captured function");
463 const CapturedDecl *CD = S.getCapturedDecl();
464 // Build the argument list.
465 bool NeedWrapperFunction =
466 getDebugInfo() &&
467 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
468 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000469 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000470 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000471 SmallString<256> Buffer;
472 llvm::raw_svector_ostream Out(Buffer);
473 Out << CapturedStmtInfo->getHelperName();
474 if (NeedWrapperFunction)
475 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000476 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataeve754b182017-08-09 19:38:53 +0000477 Out.str());
478 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
479 VLASizes, CXXThisValue, FO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000480 for (const auto &LocalAddrPair : LocalAddrs) {
481 if (LocalAddrPair.second.first) {
482 setAddrOfLocalVar(LocalAddrPair.second.first,
483 LocalAddrPair.second.second);
484 }
485 }
486 for (const auto &VLASizePair : VLASizes)
487 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000488 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000489 CapturedStmtInfo->EmitBody(*this, CD->getBody());
490 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000491 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000492 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000493
Alexey Bataevefd884d2017-08-04 21:26:25 +0000494 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000495 /*RegisterCastedArgsOnly=*/true,
496 CapturedStmtInfo->getHelperName());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000497 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000498 Args.clear();
499 LocalAddrs.clear();
500 VLASizes.clear();
501 llvm::Function *WrapperF =
502 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000503 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000504 llvm::SmallVector<llvm::Value *, 4> CallArgs;
505 for (const auto *Arg : Args) {
506 llvm::Value *CallArg;
507 auto I = LocalAddrs.find(Arg);
508 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000509 LValue LV = WrapperCGF.MakeAddrLValue(
510 I->second.second,
511 I->second.first ? I->second.first->getType() : Arg->getType(),
512 AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000513 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
514 } else {
515 auto EI = VLASizes.find(Arg);
516 if (EI != VLASizes.end())
517 CallArg = EI->second.second;
518 else {
519 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000520 Arg->getType(),
521 AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000522 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
523 }
524 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000525 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000526 }
Alexey Bataev3c595a62017-08-14 15:01:03 +0000527 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getLocStart(),
528 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000529 WrapperCGF.FinishFunction();
530 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000531}
532
Alexey Bataev9959db52014-05-06 10:08:46 +0000533//===----------------------------------------------------------------------===//
534// OpenMP Directive Emission
535//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000536void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000537 Address DestAddr, Address SrcAddr, QualType OriginalType,
538 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000539 // Perform element-by-element initialization.
540 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000541
542 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000543 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000544 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
545 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
546
547 auto SrcBegin = SrcAddr.getPointer();
548 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000549 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000550 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
551 // The basic structure here is a while-do loop.
552 auto BodyBB = createBasicBlock("omp.arraycpy.body");
553 auto DoneBB = createBasicBlock("omp.arraycpy.done");
554 auto IsEmpty =
555 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
556 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000557
Alexey Bataev420d45b2015-04-14 05:11:24 +0000558 // Enter the loop body, making that address the current address.
559 auto EntryBB = Builder.GetInsertBlock();
560 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000561
562 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
563
564 llvm::PHINode *SrcElementPHI =
565 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
566 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
567 Address SrcElementCurrent =
568 Address(SrcElementPHI,
569 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
570
571 llvm::PHINode *DestElementPHI =
572 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
573 DestElementPHI->addIncoming(DestBegin, EntryBB);
574 Address DestElementCurrent =
575 Address(DestElementPHI,
576 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000577
Alexey Bataev420d45b2015-04-14 05:11:24 +0000578 // Emit copy.
579 CopyGen(DestElementCurrent, SrcElementCurrent);
580
581 // Shift the address forward by one element.
582 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000583 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000584 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000585 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000586 // Check whether we've reached the end.
587 auto Done =
588 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
589 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000590 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
591 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000592
593 // Done.
594 EmitBlock(DoneBB, /*IsFinished=*/true);
595}
596
John McCall7f416cc2015-09-08 08:05:57 +0000597void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
598 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000599 const VarDecl *SrcVD, const Expr *Copy) {
600 if (OriginalType->isArrayType()) {
601 auto *BO = dyn_cast<BinaryOperator>(Copy);
602 if (BO && BO->getOpcode() == BO_Assign) {
603 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000604 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000605 } else {
606 // For arrays with complex element types perform element by element
607 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000608 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000609 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000610 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000611 // Working with the single array element, so have to remap
612 // destination and source variables to corresponding array
613 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000614 CodeGenFunction::OMPPrivateScope Remap(*this);
615 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000616 return DestElement;
617 });
618 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000619 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000620 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000621 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000622 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000623 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000624 } else {
625 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000626 CodeGenFunction::OMPPrivateScope Remap(*this);
627 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
628 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000629 (void)Remap.Privatize();
630 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000631 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000632 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000633}
634
Alexey Bataev69c62a92015-04-15 04:52:20 +0000635bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
636 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000637 if (!HaveInsertPoint())
638 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000639 bool FirstprivateIsLastprivate = false;
640 llvm::DenseSet<const VarDecl *> Lastprivates;
641 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
642 for (const auto *D : C->varlists())
643 Lastprivates.insert(
644 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
645 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000646 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000647 CGCapturedStmtInfo CapturesInfo(cast<CapturedStmt>(*D.getAssociatedStmt()));
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000648 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000649 auto IRef = C->varlist_begin();
650 auto InitsRef = C->inits().begin();
651 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000652 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000653 bool ThisFirstprivateIsLastprivate =
654 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000655 auto *CapFD = CapturesInfo.lookup(OrigVD);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000656 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9afe5752016-05-24 07:40:12 +0000657 if (!ThisFirstprivateIsLastprivate && FD && (FD == CapFD) &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000658 !FD->getType()->isReferenceType()) {
659 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
660 ++IRef;
661 ++InitsRef;
662 continue;
663 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000664 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000665 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000666 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000667 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
668 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
669 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000670 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
671 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
672 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000673 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000674 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000675 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000676 // Emit VarDecl with copy init for arrays.
677 // Get the address of the original variable captured in current
678 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000679 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000680 auto Emission = EmitAutoVarAlloca(*VD);
681 auto *Init = VD->getInit();
682 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
683 // Perform simple memcpy.
684 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000685 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000686 } else {
687 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000688 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000689 [this, VDInit, Init](Address DestElement,
690 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000691 // Clean up any temporaries needed by the initialization.
692 RunCleanupsScope InitScope(*this);
693 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000694 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000695 EmitAnyExprToMem(Init, DestElement,
696 Init->getType().getQualifiers(),
697 /*IsInitializer*/ false);
698 LocalDeclMap.erase(VDInit);
699 });
700 }
701 EmitAutoVarCleanups(Emission);
702 return Emission.getAllocatedAddress();
703 });
704 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000705 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000706 // Emit private VarDecl with copy init.
707 // Remap temp VDInit variable to the address of the original
708 // variable
709 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000710 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000711 EmitDecl(*VD);
712 LocalDeclMap.erase(VDInit);
713 return GetAddrOfLocalVar(VD);
714 });
715 }
716 assert(IsRegistered &&
717 "firstprivate var already registered as private");
718 // Silence the warning about unused variable.
719 (void)IsRegistered;
720 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000721 ++IRef;
722 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000723 }
724 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000725 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000726}
727
Alexey Bataev03b340a2014-10-21 03:16:40 +0000728void CodeGenFunction::EmitOMPPrivateClause(
729 const OMPExecutableDirective &D,
730 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000731 if (!HaveInsertPoint())
732 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000733 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000734 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000735 auto IRef = C->varlist_begin();
736 for (auto IInit : C->private_copies()) {
737 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000738 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
739 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
740 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000741 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000742 // Emit private VarDecl with copy init.
743 EmitDecl(*VD);
744 return GetAddrOfLocalVar(VD);
745 });
746 assert(IsRegistered && "private var already registered as private");
747 // Silence the warning about unused variable.
748 (void)IsRegistered;
749 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000750 ++IRef;
751 }
752 }
753}
754
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000755bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000756 if (!HaveInsertPoint())
757 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000758 // threadprivate_var1 = master_threadprivate_var1;
759 // operator=(threadprivate_var2, master_threadprivate_var2);
760 // ...
761 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000762 llvm::DenseSet<const VarDecl *> CopiedVars;
763 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000764 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000765 auto IRef = C->varlist_begin();
766 auto ISrcRef = C->source_exprs().begin();
767 auto IDestRef = C->destination_exprs().begin();
768 for (auto *AssignOp : C->assignment_ops()) {
769 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000770 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000771 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000772 // Get the address of the master variable. If we are emitting code with
773 // TLS support, the address is passed from the master as field in the
774 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000775 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000776 if (getLangOpts().OpenMPUseTLS &&
777 getContext().getTargetInfo().isTLSSupported()) {
778 assert(CapturedStmtInfo->lookup(VD) &&
779 "Copyin threadprivates should have been captured!");
780 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
781 VK_LValue, (*IRef)->getExprLoc());
782 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000783 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000784 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000785 MasterAddr =
786 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
787 : CGM.GetAddrOfGlobal(VD),
788 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000789 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000790 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000791 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000792 if (CopiedVars.size() == 1) {
793 // At first check if current thread is a master thread. If it is, no
794 // need to copy data.
795 CopyBegin = createBasicBlock("copyin.not.master");
796 CopyEnd = createBasicBlock("copyin.not.master.end");
797 Builder.CreateCondBr(
798 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000799 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
800 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000801 CopyBegin, CopyEnd);
802 EmitBlock(CopyBegin);
803 }
804 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
805 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000806 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000807 }
808 ++IRef;
809 ++ISrcRef;
810 ++IDestRef;
811 }
812 }
813 if (CopyEnd) {
814 // Exit out of copying procedure for non-master thread.
815 EmitBlock(CopyEnd, /*IsFinished=*/true);
816 return true;
817 }
818 return false;
819}
820
Alexey Bataev38e89532015-04-16 04:54:05 +0000821bool CodeGenFunction::EmitOMPLastprivateClauseInit(
822 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000823 if (!HaveInsertPoint())
824 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000825 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000826 llvm::DenseSet<const VarDecl *> SIMDLCVs;
827 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
828 auto *LoopDirective = cast<OMPLoopDirective>(&D);
829 for (auto *C : LoopDirective->counters()) {
830 SIMDLCVs.insert(
831 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
832 }
833 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000834 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000835 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000836 HasAtLeastOneLastprivate = true;
Alexey Bataevf93095a2016-05-05 08:46:22 +0000837 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()))
838 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000839 auto IRef = C->varlist_begin();
840 auto IDestRef = C->destination_exprs().begin();
841 for (auto *IInit : C->private_copies()) {
842 // Keep the address of the original variable for future update at the end
843 // of the loop.
844 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000845 // Taskloops do not require additional initialization, it is done in
846 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000847 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
848 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000849 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000850 DeclRefExpr DRE(
851 const_cast<VarDecl *>(OrigVD),
852 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
853 OrigVD) != nullptr,
854 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
855 return EmitLValue(&DRE).getAddress();
856 });
857 // Check if the variable is also a firstprivate: in this case IInit is
858 // not generated. Initialization of this variable will happen in codegen
859 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000860 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000861 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000862 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
863 // Emit private VarDecl with copy init.
864 EmitDecl(*VD);
865 return GetAddrOfLocalVar(VD);
866 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000867 assert(IsRegistered &&
868 "lastprivate var already registered as private");
869 (void)IsRegistered;
870 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000871 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000872 ++IRef;
873 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000874 }
875 }
876 return HasAtLeastOneLastprivate;
877}
878
879void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000880 const OMPExecutableDirective &D, bool NoFinals,
881 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000882 if (!HaveInsertPoint())
883 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000884 // Emit following code:
885 // if (<IsLastIterCond>) {
886 // orig_var1 = private_orig_var1;
887 // ...
888 // orig_varn = private_orig_varn;
889 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000890 llvm::BasicBlock *ThenBB = nullptr;
891 llvm::BasicBlock *DoneBB = nullptr;
892 if (IsLastIterCond) {
893 ThenBB = createBasicBlock(".omp.lastprivate.then");
894 DoneBB = createBasicBlock(".omp.lastprivate.done");
895 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
896 EmitBlock(ThenBB);
897 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000898 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
899 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000900 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000901 auto IC = LoopDirective->counters().begin();
902 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000903 auto *D =
904 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
905 if (NoFinals)
906 AlreadyEmittedVars.insert(D);
907 else
908 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000909 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000910 }
911 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000912 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
913 auto IRef = C->varlist_begin();
914 auto ISrcRef = C->source_exprs().begin();
915 auto IDestRef = C->destination_exprs().begin();
916 for (auto *AssignOp : C->assignment_ops()) {
917 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
918 QualType Type = PrivateVD->getType();
919 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
920 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
921 // If lastprivate variable is a loop control variable for loop-based
922 // directive, update its value before copyin back to original
923 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000924 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
925 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000926 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
927 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
928 // Get the address of the original variable.
929 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
930 // Get the address of the private variable.
931 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
932 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
933 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000934 Address(Builder.CreateLoad(PrivateAddr),
935 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000936 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000937 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000938 ++IRef;
939 ++ISrcRef;
940 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000941 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000942 if (auto *PostUpdate = C->getPostUpdateExpr())
943 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000944 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000945 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000946 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000947}
948
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000949void CodeGenFunction::EmitOMPReductionClauseInit(
950 const OMPExecutableDirective &D,
951 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000952 if (!HaveInsertPoint())
953 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000954 SmallVector<const Expr *, 4> Shareds;
955 SmallVector<const Expr *, 4> Privates;
956 SmallVector<const Expr *, 4> ReductionOps;
957 SmallVector<const Expr *, 4> LHSs;
958 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000959 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000960 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000961 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000962 auto ILHS = C->lhs_exprs().begin();
963 auto IRHS = C->rhs_exprs().begin();
964 for (const auto *Ref : C->varlists()) {
965 Shareds.emplace_back(Ref);
966 Privates.emplace_back(*IPriv);
967 ReductionOps.emplace_back(*IRed);
968 LHSs.emplace_back(*ILHS);
969 RHSs.emplace_back(*IRHS);
970 std::advance(IPriv, 1);
971 std::advance(IRed, 1);
972 std::advance(ILHS, 1);
973 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000974 }
975 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000976 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
977 unsigned Count = 0;
978 auto ILHS = LHSs.begin();
979 auto IRHS = RHSs.begin();
980 auto IPriv = Privates.begin();
981 for (const auto *IRef : Shareds) {
982 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
983 // Emit private VarDecl with reduction init.
984 RedCG.emitSharedLValue(*this, Count);
985 RedCG.emitAggregateType(*this, Count);
986 auto Emission = EmitAutoVarAlloca(*PrivateVD);
987 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
988 RedCG.getSharedLValue(Count),
989 [&Emission](CodeGenFunction &CGF) {
990 CGF.EmitAutoVarInit(Emission);
991 return true;
992 });
993 EmitAutoVarCleanups(Emission);
994 Address BaseAddr = RedCG.adjustPrivateAddress(
995 *this, Count, Emission.getAllocatedAddress());
996 bool IsRegistered = PrivateScope.addPrivate(
997 RedCG.getBaseDecl(Count), [BaseAddr]() -> Address { return BaseAddr; });
998 assert(IsRegistered && "private var already registered as private");
999 // Silence the warning about unused variable.
1000 (void)IsRegistered;
1001
1002 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1003 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001004 QualType Type = PrivateVD->getType();
1005 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1006 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001007 // Store the address of the original variable associated with the LHS
1008 // implicit variable.
1009 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1010 return RedCG.getSharedLValue(Count).getAddress();
1011 });
1012 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1013 return GetAddrOfLocalVar(PrivateVD);
1014 });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001015 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1016 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001017 // Store the address of the original variable associated with the LHS
1018 // implicit variable.
1019 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1020 return RedCG.getSharedLValue(Count).getAddress();
1021 });
1022 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1023 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1024 ConvertTypeForMem(RHSVD->getType()),
1025 "rhs.begin");
1026 });
1027 } else {
1028 QualType Type = PrivateVD->getType();
1029 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1030 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1031 // Store the address of the original variable associated with the LHS
1032 // implicit variable.
1033 if (IsArray) {
1034 OriginalAddr = Builder.CreateElementBitCast(
1035 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1036 }
1037 PrivateScope.addPrivate(
1038 LHSVD, [OriginalAddr]() -> Address { return OriginalAddr; });
1039 PrivateScope.addPrivate(
1040 RHSVD, [this, PrivateVD, RHSVD, IsArray]() -> Address {
1041 return IsArray
1042 ? Builder.CreateElementBitCast(
1043 GetAddrOfLocalVar(PrivateVD),
1044 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1045 : GetAddrOfLocalVar(PrivateVD);
1046 });
1047 }
1048 ++ILHS;
1049 ++IRHS;
1050 ++IPriv;
1051 ++Count;
1052 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001053}
1054
1055void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001056 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001057 if (!HaveInsertPoint())
1058 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001059 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001060 llvm::SmallVector<const Expr *, 8> LHSExprs;
1061 llvm::SmallVector<const Expr *, 8> RHSExprs;
1062 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001063 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001064 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001065 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001066 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001067 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1068 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1069 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1070 }
1071 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001072 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1073 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1074 D.getDirectiveKind() == OMPD_simd;
1075 bool SimpleReduction = D.getDirectiveKind() == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001076 // Emit nowait reduction if nowait clause is present or directive is a
1077 // parallel directive (it always has implicit barrier).
1078 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001079 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001080 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001081 }
1082}
1083
Alexey Bataev61205072016-03-02 04:57:40 +00001084static void emitPostUpdateForReductionClause(
1085 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1086 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1087 if (!CGF.HaveInsertPoint())
1088 return;
1089 llvm::BasicBlock *DoneBB = nullptr;
1090 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1091 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1092 if (!DoneBB) {
1093 if (auto *Cond = CondGen(CGF)) {
1094 // If the first post-update expression is found, emit conditional
1095 // block if it was requested.
1096 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1097 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1098 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1099 CGF.EmitBlock(ThenBB);
1100 }
1101 }
1102 CGF.EmitIgnoredExpr(PostUpdate);
1103 }
1104 }
1105 if (DoneBB)
1106 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1107}
1108
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001109namespace {
1110/// Codegen lambda for appending distribute lower and upper bounds to outlined
1111/// parallel function. This is necessary for combined constructs such as
1112/// 'distribute parallel for'
1113typedef llvm::function_ref<void(CodeGenFunction &,
1114 const OMPExecutableDirective &,
1115 llvm::SmallVectorImpl<llvm::Value *> &)>
1116 CodeGenBoundParametersTy;
1117} // anonymous namespace
1118
1119static void emitCommonOMPParallelDirective(
1120 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1121 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1122 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001123 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1124 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1125 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001126 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001127 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001128 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1129 /*IgnoreResultAssign*/ true);
1130 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1131 CGF, NumThreads, NumThreadsClause->getLocStart());
1132 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001133 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001134 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001135 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1136 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1137 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001138 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001139 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1140 if (C->getNameModifier() == OMPD_unknown ||
1141 C->getNameModifier() == OMPD_parallel) {
1142 IfCond = C->getCondition();
1143 break;
1144 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001145 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001146
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001147 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001148 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001149 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1150 // lower and upper bounds with the pragma 'for' chunking mechanism.
1151 // The following lambda takes care of appending the lower and upper bound
1152 // parameters when necessary
1153 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001154 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001155 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001156 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001157}
1158
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001159static void emitEmptyBoundParameters(CodeGenFunction &,
1160 const OMPExecutableDirective &,
1161 llvm::SmallVectorImpl<llvm::Value *> &) {}
1162
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001163void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001164 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001165 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001166 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001167 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001168 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1169 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001170 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001171 // propagation master's thread values of threadprivate variables to local
1172 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001173 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1174 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1175 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001176 }
1177 CGF.EmitOMPPrivateClause(S, PrivateScope);
1178 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1179 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001180 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001181 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001182 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001183 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1184 emitEmptyBoundParameters);
Alexey Bataev61205072016-03-02 04:57:40 +00001185 emitPostUpdateForReductionClause(
1186 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001187}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001188
Alexey Bataev0f34da12015-07-02 04:17:07 +00001189void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1190 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001191 RunCleanupsScope BodyScope(*this);
1192 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001193 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001194 EmitIgnoredExpr(I);
1195 }
Alexander Musman3276a272015-03-21 10:12:56 +00001196 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001197 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001198 for (auto *U : C->updates())
Alexander Musman3276a272015-03-21 10:12:56 +00001199 EmitIgnoredExpr(U);
Alexander Musman3276a272015-03-21 10:12:56 +00001200 }
1201
Alexander Musmana5f070a2014-10-01 06:03:56 +00001202 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001203 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001204 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001205 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001206 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001207 // The end (updates/cleanups).
1208 EmitBlock(Continue.getBlock());
1209 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001210}
1211
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001212void CodeGenFunction::EmitOMPInnerLoop(
1213 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1214 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001215 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1216 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001217 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001218
1219 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001220 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001221 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001222 const SourceRange &R = S.getSourceRange();
1223 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1224 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001225
1226 // If there are any cleanups between here and the loop-exit scope,
1227 // create a block to stage a loop exit along.
1228 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001229 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001230 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001231
Alexander Musmand196ef22014-10-07 08:57:09 +00001232 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001233
Alexey Bataev2df54a02015-03-12 08:53:29 +00001234 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001235 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001236 if (ExitBlock != LoopExit.getBlock()) {
1237 EmitBlock(ExitBlock);
1238 EmitBranchThroughCleanup(LoopExit);
1239 }
1240
1241 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001242 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001243
1244 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001245 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001246 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1247
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001248 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001249
1250 // Emit "IV = IV + 1" and a back-edge to the condition block.
1251 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001252 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001253 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001254 BreakContinueStack.pop_back();
1255 EmitBranch(CondBlock);
1256 LoopStack.pop();
1257 // Emit the fall-through block.
1258 EmitBlock(LoopExit.getBlock());
1259}
1260
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001261bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001262 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001263 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001264 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001265 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001266 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001267 for (auto *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001268 HasLinears = true;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001269 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001270 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1271 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1272 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1273 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1274 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1275 VD->getInit()->getType(), VK_LValue,
1276 VD->getInit()->getExprLoc());
1277 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1278 VD->getType()),
1279 /*capturedByInit=*/false);
1280 EmitAutoVarCleanups(Emission);
1281 } else
1282 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001283 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001284 // Emit the linear steps for the linear clauses.
1285 // If a step is not constant, it is pre-calculated before the loop.
1286 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1287 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001288 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001289 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001290 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001291 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001292 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001293 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001294}
1295
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001296void CodeGenFunction::EmitOMPLinearClauseFinal(
1297 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001298 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001299 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001300 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001301 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001302 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001303 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001304 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001305 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001306 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001307 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001308 // If the first post-update expression is found, emit conditional
1309 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001310 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1311 DoneBB = createBasicBlock(".omp.linear.pu.done");
1312 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1313 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001314 }
1315 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001316 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1317 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001318 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001319 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001320 Address OrigAddr = EmitLValue(&DRE).getAddress();
1321 CodeGenFunction::OMPPrivateScope VarScope(*this);
1322 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001323 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001324 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001325 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001326 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001327 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001328 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001329 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001330 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001331 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001332}
1333
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001334static void emitAlignedClause(CodeGenFunction &CGF,
1335 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001336 if (!CGF.HaveInsertPoint())
1337 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001338 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001339 unsigned ClauseAlignment = 0;
1340 if (auto AlignmentExpr = Clause->getAlignment()) {
1341 auto AlignmentCI =
1342 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1343 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001344 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001345 for (auto E : Clause->varlists()) {
1346 unsigned Alignment = ClauseAlignment;
1347 if (Alignment == 0) {
1348 // OpenMP [2.8.1, Description]
1349 // If no optional parameter is specified, implementation-defined default
1350 // alignments for SIMD instructions on the target platforms are assumed.
1351 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001352 CGF.getContext()
1353 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1354 E->getType()->getPointeeType()))
1355 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001356 }
1357 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1358 "alignment is not power of 2");
1359 if (Alignment != 0) {
1360 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1361 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1362 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001363 }
1364 }
1365}
1366
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001367void CodeGenFunction::EmitOMPPrivateLoopCounters(
1368 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1369 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001370 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001371 auto I = S.private_counters().begin();
1372 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001373 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1374 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001375 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001376 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001377 if (!LocalDeclMap.count(PrivateVD)) {
1378 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1379 EmitAutoVarCleanups(VarEmission);
1380 }
1381 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1382 /*RefersToEnclosingVariableOrCapture=*/false,
1383 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1384 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001385 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001386 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1387 VD->hasGlobalStorage()) {
1388 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1389 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1390 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1391 E->getType(), VK_LValue, E->getExprLoc());
1392 return EmitLValue(&DRE).getAddress();
1393 });
1394 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001395 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001396 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001397}
1398
Alexey Bataev62dbb972015-04-22 11:59:37 +00001399static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1400 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1401 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001402 if (!CGF.HaveInsertPoint())
1403 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001404 {
1405 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001406 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001407 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001408 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001409 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001410 CGF.EmitIgnoredExpr(I);
1411 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001412 }
1413 // Check that loop is executed at least one time.
1414 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1415}
1416
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001417void CodeGenFunction::EmitOMPLinearClause(
1418 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1419 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001420 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001421 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1422 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1423 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1424 for (auto *C : LoopDirective->counters()) {
1425 SIMDLCVs.insert(
1426 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1427 }
1428 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001429 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001430 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001431 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001432 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1433 auto *PrivateVD =
1434 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001435 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1436 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1437 // Emit private VarDecl with copy init.
1438 EmitVarDecl(*PrivateVD);
1439 return GetAddrOfLocalVar(PrivateVD);
1440 });
1441 assert(IsRegistered && "linear var already registered as private");
1442 // Silence the warning about unused variable.
1443 (void)IsRegistered;
1444 } else
1445 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001446 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001447 }
1448 }
1449}
1450
Alexey Bataev45bfad52015-08-21 12:19:04 +00001451static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001452 const OMPExecutableDirective &D,
1453 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001454 if (!CGF.HaveInsertPoint())
1455 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001456 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001457 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1458 /*ignoreResult=*/true);
1459 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1460 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1461 // In presence of finite 'safelen', it may be unsafe to mark all
1462 // the memory instructions parallel, because loop-carried
1463 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001464 if (!IsMonotonic)
1465 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001466 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001467 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1468 /*ignoreResult=*/true);
1469 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001470 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001471 // In presence of finite 'safelen', it may be unsafe to mark all
1472 // the memory instructions parallel, because loop-carried
1473 // dependences of 'safelen' iterations are possible.
1474 CGF.LoopStack.setParallel(false);
1475 }
1476}
1477
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001478void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1479 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001480 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001481 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001482 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001483 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001484}
1485
Alexey Bataevef549a82016-03-09 09:49:09 +00001486void CodeGenFunction::EmitOMPSimdFinal(
1487 const OMPLoopDirective &D,
1488 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001489 if (!HaveInsertPoint())
1490 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001491 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001492 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001493 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001494 for (auto F : D.finals()) {
1495 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001496 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1497 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1498 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1499 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001500 if (!DoneBB) {
1501 if (auto *Cond = CondGen(*this)) {
1502 // If the first post-update expression is found, emit conditional
1503 // block if it was requested.
1504 auto *ThenBB = createBasicBlock(".omp.final.then");
1505 DoneBB = createBasicBlock(".omp.final.done");
1506 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1507 EmitBlock(ThenBB);
1508 }
1509 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001510 Address OrigAddr = Address::invalid();
1511 if (CED)
1512 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1513 else {
1514 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1515 /*RefersToEnclosingVariableOrCapture=*/false,
1516 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1517 OrigAddr = EmitLValue(&DRE).getAddress();
1518 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001519 OMPPrivateScope VarScope(*this);
1520 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001521 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001522 (void)VarScope.Privatize();
1523 EmitIgnoredExpr(F);
1524 }
1525 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001526 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001527 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001528 if (DoneBB)
1529 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001530}
1531
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001532static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1533 const OMPLoopDirective &S,
1534 CodeGenFunction::JumpDest LoopExit) {
1535 CGF.EmitOMPLoopBody(S, LoopExit);
1536 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001537}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001538
Alexander Musman515ad8c2014-05-22 08:54:05 +00001539void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001540 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00001541 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001542 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001543 // for (IV in 0..LastIteration) BODY;
1544 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001545 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001546 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001547
Alexey Bataev62dbb972015-04-22 11:59:37 +00001548 // Emit: if (PreCond) - begin.
1549 // If the condition constant folds and can be elided, avoid emitting the
1550 // whole loop.
1551 bool CondConstant;
1552 llvm::BasicBlock *ContBlock = nullptr;
1553 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1554 if (!CondConstant)
1555 return;
1556 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001557 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1558 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001559 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1560 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001561 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001562 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001563 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001564
1565 // Emit the loop iteration variable.
1566 const Expr *IVExpr = S.getIterationVariable();
1567 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1568 CGF.EmitVarDecl(*IVDecl);
1569 CGF.EmitIgnoredExpr(S.getInit());
1570
1571 // Emit the iterations count variable.
1572 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001573 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001574 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1575 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1576 // Emit calculation of the iterations count.
1577 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001578 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001579
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001580 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001581
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001582 emitAlignedClause(CGF, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001583 (void)CGF.EmitOMPLinearClauseInit(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001584 {
1585 OMPPrivateScope LoopScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001586 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1587 CGF.EmitOMPLinearClause(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001588 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001589 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001590 bool HasLastprivateClause =
1591 CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001592 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001593 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1594 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001595 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001596 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001597 CGF.EmitStopPoint(&S);
1598 },
1599 [](CodeGenFunction &) {});
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001600 CGF.EmitOMPSimdFinal(
1601 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001602 // Emit final copy of the lastprivate variables at the end of loops.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001603 if (HasLastprivateClause)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001604 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001605 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
Alexey Bataev61205072016-03-02 04:57:40 +00001606 emitPostUpdateForReductionClause(
1607 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001608 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001609 CGF.EmitOMPLinearClauseFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001610 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001611 // Emit: if (PreCond) - end.
1612 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001613 CGF.EmitBranch(ContBlock);
1614 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001615 }
1616 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00001617 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001618 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001619}
1620
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001621void CodeGenFunction::EmitOMPOuterLoop(
1622 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1623 CodeGenFunction::OMPPrivateScope &LoopScope,
1624 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1625 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1626 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001627 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001628
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001629 const Expr *IVExpr = S.getIterationVariable();
1630 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1631 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1632
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001633 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1634
1635 // Start the loop with a block that tests the condition.
1636 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1637 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001638 const SourceRange &R = S.getSourceRange();
1639 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1640 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001641
1642 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001643 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001644 // UB = min(UB, GlobalUB) or
1645 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1646 // 'distribute parallel for')
1647 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001648 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001649 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001650 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001651 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001652 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001653 BoolCondVal =
1654 RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1655 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001656 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001657
1658 // If there are any cleanups between here and the loop-exit scope,
1659 // create a block to stage a loop exit along.
1660 auto ExitBlock = LoopExit.getBlock();
1661 if (LoopScope.requiresCleanups())
1662 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1663
1664 auto LoopBody = createBasicBlock("omp.dispatch.body");
1665 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1666 if (ExitBlock != LoopExit.getBlock()) {
1667 EmitBlock(ExitBlock);
1668 EmitBranchThroughCleanup(LoopExit);
1669 }
1670 EmitBlock(LoopBody);
1671
Alexander Musman92bdaab2015-03-12 13:37:50 +00001672 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1673 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001674 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001675 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001676
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001677 // Create a block for the increment.
1678 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1679 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1680
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001681 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1682 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001683 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1684 LoopStack.setParallel(!IsMonotonic);
1685 else
1686 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001687
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001688 SourceLocation Loc = S.getLocStart();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001689
1690 // when 'distribute' is not combined with a 'for':
1691 // while (idx <= UB) { BODY; ++idx; }
1692 // when 'distribute' is combined with a 'for'
1693 // (e.g. 'distribute parallel for')
1694 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1695 EmitOMPInnerLoop(
1696 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1697 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1698 CodeGenLoop(CGF, S, LoopExit);
1699 },
1700 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1701 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1702 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001703
1704 EmitBlock(Continue.getBlock());
1705 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001706 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001707 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001708 EmitIgnoredExpr(LoopArgs.NextLB);
1709 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001710 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001711
1712 EmitBranch(CondBlock);
1713 LoopStack.pop();
1714 // Emit the fall-through block.
1715 EmitBlock(LoopExit.getBlock());
1716
1717 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001718 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1719 if (!DynamicOrOrdered)
Alexey Bataevf43f7142017-09-06 16:17:35 +00001720 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
1721 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00001722 };
1723 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001724}
1725
1726void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001727 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001728 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001729 const OMPLoopArguments &LoopArgs,
1730 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001731 auto &RT = CGM.getOpenMPRuntime();
1732
1733 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001734 const bool DynamicOrOrdered =
1735 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001736
1737 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001738 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001739 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001740 "static non-chunked schedule does not need outer loop");
1741
1742 // Emit outer loop.
1743 //
1744 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1745 // When schedule(dynamic,chunk_size) is specified, the iterations are
1746 // distributed to threads in the team in chunks as the threads request them.
1747 // Each thread executes a chunk of iterations, then requests another chunk,
1748 // until no chunks remain to be distributed. Each chunk contains chunk_size
1749 // iterations, except for the last chunk to be distributed, which may have
1750 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1751 //
1752 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1753 // to threads in the team in chunks as the executing threads request them.
1754 // Each thread executes a chunk of iterations, then requests another chunk,
1755 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1756 // each chunk is proportional to the number of unassigned iterations divided
1757 // by the number of threads in the team, decreasing to 1. For a chunk_size
1758 // with value k (greater than 1), the size of each chunk is determined in the
1759 // same way, with the restriction that the chunks do not contain fewer than k
1760 // iterations (except for the last chunk to be assigned, which may have fewer
1761 // than k iterations).
1762 //
1763 // When schedule(auto) is specified, the decision regarding scheduling is
1764 // delegated to the compiler and/or runtime system. The programmer gives the
1765 // implementation the freedom to choose any possible mapping of iterations to
1766 // threads in the team.
1767 //
1768 // When schedule(runtime) is specified, the decision regarding scheduling is
1769 // deferred until run time, and the schedule and chunk size are taken from the
1770 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1771 // implementation defined
1772 //
1773 // while(__kmpc_dispatch_next(&LB, &UB)) {
1774 // idx = LB;
1775 // while (idx <= UB) { BODY; ++idx;
1776 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1777 // } // inner loop
1778 // }
1779 //
1780 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1781 // When schedule(static, chunk_size) is specified, iterations are divided into
1782 // chunks of size chunk_size, and the chunks are assigned to the threads in
1783 // the team in a round-robin fashion in the order of the thread number.
1784 //
1785 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1786 // while (idx <= UB) { BODY; ++idx; } // inner loop
1787 // LB = LB + ST;
1788 // UB = UB + ST;
1789 // }
1790 //
1791
1792 const Expr *IVExpr = S.getIterationVariable();
1793 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1794 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1795
1796 if (DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001797 auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1798 llvm::Value *LBVal = DispatchBounds.first;
1799 llvm::Value *UBVal = DispatchBounds.second;
1800 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1801 LoopArgs.Chunk};
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001802 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001803 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001804 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001805 CGOpenMPRuntime::StaticRTInput StaticInit(
1806 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1807 LoopArgs.ST, LoopArgs.Chunk);
1808 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
1809 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001810 }
1811
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001812 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1813 const unsigned IVSize,
1814 const bool IVSigned) {
1815 if (Ordered) {
1816 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1817 IVSigned);
1818 }
1819 };
1820
1821 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1822 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1823 OuterLoopArgs.IncExpr = S.getInc();
1824 OuterLoopArgs.Init = S.getInit();
1825 OuterLoopArgs.Cond = S.getCond();
1826 OuterLoopArgs.NextLB = S.getNextLowerBound();
1827 OuterLoopArgs.NextUB = S.getNextUpperBound();
1828 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1829 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001830}
1831
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001832static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1833 const unsigned IVSize, const bool IVSigned) {}
1834
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001835void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001836 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1837 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1838 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001839
1840 auto &RT = CGM.getOpenMPRuntime();
1841
1842 // Emit outer loop.
1843 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1844 // dynamic
1845 //
1846
1847 const Expr *IVExpr = S.getIterationVariable();
1848 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1849 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1850
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001851 CGOpenMPRuntime::StaticRTInput StaticInit(
1852 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
1853 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
1854 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001855
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001856 // for combined 'distribute' and 'for' the increment expression of distribute
1857 // is store in DistInc. For 'distribute' alone, it is in Inc.
1858 Expr *IncExpr;
1859 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1860 IncExpr = S.getDistInc();
1861 else
1862 IncExpr = S.getInc();
1863
1864 // this routine is shared by 'omp distribute parallel for' and
1865 // 'omp distribute': select the right EUB expression depending on the
1866 // directive
1867 OMPLoopArguments OuterLoopArgs;
1868 OuterLoopArgs.LB = LoopArgs.LB;
1869 OuterLoopArgs.UB = LoopArgs.UB;
1870 OuterLoopArgs.ST = LoopArgs.ST;
1871 OuterLoopArgs.IL = LoopArgs.IL;
1872 OuterLoopArgs.Chunk = LoopArgs.Chunk;
1873 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1874 ? S.getCombinedEnsureUpperBound()
1875 : S.getEnsureUpperBound();
1876 OuterLoopArgs.IncExpr = IncExpr;
1877 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1878 ? S.getCombinedInit()
1879 : S.getInit();
1880 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1881 ? S.getCombinedCond()
1882 : S.getCond();
1883 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1884 ? S.getCombinedNextLowerBound()
1885 : S.getNextLowerBound();
1886 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1887 ? S.getCombinedNextUpperBound()
1888 : S.getNextUpperBound();
1889
1890 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
1891 LoopScope, OuterLoopArgs, CodeGenLoopContent,
1892 emitEmptyOrdered);
1893}
1894
1895/// Emit a helper variable and return corresponding lvalue.
1896static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1897 const DeclRefExpr *Helper) {
1898 auto VDecl = cast<VarDecl>(Helper->getDecl());
1899 CGF.EmitVarDecl(*VDecl);
1900 return CGF.EmitLValue(Helper);
1901}
1902
1903static std::pair<LValue, LValue>
1904emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
1905 const OMPExecutableDirective &S) {
1906 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1907 LValue LB =
1908 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
1909 LValue UB =
1910 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
1911
1912 // When composing 'distribute' with 'for' (e.g. as in 'distribute
1913 // parallel for') we need to use the 'distribute'
1914 // chunk lower and upper bounds rather than the whole loop iteration
1915 // space. These are parameters to the outlined function for 'parallel'
1916 // and we copy the bounds of the previous schedule into the
1917 // the current ones.
1918 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
1919 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
1920 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(PrevLB, SourceLocation());
1921 PrevLBVal = CGF.EmitScalarConversion(
1922 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
1923 LS.getIterationVariable()->getType(), SourceLocation());
1924 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(PrevUB, SourceLocation());
1925 PrevUBVal = CGF.EmitScalarConversion(
1926 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
1927 LS.getIterationVariable()->getType(), SourceLocation());
1928
1929 CGF.EmitStoreOfScalar(PrevLBVal, LB);
1930 CGF.EmitStoreOfScalar(PrevUBVal, UB);
1931
1932 return {LB, UB};
1933}
1934
1935/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
1936/// we need to use the LB and UB expressions generated by the worksharing
1937/// code generation support, whereas in non combined situations we would
1938/// just emit 0 and the LastIteration expression
1939/// This function is necessary due to the difference of the LB and UB
1940/// types for the RT emission routines for 'for_static_init' and
1941/// 'for_dispatch_init'
1942static std::pair<llvm::Value *, llvm::Value *>
1943emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
1944 const OMPExecutableDirective &S,
1945 Address LB, Address UB) {
1946 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1947 const Expr *IVExpr = LS.getIterationVariable();
1948 // when implementing a dynamic schedule for a 'for' combined with a
1949 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
1950 // is not normalized as each team only executes its own assigned
1951 // distribute chunk
1952 QualType IteratorTy = IVExpr->getType();
1953 llvm::Value *LBVal = CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy,
1954 SourceLocation());
1955 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy,
1956 SourceLocation());
1957 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00001958}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001959
1960static void emitDistributeParallelForDistributeInnerBoundParams(
1961 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1962 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
1963 const auto &Dir = cast<OMPLoopDirective>(S);
1964 LValue LB =
1965 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
1966 auto LBCast = CGF.Builder.CreateIntCast(
1967 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
1968 CapturedVars.push_back(LBCast);
1969 LValue UB =
1970 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
1971
1972 auto UBCast = CGF.Builder.CreateIntCast(
1973 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
1974 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00001975}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001976
1977static void
1978emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
1979 const OMPLoopDirective &S,
1980 CodeGenFunction::JumpDest LoopExit) {
1981 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
1982 PrePostActionTy &) {
1983 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
1984 emitDistributeParallelForInnerBounds,
1985 emitDistributeParallelForDispatchBounds);
1986 };
1987
1988 emitCommonOMPParallelDirective(
1989 CGF, S, OMPD_for, CGInlinedWorksharingLoop,
1990 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001991}
1992
Carlo Bertolli9925f152016-06-27 14:55:37 +00001993void CodeGenFunction::EmitOMPDistributeParallelForDirective(
1994 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001995 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1996 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
1997 S.getDistInc());
1998 };
Carlo Bertolli9925f152016-06-27 14:55:37 +00001999 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002000 OMPCancelStackRAII CancelRegion(*this, OMPD_distribute_parallel_for,
2001 /*HasCancel=*/false);
2002 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
2003 /*HasCancel=*/false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002004}
2005
Kelvin Li4a39add2016-07-05 05:00:15 +00002006void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2007 const OMPDistributeParallelForSimdDirective &S) {
2008 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2009 CGM.getOpenMPRuntime().emitInlinedDirective(
2010 *this, OMPD_distribute_parallel_for_simd,
2011 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2012 OMPLoopScope PreInitScope(CGF, S);
2013 CGF.EmitStmt(
2014 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2015 });
2016}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002017
2018void CodeGenFunction::EmitOMPDistributeSimdDirective(
2019 const OMPDistributeSimdDirective &S) {
2020 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2021 CGM.getOpenMPRuntime().emitInlinedDirective(
2022 *this, OMPD_distribute_simd,
2023 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2024 OMPLoopScope PreInitScope(CGF, S);
2025 CGF.EmitStmt(
2026 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2027 });
2028}
2029
Kelvin Li986330c2016-07-20 22:57:10 +00002030void CodeGenFunction::EmitOMPTargetSimdDirective(
2031 const OMPTargetSimdDirective &S) {
2032 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2033 CGM.getOpenMPRuntime().emitInlinedDirective(
2034 *this, OMPD_target_simd, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2035 OMPLoopScope PreInitScope(CGF, S);
2036 CGF.EmitStmt(
2037 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2038 });
2039}
2040
Kelvin Li4e325f72016-10-25 12:50:55 +00002041void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
2042 const OMPTeamsDistributeSimdDirective &S) {
2043 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2044 CGM.getOpenMPRuntime().emitInlinedDirective(
2045 *this, OMPD_teams_distribute_simd,
2046 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2047 OMPLoopScope PreInitScope(CGF, S);
2048 CGF.EmitStmt(
2049 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2050 });
2051}
2052
Kelvin Li579e41c2016-11-30 23:51:03 +00002053void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
2054 const OMPTeamsDistributeParallelForSimdDirective &S) {
2055 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2056 CGM.getOpenMPRuntime().emitInlinedDirective(
2057 *this, OMPD_teams_distribute_parallel_for_simd,
2058 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2059 OMPLoopScope PreInitScope(CGF, S);
2060 CGF.EmitStmt(
2061 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2062 });
2063}
Kelvin Li4e325f72016-10-25 12:50:55 +00002064
Kelvin Li7ade93f2016-12-09 03:24:30 +00002065void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
2066 const OMPTeamsDistributeParallelForDirective &S) {
2067 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2068 CGM.getOpenMPRuntime().emitInlinedDirective(
2069 *this, OMPD_teams_distribute_parallel_for,
2070 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2071 OMPLoopScope PreInitScope(CGF, S);
2072 CGF.EmitStmt(
2073 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2074 });
2075}
2076
Kelvin Li83c451e2016-12-25 04:52:54 +00002077void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
2078 const OMPTargetTeamsDistributeDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002079 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Li26fd21a2016-12-28 17:57:07 +00002080 CGM.getOpenMPRuntime().emitInlinedDirective(
2081 *this, OMPD_target_teams_distribute,
Kelvin Li83c451e2016-12-25 04:52:54 +00002082 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002083 CGF.EmitStmt(
2084 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Kelvin Li83c451e2016-12-25 04:52:54 +00002085 });
2086}
2087
Kelvin Li80e8f562016-12-29 22:16:30 +00002088void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
2089 const OMPTargetTeamsDistributeParallelForDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002090 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Li80e8f562016-12-29 22:16:30 +00002091 CGM.getOpenMPRuntime().emitInlinedDirective(
2092 *this, OMPD_target_teams_distribute_parallel_for,
2093 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2094 CGF.EmitStmt(
2095 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2096 });
2097}
2098
Kelvin Li1851df52017-01-03 05:23:48 +00002099void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2100 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002101 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Li1851df52017-01-03 05:23:48 +00002102 CGM.getOpenMPRuntime().emitInlinedDirective(
2103 *this, OMPD_target_teams_distribute_parallel_for_simd,
2104 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2105 CGF.EmitStmt(
2106 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2107 });
2108}
2109
Kelvin Lida681182017-01-10 18:08:18 +00002110void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
2111 const OMPTargetTeamsDistributeSimdDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002112 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Lida681182017-01-10 18:08:18 +00002113 CGM.getOpenMPRuntime().emitInlinedDirective(
2114 *this, OMPD_target_teams_distribute_simd,
2115 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2116 CGF.EmitStmt(
2117 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2118 });
2119}
2120
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002121namespace {
2122 struct ScheduleKindModifiersTy {
2123 OpenMPScheduleClauseKind Kind;
2124 OpenMPScheduleClauseModifier M1;
2125 OpenMPScheduleClauseModifier M2;
2126 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2127 OpenMPScheduleClauseModifier M1,
2128 OpenMPScheduleClauseModifier M2)
2129 : Kind(Kind), M1(M1), M2(M2) {}
2130 };
2131} // namespace
2132
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002133bool CodeGenFunction::EmitOMPWorksharingLoop(
2134 const OMPLoopDirective &S, Expr *EUB,
2135 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2136 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002137 // Emit the loop iteration variable.
2138 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2139 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2140 EmitVarDecl(*IVDecl);
2141
2142 // Emit the iterations count variable.
2143 // If it is not a variable, Sema decided to calculate iterations count on each
2144 // iteration (e.g., it is foldable into a constant).
2145 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2146 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2147 // Emit calculation of the iterations count.
2148 EmitIgnoredExpr(S.getCalcLastIteration());
2149 }
2150
2151 auto &RT = CGM.getOpenMPRuntime();
2152
Alexey Bataev38e89532015-04-16 04:54:05 +00002153 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002154 // Check pre-condition.
2155 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002156 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002157 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002158 // If the condition constant folds and can be elided, avoid emitting the
2159 // whole loop.
2160 bool CondConstant;
2161 llvm::BasicBlock *ContBlock = nullptr;
2162 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2163 if (!CondConstant)
2164 return false;
2165 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002166 auto *ThenBlock = createBasicBlock("omp.precond.then");
2167 ContBlock = createBasicBlock("omp.precond.end");
2168 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002169 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002170 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002171 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002172 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002173
Alexey Bataev8b427062016-05-25 12:36:08 +00002174 bool Ordered = false;
2175 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2176 if (OrderedClause->getNumForLoops())
2177 RT.emitDoacrossInit(*this, S);
2178 else
2179 Ordered = true;
2180 }
2181
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002182 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002183 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002184 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002185 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002186
2187 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2188 LValue LB = Bounds.first;
2189 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002190 LValue ST =
2191 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2192 LValue IL =
2193 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2194
Alexander Musmanc6388682014-12-15 07:07:06 +00002195 // Emit 'then' code.
2196 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002197 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002198 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002199 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002200 // initialization of firstprivate variables and post-update of
2201 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002202 CGM.getOpenMPRuntime().emitBarrierCall(
2203 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2204 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002205 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002206 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002207 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002208 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002209 EmitOMPPrivateLoopCounters(S, LoopScope);
2210 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002211 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002212
2213 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002214 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002215 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002216 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002217 ScheduleKind.Schedule = C->getScheduleKind();
2218 ScheduleKind.M1 = C->getFirstScheduleModifier();
2219 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002220 if (const auto *Ch = C->getChunkSize()) {
2221 Chunk = EmitScalarExpr(Ch);
2222 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2223 S.getIterationVariable()->getType(),
2224 S.getLocStart());
2225 }
2226 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002227 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2228 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002229 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2230 // If the static schedule kind is specified or if the ordered clause is
2231 // specified, and if no monotonic modifier is specified, the effect will
2232 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002233 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002234 /* Chunked */ Chunk != nullptr) &&
2235 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002236 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2237 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002238 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2239 // When no chunk_size is specified, the iteration space is divided into
2240 // chunks that are approximately equal in size, and at most one chunk is
2241 // distributed to each thread. Note that the size of the chunks is
2242 // unspecified in this case.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002243 CGOpenMPRuntime::StaticRTInput StaticInit(
2244 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
2245 UB.getAddress(), ST.getAddress());
2246 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
2247 ScheduleKind, StaticInit);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002248 auto LoopExit =
2249 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002250 // UB = min(UB, GlobalUB);
2251 EmitIgnoredExpr(S.getEnsureUpperBound());
2252 // IV = LB;
2253 EmitIgnoredExpr(S.getInit());
2254 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002255 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2256 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002257 [&S, LoopExit](CodeGenFunction &CGF) {
2258 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002259 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002260 },
2261 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002262 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002263 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002264 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002265 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2266 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002267 };
2268 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002269 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002270 const bool IsMonotonic =
2271 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2272 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2273 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2274 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002275 // Emit the outer loop, which requests its work chunk [LB..UB] from
2276 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002277 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2278 ST.getAddress(), IL.getAddress(),
2279 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002280 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002281 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002282 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002283 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2284 EmitOMPSimdFinal(S,
2285 [&](CodeGenFunction &CGF) -> llvm::Value * {
2286 return CGF.Builder.CreateIsNotNull(
2287 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2288 });
2289 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002290 EmitOMPReductionClauseFinal(
2291 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2292 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2293 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002294 // Emit post-update of the reduction variables if IsLastIter != 0.
2295 emitPostUpdateForReductionClause(
2296 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2297 return CGF.Builder.CreateIsNotNull(
2298 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2299 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002300 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2301 if (HasLastprivateClause)
2302 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002303 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2304 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002305 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002306 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002307 return CGF.Builder.CreateIsNotNull(
2308 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2309 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002310 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002311 if (ContBlock) {
2312 EmitBranch(ContBlock);
2313 EmitBlock(ContBlock, true);
2314 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002315 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002316 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002317}
2318
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002319/// The following two functions generate expressions for the loop lower
2320/// and upper bounds in case of static and dynamic (dispatch) schedule
2321/// of the associated 'for' or 'distribute' loop.
2322static std::pair<LValue, LValue>
2323emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2324 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2325 LValue LB =
2326 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2327 LValue UB =
2328 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2329 return {LB, UB};
2330}
2331
2332/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2333/// consider the lower and upper bound expressions generated by the
2334/// worksharing loop support, but we use 0 and the iteration space size as
2335/// constants
2336static std::pair<llvm::Value *, llvm::Value *>
2337emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2338 Address LB, Address UB) {
2339 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2340 const Expr *IVExpr = LS.getIterationVariable();
2341 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2342 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2343 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2344 return {LBVal, UBVal};
2345}
2346
Alexander Musmanc6388682014-12-15 07:07:06 +00002347void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002348 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002349 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2350 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002351 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002352 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2353 emitForLoopBounds,
2354 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002355 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002356 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002357 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002358 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2359 S.hasCancel());
2360 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002361
2362 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002363 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002364 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2365 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002366}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002367
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002368void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002369 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002370 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2371 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002372 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2373 emitForLoopBounds,
2374 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002375 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002376 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002377 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002378 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2379 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002380
2381 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002382 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002383 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2384 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002385}
2386
Alexey Bataev2df54a02015-03-12 08:53:29 +00002387static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2388 const Twine &Name,
2389 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002390 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002391 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002392 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002393 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002394}
2395
Alexey Bataev3392d762016-02-16 11:18:12 +00002396void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00002397 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2398 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002399 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002400 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2401 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002402 auto &C = CGF.CGM.getContext();
2403 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2404 // Emit helper vars inits.
2405 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2406 CGF.Builder.getInt32(0));
2407 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2408 : CGF.Builder.getInt32(0);
2409 LValue UB =
2410 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2411 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2412 CGF.Builder.getInt32(1));
2413 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2414 CGF.Builder.getInt32(0));
2415 // Loop counter.
2416 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2417 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2418 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2419 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2420 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2421 // Generate condition for loop.
2422 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002423 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002424 // Increment for loop counter.
2425 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2426 S.getLocStart());
2427 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2428 // Iterate through all sections and emit a switch construct:
2429 // switch (IV) {
2430 // case 0:
2431 // <SectionStmt[0]>;
2432 // break;
2433 // ...
2434 // case <NumSection> - 1:
2435 // <SectionStmt[<NumSection> - 1]>;
2436 // break;
2437 // }
2438 // .omp.sections.exit:
2439 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2440 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2441 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2442 CS == nullptr ? 1 : CS->size());
2443 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002444 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002445 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002446 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2447 CGF.EmitBlock(CaseBB);
2448 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002449 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002450 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002451 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002452 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002453 } else {
2454 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2455 CGF.EmitBlock(CaseBB);
2456 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2457 CGF.EmitStmt(Stmt);
2458 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002459 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002460 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002461 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002462
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002463 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2464 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002465 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002466 // initialization of firstprivate variables and post-update of lastprivate
2467 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002468 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2469 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2470 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002471 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002472 CGF.EmitOMPPrivateClause(S, LoopScope);
2473 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2474 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2475 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002476
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002477 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002478 OpenMPScheduleTy ScheduleKind;
2479 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002480 CGOpenMPRuntime::StaticRTInput StaticInit(
2481 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2482 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002483 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002484 CGF, S.getLocStart(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002485 // UB = min(UB, GlobalUB);
2486 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2487 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2488 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2489 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2490 // IV = LB;
2491 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2492 // while (idx <= UB) { BODY; ++idx; }
2493 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2494 [](CodeGenFunction &) {});
2495 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002496 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002497 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2498 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002499 };
2500 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002501 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002502 // Emit post-update of the reduction variables if IsLastIter != 0.
2503 emitPostUpdateForReductionClause(
2504 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2505 return CGF.Builder.CreateIsNotNull(
2506 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2507 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002508
2509 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2510 if (HasLastprivates)
2511 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002512 S, /*NoFinals=*/false,
2513 CGF.Builder.CreateIsNotNull(
2514 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002515 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002516
2517 bool HasCancel = false;
2518 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2519 HasCancel = OSD->hasCancel();
2520 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2521 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002522 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002523 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2524 HasCancel);
2525 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2526 // clause. Otherwise the barrier will be generated by the codegen for the
2527 // directive.
2528 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002529 // Emit implicit barrier to synchronize threads and avoid data races on
2530 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002531 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2532 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002533 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002534}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002535
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002536void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002537 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002538 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002539 EmitSections(S);
2540 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002541 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002542 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002543 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2544 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002545 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002546}
2547
2548void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002549 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002550 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002551 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002552 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002553 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2554 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002555}
2556
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002557void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002558 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002559 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002560 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002561 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002562 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002563 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002564 // Build a list of copyprivate variables along with helper expressions
2565 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002566 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002567 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002568 DestExprs.append(C->destination_exprs().begin(),
2569 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002570 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002571 AssignmentOps.append(C->assignment_ops().begin(),
2572 C->assignment_ops().end());
2573 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002574 // Emit code for 'single' region along with 'copyprivate' clauses
2575 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2576 Action.Enter(CGF);
2577 OMPPrivateScope SingleScope(CGF);
2578 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2579 CGF.EmitOMPPrivateClause(S, SingleScope);
2580 (void)SingleScope.Privatize();
2581 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2582 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002583 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002584 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002585 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2586 CopyprivateVars, DestExprs,
2587 SrcExprs, AssignmentOps);
2588 }
2589 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2590 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002591 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002592 CGM.getOpenMPRuntime().emitBarrierCall(
2593 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002594 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002595 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002596}
2597
Alexey Bataev8d690652014-12-04 07:23:53 +00002598void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002599 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2600 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002601 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002602 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002603 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002604 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002605}
2606
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002607void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &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 Bataevfc57d162015-12-15 10:55:09 +00002612 Expr *Hint = nullptr;
2613 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2614 Hint = HintClause->getHint();
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002615 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002616 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2617 S.getDirectiveName().getAsString(),
2618 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002619}
2620
Alexey Bataev671605e2015-04-13 05:28:11 +00002621void CodeGenFunction::EmitOMPParallelForDirective(
2622 const OMPParallelForDirective &S) {
2623 // Emit directive as a combined directive that consists of two implicit
2624 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002625 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002626 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002627 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2628 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002629 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002630 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2631 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002632}
2633
Alexander Musmane4e893b2014-09-23 09:33:00 +00002634void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002635 const OMPParallelForSimdDirective &S) {
2636 // Emit directive as a combined directive that consists of two implicit
2637 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002638 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002639 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2640 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002641 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002642 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2643 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002644}
2645
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002646void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002647 const OMPParallelSectionsDirective &S) {
2648 // Emit directive as a combined directive that consists of two implicit
2649 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002650 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2651 CGF.EmitSections(S);
2652 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002653 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2654 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002655}
2656
Alexey Bataev7292c292016-04-25 12:22:29 +00002657void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2658 const RegionCodeGenTy &BodyGen,
2659 const TaskGenTy &TaskGen,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002660 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002661 // Emit outlined function for task construct.
2662 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002663 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002664 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002665 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002666 // Check if the task is final
2667 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2668 // If the condition constant folds and can be elided, try to avoid emitting
2669 // the condition and the dead arm of the if/else.
2670 auto *Cond = Clause->getCondition();
2671 bool CondConstant;
2672 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2673 Data.Final.setInt(CondConstant);
2674 else
2675 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2676 } else {
2677 // By default the task is not final.
2678 Data.Final.setInt(/*IntVal=*/false);
2679 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002680 // Check if the task has 'priority' clause.
2681 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002682 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002683 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002684 Data.Priority.setPointer(EmitScalarConversion(
2685 EmitScalarExpr(Prio), Prio->getType(),
2686 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2687 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002688 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002689 // The first function argument for tasks is a thread id, the second one is a
2690 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002691 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2692 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002693 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002694 auto IRef = C->varlist_begin();
2695 for (auto *IInit : C->private_copies()) {
2696 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2697 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002698 Data.PrivateVars.push_back(*IRef);
2699 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002700 }
2701 ++IRef;
2702 }
2703 }
2704 EmittedAsPrivate.clear();
2705 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002706 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002707 auto IRef = C->varlist_begin();
2708 auto IElemInitRef = C->inits().begin();
2709 for (auto *IInit : C->private_copies()) {
2710 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2711 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002712 Data.FirstprivateVars.push_back(*IRef);
2713 Data.FirstprivateCopies.push_back(IInit);
2714 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002715 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002716 ++IRef;
2717 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002718 }
2719 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002720 // Get list of lastprivate variables (for taskloops).
2721 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2722 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2723 auto IRef = C->varlist_begin();
2724 auto ID = C->destination_exprs().begin();
2725 for (auto *IInit : C->private_copies()) {
2726 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2727 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2728 Data.LastprivateVars.push_back(*IRef);
2729 Data.LastprivateCopies.push_back(IInit);
2730 }
2731 LastprivateDstsOrigs.insert(
2732 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2733 cast<DeclRefExpr>(*IRef)});
2734 ++IRef;
2735 ++ID;
2736 }
2737 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002738 SmallVector<const Expr *, 4> LHSs;
2739 SmallVector<const Expr *, 4> RHSs;
2740 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2741 auto IPriv = C->privates().begin();
2742 auto IRed = C->reduction_ops().begin();
2743 auto ILHS = C->lhs_exprs().begin();
2744 auto IRHS = C->rhs_exprs().begin();
2745 for (const auto *Ref : C->varlists()) {
2746 Data.ReductionVars.emplace_back(Ref);
2747 Data.ReductionCopies.emplace_back(*IPriv);
2748 Data.ReductionOps.emplace_back(*IRed);
2749 LHSs.emplace_back(*ILHS);
2750 RHSs.emplace_back(*IRHS);
2751 std::advance(IPriv, 1);
2752 std::advance(IRed, 1);
2753 std::advance(ILHS, 1);
2754 std::advance(IRHS, 1);
2755 }
2756 }
2757 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2758 *this, S.getLocStart(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002759 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002760 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2761 for (auto *IRef : C->varlists())
2762 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002763 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs](
Alexey Bataevf93095a2016-05-05 08:46:22 +00002764 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002765 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002766 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002767 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2768 !Data.LastprivateVars.empty()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00002769 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataev48591dd2016-04-20 04:01:36 +00002770 auto *CopyFn = CGF.Builder.CreateLoad(
2771 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2772 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2773 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2774 // Map privates.
2775 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2776 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2777 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002778 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002779 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2780 Address PrivatePtr = CGF.CreateMemTemp(
2781 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2782 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2783 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002784 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002785 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002786 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2787 Address PrivatePtr =
2788 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2789 ".firstpriv.ptr.addr");
2790 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2791 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002792 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002793 for (auto *E : Data.LastprivateVars) {
2794 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2795 Address PrivatePtr =
2796 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2797 ".lastpriv.ptr.addr");
2798 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2799 CallArgs.push_back(PrivatePtr.getPointer());
2800 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00002801 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
2802 CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002803 for (auto &&Pair : LastprivateDstsOrigs) {
2804 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2805 DeclRefExpr DRE(
2806 const_cast<VarDecl *>(OrigVD),
2807 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2808 OrigVD) != nullptr,
2809 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2810 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2811 return CGF.EmitLValue(&DRE).getAddress();
2812 });
2813 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002814 for (auto &&Pair : PrivatePtrs) {
2815 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2816 CGF.getContext().getDeclAlign(Pair.first));
2817 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2818 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002819 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002820 if (Data.Reductions) {
2821 OMPLexicalScope LexScope(CGF, S, /*AsInlined=*/true);
2822 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2823 Data.ReductionOps);
2824 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2825 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2826 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2827 RedCG.emitSharedLValue(CGF, Cnt);
2828 RedCG.emitAggregateType(CGF, Cnt);
2829 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2830 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2831 Replacement =
2832 Address(CGF.EmitScalarConversion(
2833 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2834 CGF.getContext().getPointerType(
2835 Data.ReductionCopies[Cnt]->getType()),
2836 SourceLocation()),
2837 Replacement.getAlignment());
2838 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2839 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2840 [Replacement]() { return Replacement; });
2841 // FIXME: This must removed once the runtime library is fixed.
2842 // Emit required threadprivate variables for
2843 // initilizer/combiner/finalizer.
2844 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2845 RedCG, Cnt);
2846 }
2847 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002848 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002849 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002850 SmallVector<const Expr *, 4> InRedVars;
2851 SmallVector<const Expr *, 4> InRedPrivs;
2852 SmallVector<const Expr *, 4> InRedOps;
2853 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2854 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2855 auto IPriv = C->privates().begin();
2856 auto IRed = C->reduction_ops().begin();
2857 auto ITD = C->taskgroup_descriptors().begin();
2858 for (const auto *Ref : C->varlists()) {
2859 InRedVars.emplace_back(Ref);
2860 InRedPrivs.emplace_back(*IPriv);
2861 InRedOps.emplace_back(*IRed);
2862 TaskgroupDescriptors.emplace_back(*ITD);
2863 std::advance(IPriv, 1);
2864 std::advance(IRed, 1);
2865 std::advance(ITD, 1);
2866 }
2867 }
2868 // Privatize in_reduction items here, because taskgroup descriptors must be
2869 // privatized earlier.
2870 OMPPrivateScope InRedScope(CGF);
2871 if (!InRedVars.empty()) {
2872 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2873 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2874 RedCG.emitSharedLValue(CGF, Cnt);
2875 RedCG.emitAggregateType(CGF, Cnt);
2876 // The taskgroup descriptor variable is always implicit firstprivate and
2877 // privatized already during procoessing of the firstprivates.
2878 llvm::Value *ReductionsPtr = CGF.EmitLoadOfScalar(
2879 CGF.EmitLValue(TaskgroupDescriptors[Cnt]), SourceLocation());
2880 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2881 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2882 Replacement = Address(
2883 CGF.EmitScalarConversion(
2884 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2885 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
2886 SourceLocation()),
2887 Replacement.getAlignment());
2888 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2889 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2890 [Replacement]() { return Replacement; });
2891 // FIXME: This must removed once the runtime library is fixed.
2892 // Emit required threadprivate variables for
2893 // initilizer/combiner/finalizer.
2894 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2895 RedCG, Cnt);
2896 }
2897 }
2898 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00002899
2900 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002901 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002902 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002903 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2904 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2905 Data.NumberOfParts);
2906 OMPLexicalScope Scope(*this, S);
2907 TaskGen(*this, OutlinedFn, Data);
2908}
2909
2910void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2911 // Emit outlined function for task construct.
2912 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2913 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002914 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002915 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002916 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2917 if (C->getNameModifier() == OMPD_unknown ||
2918 C->getNameModifier() == OMPD_task) {
2919 IfCond = C->getCondition();
2920 break;
2921 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002922 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002923
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002924 OMPTaskDataTy Data;
2925 // Check if we should emit tied or untied task.
2926 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00002927 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
2928 CGF.EmitStmt(CS->getCapturedStmt());
2929 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002930 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00002931 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002932 const OMPTaskDataTy &Data) {
2933 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
2934 SharedsTy, CapturedStruct, IfCond,
2935 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00002936 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002937 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002938}
2939
Alexey Bataev9f797f32015-02-05 05:57:51 +00002940void CodeGenFunction::EmitOMPTaskyieldDirective(
2941 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002942 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002943}
2944
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002945void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002946 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002947}
2948
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002949void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2950 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002951}
2952
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002953void CodeGenFunction::EmitOMPTaskgroupDirective(
2954 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002955 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2956 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002957 if (const Expr *E = S.getReductionRef()) {
2958 SmallVector<const Expr *, 4> LHSs;
2959 SmallVector<const Expr *, 4> RHSs;
2960 OMPTaskDataTy Data;
2961 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
2962 auto IPriv = C->privates().begin();
2963 auto IRed = C->reduction_ops().begin();
2964 auto ILHS = C->lhs_exprs().begin();
2965 auto IRHS = C->rhs_exprs().begin();
2966 for (const auto *Ref : C->varlists()) {
2967 Data.ReductionVars.emplace_back(Ref);
2968 Data.ReductionCopies.emplace_back(*IPriv);
2969 Data.ReductionOps.emplace_back(*IRed);
2970 LHSs.emplace_back(*ILHS);
2971 RHSs.emplace_back(*IRHS);
2972 std::advance(IPriv, 1);
2973 std::advance(IRed, 1);
2974 std::advance(ILHS, 1);
2975 std::advance(IRHS, 1);
2976 }
2977 }
2978 llvm::Value *ReductionDesc =
2979 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getLocStart(),
2980 LHSs, RHSs, Data);
2981 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2982 CGF.EmitVarDecl(*VD);
2983 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
2984 /*Volatile=*/false, E->getType());
2985 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002986 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002987 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002988 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002989 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2990}
2991
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002992void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002993 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002994 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002995 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2996 FlushClause->varlist_end());
2997 }
2998 return llvm::None;
2999 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00003000}
3001
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003002void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3003 const CodeGenLoopTy &CodeGenLoop,
3004 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003005 // Emit the loop iteration variable.
3006 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3007 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
3008 EmitVarDecl(*IVDecl);
3009
3010 // Emit the iterations count variable.
3011 // If it is not a variable, Sema decided to calculate iterations count on each
3012 // iteration (e.g., it is foldable into a constant).
3013 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3014 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3015 // Emit calculation of the iterations count.
3016 EmitIgnoredExpr(S.getCalcLastIteration());
3017 }
3018
3019 auto &RT = CGM.getOpenMPRuntime();
3020
Carlo Bertolli962bb802017-01-03 18:24:42 +00003021 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003022 // Check pre-condition.
3023 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003024 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003025 // Skip the entire loop if we don't meet the precondition.
3026 // If the condition constant folds and can be elided, avoid emitting the
3027 // whole loop.
3028 bool CondConstant;
3029 llvm::BasicBlock *ContBlock = nullptr;
3030 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3031 if (!CondConstant)
3032 return;
3033 } else {
3034 auto *ThenBlock = createBasicBlock("omp.precond.then");
3035 ContBlock = createBasicBlock("omp.precond.end");
3036 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3037 getProfileCount(&S));
3038 EmitBlock(ThenBlock);
3039 incrementProfileCounter(&S);
3040 }
3041
3042 // Emit 'then' code.
3043 {
3044 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003045
3046 LValue LB = EmitOMPHelperVar(
3047 *this, cast<DeclRefExpr>(
3048 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3049 ? S.getCombinedLowerBoundVariable()
3050 : S.getLowerBoundVariable())));
3051 LValue UB = EmitOMPHelperVar(
3052 *this, cast<DeclRefExpr>(
3053 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3054 ? S.getCombinedUpperBoundVariable()
3055 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003056 LValue ST =
3057 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3058 LValue IL =
3059 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3060
3061 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003062 if (EmitOMPFirstprivateClause(S, LoopScope)) {
3063 // Emit implicit barrier to synchronize threads and avoid data races on
3064 // initialization of firstprivate variables and post-update of
3065 // lastprivate variables.
3066 CGM.getOpenMPRuntime().emitBarrierCall(
3067 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3068 /*ForceSimpleCall=*/true);
3069 }
3070 EmitOMPPrivateClause(S, LoopScope);
3071 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003072 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003073 (void)LoopScope.Privatize();
3074
3075 // Detect the distribute schedule kind and chunk.
3076 llvm::Value *Chunk = nullptr;
3077 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3078 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3079 ScheduleKind = C->getDistScheduleKind();
3080 if (const auto *Ch = C->getChunkSize()) {
3081 Chunk = EmitScalarExpr(Ch);
3082 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
3083 S.getIterationVariable()->getType(),
3084 S.getLocStart());
3085 }
3086 }
3087 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3088 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3089
3090 // OpenMP [2.10.8, distribute Construct, Description]
3091 // If dist_schedule is specified, kind must be static. If specified,
3092 // iterations are divided into chunks of size chunk_size, chunks are
3093 // assigned to the teams of the league in a round-robin fashion in the
3094 // order of the team number. When no chunk_size is specified, the
3095 // iteration space is divided into chunks that are approximately equal
3096 // in size, and at most one chunk is distributed to each team of the
3097 // league. The size of the chunks is unspecified in this case.
3098 if (RT.isStaticNonchunked(ScheduleKind,
3099 /* Chunked */ Chunk != nullptr)) {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003100 CGOpenMPRuntime::StaticRTInput StaticInit(
3101 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3102 LB.getAddress(), UB.getAddress(), ST.getAddress());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003103 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003104 StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003105 auto LoopExit =
3106 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3107 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003108 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3109 ? S.getCombinedEnsureUpperBound()
3110 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003111 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003112 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3113 ? S.getCombinedInit()
3114 : S.getInit());
3115
3116 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3117 ? S.getCombinedCond()
3118 : S.getCond();
3119
3120 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003121 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003122 // when combined with 'for' (e.g. as in 'distribute parallel for')
3123 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3124 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3125 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3126 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003127 },
3128 [](CodeGenFunction &) {});
3129 EmitBlock(LoopExit.getBlock());
3130 // Tell the runtime we are done.
Alexey Bataevf43f7142017-09-06 16:17:35 +00003131 RT.emitForStaticFinish(*this, S.getLocStart(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003132 } else {
3133 // Emit the outer loop, which requests its work chunk [LB..UB] from
3134 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003135 const OMPLoopArguments LoopArguments = {
3136 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3137 Chunk};
3138 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3139 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003140 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00003141
3142 // Emit final copy of the lastprivate variables if IsLastIter != 0.
3143 if (HasLastprivateClause)
3144 EmitOMPLastprivateClauseFinal(
3145 S, /*NoFinals=*/false,
3146 Builder.CreateIsNotNull(
3147 EmitLoadOfScalar(IL, S.getLocStart())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003148 }
3149
3150 // We're now done with the loop, so jump to the continuation block.
3151 if (ContBlock) {
3152 EmitBranch(ContBlock);
3153 EmitBlock(ContBlock, true);
3154 }
3155 }
3156}
3157
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003158void CodeGenFunction::EmitOMPDistributeDirective(
3159 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003160 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003161
3162 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003163 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003164 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003165 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
3166 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003167}
3168
Alexey Bataev5f600d62015-09-29 03:48:57 +00003169static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3170 const CapturedStmt *S) {
3171 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3172 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3173 CGF.CapturedStmtInfo = &CapStmtInfo;
3174 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3175 Fn->addFnAttr(llvm::Attribute::NoInline);
3176 return Fn;
3177}
3178
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003179void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8b427062016-05-25 12:36:08 +00003180 if (!S.getAssociatedStmt()) {
3181 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3182 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003183 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003184 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003185 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003186 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3187 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003188 if (C) {
3189 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3190 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3191 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3192 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Alexey Bataev3c595a62017-08-14 15:01:03 +00003193 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3194 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003195 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003196 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003197 CGF.EmitStmt(
3198 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3199 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003200 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003201 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003202 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003203}
3204
Alexey Bataevb57056f2015-01-22 06:17:56 +00003205static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003206 QualType SrcType, QualType DestType,
3207 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003208 assert(CGF.hasScalarEvaluationKind(DestType) &&
3209 "DestType must have scalar evaluation kind.");
3210 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3211 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003212 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3213 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00003214 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003215 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003216}
3217
3218static CodeGenFunction::ComplexPairTy
3219convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003220 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003221 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3222 "DestType must have complex evaluation kind.");
3223 CodeGenFunction::ComplexPairTy ComplexVal;
3224 if (Val.isScalar()) {
3225 // Convert the input element to the element type of the complex.
3226 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003227 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3228 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003229 ComplexVal = CodeGenFunction::ComplexPairTy(
3230 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3231 } else {
3232 assert(Val.isComplex() && "Must be a scalar or complex.");
3233 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3234 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3235 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003236 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003237 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003238 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003239 }
3240 return ComplexVal;
3241}
3242
Alexey Bataev5e018f92015-04-23 06:35:10 +00003243static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3244 LValue LVal, RValue RVal) {
3245 if (LVal.isGlobalReg()) {
3246 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3247 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003248 CGF.EmitAtomicStore(RVal, LVal,
3249 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3250 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003251 LVal.isVolatile(), /*IsInit=*/false);
3252 }
3253}
3254
Alexey Bataev8524d152016-01-21 12:35:58 +00003255void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3256 QualType RValTy, SourceLocation Loc) {
3257 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003258 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003259 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3260 *this, RVal, RValTy, LVal.getType(), Loc)),
3261 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003262 break;
3263 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003264 EmitStoreOfComplex(
3265 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003266 /*isInit=*/false);
3267 break;
3268 case TEK_Aggregate:
3269 llvm_unreachable("Must be a scalar or complex.");
3270 }
3271}
3272
Alexey Bataevb57056f2015-01-22 06:17:56 +00003273static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3274 const Expr *X, const Expr *V,
3275 SourceLocation Loc) {
3276 // v = x;
3277 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3278 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3279 LValue XLValue = CGF.EmitLValue(X);
3280 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003281 RValue Res = XLValue.isGlobalReg()
3282 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003283 : CGF.EmitAtomicLoad(
3284 XLValue, Loc,
3285 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3286 : llvm::AtomicOrdering::Monotonic,
3287 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003288 // OpenMP, 2.12.6, atomic Construct
3289 // Any atomic construct with a seq_cst clause forces the atomically
3290 // performed operation to include an implicit flush operation without a
3291 // list.
3292 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003293 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003294 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003295}
3296
Alexey Bataevb8329262015-02-27 06:33:30 +00003297static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3298 const Expr *X, const Expr *E,
3299 SourceLocation Loc) {
3300 // x = expr;
3301 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003302 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003303 // OpenMP, 2.12.6, atomic Construct
3304 // Any atomic construct with a seq_cst clause forces the atomically
3305 // performed operation to include an implicit flush operation without a
3306 // list.
3307 if (IsSeqCst)
3308 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3309}
3310
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003311static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3312 RValue Update,
3313 BinaryOperatorKind BO,
3314 llvm::AtomicOrdering AO,
3315 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003316 auto &Context = CGF.CGM.getContext();
3317 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003318 // expression is simple and atomic is allowed for the given type for the
3319 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003320 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003321 !Update.getScalarVal()->getType()->isIntegerTy() ||
3322 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3323 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003324 X.getAddress().getElementType())) ||
3325 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003326 !Context.getTargetInfo().hasBuiltinAtomic(
3327 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003328 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003329
3330 llvm::AtomicRMWInst::BinOp RMWOp;
3331 switch (BO) {
3332 case BO_Add:
3333 RMWOp = llvm::AtomicRMWInst::Add;
3334 break;
3335 case BO_Sub:
3336 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003337 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003338 RMWOp = llvm::AtomicRMWInst::Sub;
3339 break;
3340 case BO_And:
3341 RMWOp = llvm::AtomicRMWInst::And;
3342 break;
3343 case BO_Or:
3344 RMWOp = llvm::AtomicRMWInst::Or;
3345 break;
3346 case BO_Xor:
3347 RMWOp = llvm::AtomicRMWInst::Xor;
3348 break;
3349 case BO_LT:
3350 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3351 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3352 : llvm::AtomicRMWInst::Max)
3353 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3354 : llvm::AtomicRMWInst::UMax);
3355 break;
3356 case BO_GT:
3357 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3358 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3359 : llvm::AtomicRMWInst::Min)
3360 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3361 : llvm::AtomicRMWInst::UMin);
3362 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003363 case BO_Assign:
3364 RMWOp = llvm::AtomicRMWInst::Xchg;
3365 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003366 case BO_Mul:
3367 case BO_Div:
3368 case BO_Rem:
3369 case BO_Shl:
3370 case BO_Shr:
3371 case BO_LAnd:
3372 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003373 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003374 case BO_PtrMemD:
3375 case BO_PtrMemI:
3376 case BO_LE:
3377 case BO_GE:
3378 case BO_EQ:
3379 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003380 case BO_AddAssign:
3381 case BO_SubAssign:
3382 case BO_AndAssign:
3383 case BO_OrAssign:
3384 case BO_XorAssign:
3385 case BO_MulAssign:
3386 case BO_DivAssign:
3387 case BO_RemAssign:
3388 case BO_ShlAssign:
3389 case BO_ShrAssign:
3390 case BO_Comma:
3391 llvm_unreachable("Unsupported atomic update operation");
3392 }
3393 auto *UpdateVal = Update.getScalarVal();
3394 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3395 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003396 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003397 X.getType()->hasSignedIntegerRepresentation());
3398 }
John McCall7f416cc2015-09-08 08:05:57 +00003399 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003400 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003401}
3402
Alexey Bataev5e018f92015-04-23 06:35:10 +00003403std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003404 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3405 llvm::AtomicOrdering AO, SourceLocation Loc,
3406 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3407 // Update expressions are allowed to have the following forms:
3408 // x binop= expr; -> xrval + expr;
3409 // x++, ++x -> xrval + 1;
3410 // x--, --x -> xrval - 1;
3411 // x = x binop expr; -> xrval binop expr
3412 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003413 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3414 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003415 if (X.isGlobalReg()) {
3416 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3417 // 'xrval'.
3418 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3419 } else {
3420 // Perform compare-and-swap procedure.
3421 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003422 }
3423 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003424 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003425}
3426
3427static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3428 const Expr *X, const Expr *E,
3429 const Expr *UE, bool IsXLHSInRHSPart,
3430 SourceLocation Loc) {
3431 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3432 "Update expr in 'atomic update' must be a binary operator.");
3433 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3434 // Update expressions are allowed to have the following forms:
3435 // x binop= expr; -> xrval + expr;
3436 // x++, ++x -> xrval + 1;
3437 // x--, --x -> xrval - 1;
3438 // x = x binop expr; -> xrval binop expr
3439 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003440 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003441 LValue XLValue = CGF.EmitLValue(X);
3442 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003443 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3444 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003445 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3446 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3447 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3448 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3449 auto Gen =
3450 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3451 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3452 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3453 return CGF.EmitAnyExpr(UE);
3454 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003455 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3456 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3457 // OpenMP, 2.12.6, atomic Construct
3458 // Any atomic construct with a seq_cst clause forces the atomically
3459 // performed operation to include an implicit flush operation without a
3460 // list.
3461 if (IsSeqCst)
3462 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3463}
3464
3465static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003466 QualType SourceType, QualType ResType,
3467 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003468 switch (CGF.getEvaluationKind(ResType)) {
3469 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003470 return RValue::get(
3471 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003472 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003473 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003474 return RValue::getComplex(Res.first, Res.second);
3475 }
3476 case TEK_Aggregate:
3477 break;
3478 }
3479 llvm_unreachable("Must be a scalar or complex.");
3480}
3481
3482static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3483 bool IsPostfixUpdate, const Expr *V,
3484 const Expr *X, const Expr *E,
3485 const Expr *UE, bool IsXLHSInRHSPart,
3486 SourceLocation Loc) {
3487 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3488 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3489 RValue NewVVal;
3490 LValue VLValue = CGF.EmitLValue(V);
3491 LValue XLValue = CGF.EmitLValue(X);
3492 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003493 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3494 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003495 QualType NewVValType;
3496 if (UE) {
3497 // 'x' is updated with some additional value.
3498 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3499 "Update expr in 'atomic capture' must be a binary operator.");
3500 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3501 // Update expressions are allowed to have the following forms:
3502 // x binop= expr; -> xrval + expr;
3503 // x++, ++x -> xrval + 1;
3504 // x--, --x -> xrval - 1;
3505 // x = x binop expr; -> xrval binop expr
3506 // x = expr Op x; - > expr binop xrval;
3507 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3508 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3509 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3510 NewVValType = XRValExpr->getType();
3511 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3512 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003513 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003514 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3515 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3516 RValue Res = CGF.EmitAnyExpr(UE);
3517 NewVVal = IsPostfixUpdate ? XRValue : Res;
3518 return Res;
3519 };
3520 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3521 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3522 if (Res.first) {
3523 // 'atomicrmw' instruction was generated.
3524 if (IsPostfixUpdate) {
3525 // Use old value from 'atomicrmw'.
3526 NewVVal = Res.second;
3527 } else {
3528 // 'atomicrmw' does not provide new value, so evaluate it using old
3529 // value of 'x'.
3530 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3531 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3532 NewVVal = CGF.EmitAnyExpr(UE);
3533 }
3534 }
3535 } else {
3536 // 'x' is simply rewritten with some 'expr'.
3537 NewVValType = X->getType().getNonReferenceType();
3538 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003539 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003540 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003541 NewVVal = XRValue;
3542 return ExprRValue;
3543 };
3544 // Try to perform atomicrmw xchg, otherwise simple exchange.
3545 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3546 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3547 Loc, Gen);
3548 if (Res.first) {
3549 // 'atomicrmw' instruction was generated.
3550 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3551 }
3552 }
3553 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003554 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003555 // OpenMP, 2.12.6, atomic Construct
3556 // Any atomic construct with a seq_cst clause forces the atomically
3557 // performed operation to include an implicit flush operation without a
3558 // list.
3559 if (IsSeqCst)
3560 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3561}
3562
Alexey Bataevb57056f2015-01-22 06:17:56 +00003563static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003564 bool IsSeqCst, bool IsPostfixUpdate,
3565 const Expr *X, const Expr *V, const Expr *E,
3566 const Expr *UE, bool IsXLHSInRHSPart,
3567 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003568 switch (Kind) {
3569 case OMPC_read:
3570 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3571 break;
3572 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003573 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3574 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003575 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003576 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003577 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3578 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003579 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003580 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3581 IsXLHSInRHSPart, Loc);
3582 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003583 case OMPC_if:
3584 case OMPC_final:
3585 case OMPC_num_threads:
3586 case OMPC_private:
3587 case OMPC_firstprivate:
3588 case OMPC_lastprivate:
3589 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003590 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003591 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003592 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003593 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003594 case OMPC_collapse:
3595 case OMPC_default:
3596 case OMPC_seq_cst:
3597 case OMPC_shared:
3598 case OMPC_linear:
3599 case OMPC_aligned:
3600 case OMPC_copyin:
3601 case OMPC_copyprivate:
3602 case OMPC_flush:
3603 case OMPC_proc_bind:
3604 case OMPC_schedule:
3605 case OMPC_ordered:
3606 case OMPC_nowait:
3607 case OMPC_untied:
3608 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003609 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003610 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003611 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003612 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003613 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003614 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003615 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003616 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003617 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003618 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003619 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003620 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003621 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003622 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003623 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003624 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003625 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003626 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003627 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003628 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003629 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3630 }
3631}
3632
3633void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003634 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003635 OpenMPClauseKind Kind = OMPC_unknown;
3636 for (auto *C : S.clauses()) {
3637 // Find first clause (skip seq_cst clause, if it is first).
3638 if (C->getClauseKind() != OMPC_seq_cst) {
3639 Kind = C->getClauseKind();
3640 break;
3641 }
3642 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003643
3644 const auto *CS =
3645 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003646 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003647 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003648 }
3649 // Processing for statements under 'atomic capture'.
3650 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3651 for (const auto *C : Compound->body()) {
3652 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3653 enterFullExpression(EWC);
3654 }
3655 }
3656 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003657
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003658 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3659 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003660 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003661 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3662 S.getV(), S.getExpr(), S.getUpdateExpr(),
3663 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003664 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003665 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003666 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003667}
3668
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003669static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3670 const OMPExecutableDirective &S,
3671 const RegionCodeGenTy &CodeGen) {
3672 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3673 CodeGenModule &CGM = CGF.CGM;
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00003674 const CapturedStmt &CS = *S.getCapturedStmt(OMPD_target);
Samuel Antaobed3c462015-10-02 16:14:20 +00003675
Samuel Antaoee8fb302016-01-06 13:42:12 +00003676 llvm::Function *Fn = nullptr;
3677 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003678
Samuel Antaobed3c462015-10-02 16:14:20 +00003679 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003680 // Check for the at most one if clause associated with the target region.
3681 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3682 if (C->getNameModifier() == OMPD_unknown ||
3683 C->getNameModifier() == OMPD_target) {
3684 IfCond = C->getCondition();
3685 break;
3686 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003687 }
3688
3689 // Check if we have any device clause associated with the directive.
3690 const Expr *Device = nullptr;
3691 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3692 Device = C->getDevice();
3693 }
3694
Samuel Antaoee8fb302016-01-06 13:42:12 +00003695 // Check if we have an if clause whose conditional always evaluates to false
3696 // or if we do not have any targets specified. If so the target region is not
3697 // an offload entry point.
3698 bool IsOffloadEntry = true;
3699 if (IfCond) {
3700 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003701 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003702 IsOffloadEntry = false;
3703 }
3704 if (CGM.getLangOpts().OMPTargetTriples.empty())
3705 IsOffloadEntry = false;
3706
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003707 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003708 StringRef ParentName;
3709 // In case we have Ctors/Dtors we use the complete type variant to produce
3710 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003711 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003712 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003713 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003714 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3715 else
3716 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003717 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003718
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003719 // Emit target region as a standalone region.
3720 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3721 IsOffloadEntry, CodeGen);
3722 OMPLexicalScope Scope(CGF, S);
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003723 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3724 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003725 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003726 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003727}
3728
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003729static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3730 PrePostActionTy &Action) {
3731 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3732 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3733 CGF.EmitOMPPrivateClause(S, PrivateScope);
3734 (void)PrivateScope.Privatize();
3735
3736 Action.Enter(CGF);
3737 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3738}
3739
3740void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3741 StringRef ParentName,
3742 const OMPTargetDirective &S) {
3743 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3744 emitTargetRegion(CGF, S, Action);
3745 };
3746 llvm::Function *Fn;
3747 llvm::Constant *Addr;
3748 // Emit target region as a standalone region.
3749 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3750 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3751 assert(Fn && Addr && "Target device function emission failed.");
3752}
3753
3754void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3755 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3756 emitTargetRegion(CGF, S, Action);
3757 };
3758 emitCommonOMPTargetDirective(*this, S, CodeGen);
3759}
3760
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003761static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3762 const OMPExecutableDirective &S,
3763 OpenMPDirectiveKind InnermostKind,
3764 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003765 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
3766 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
3767 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003768
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003769 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
3770 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003771 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003772 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3773 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003774
Carlo Bertollic6872252016-04-04 15:55:02 +00003775 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3776 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003777 }
3778
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003779 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003780 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3781 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003782 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3783 CapturedVars);
3784}
3785
3786void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00003787 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003788 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003789 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003790 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3791 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003792 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003793 (void)PrivateScope.Privatize();
3794 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003795 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003796 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00003797 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003798 emitPostUpdateForReductionClause(
3799 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00003800}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003801
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003802static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
3803 const OMPTargetTeamsDirective &S) {
3804 auto *CS = S.getCapturedStmt(OMPD_teams);
3805 Action.Enter(CGF);
3806 auto &&CodeGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3807 // TODO: Add support for clauses.
3808 CGF.EmitStmt(CS->getCapturedStmt());
3809 };
3810 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
3811}
3812
3813void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
3814 CodeGenModule &CGM, StringRef ParentName,
3815 const OMPTargetTeamsDirective &S) {
3816 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3817 emitTargetTeamsRegion(CGF, Action, S);
3818 };
3819 llvm::Function *Fn;
3820 llvm::Constant *Addr;
3821 // Emit target region as a standalone region.
3822 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3823 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3824 assert(Fn && Addr && "Target device function emission failed.");
3825}
3826
3827void CodeGenFunction::EmitOMPTargetTeamsDirective(
3828 const OMPTargetTeamsDirective &S) {
3829 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3830 emitTargetTeamsRegion(CGF, Action, S);
3831 };
3832 emitCommonOMPTargetDirective(*this, S, CodeGen);
3833}
3834
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003835void CodeGenFunction::EmitOMPTeamsDistributeDirective(
3836 const OMPTeamsDistributeDirective &S) {
3837
3838 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3839 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
3840 };
3841
3842 // Emit teams region as a standalone region.
3843 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
3844 PrePostActionTy &) {
3845 OMPPrivateScope PrivateScope(CGF);
3846 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3847 (void)PrivateScope.Privatize();
3848 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
3849 CodeGenDistribute);
3850 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3851 };
3852 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
3853 emitPostUpdateForReductionClause(*this, S,
3854 [](CodeGenFunction &) { return nullptr; });
3855}
3856
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003857void CodeGenFunction::EmitOMPCancellationPointDirective(
3858 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00003859 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
3860 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003861}
3862
Alexey Bataev80909872015-07-02 11:25:17 +00003863void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003864 const Expr *IfCond = nullptr;
3865 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3866 if (C->getNameModifier() == OMPD_unknown ||
3867 C->getNameModifier() == OMPD_cancel) {
3868 IfCond = C->getCondition();
3869 break;
3870 }
3871 }
3872 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003873 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00003874}
3875
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003876CodeGenFunction::JumpDest
3877CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00003878 if (Kind == OMPD_parallel || Kind == OMPD_task ||
3879 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003880 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003881 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00003882 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
3883 Kind == OMPD_distribute_parallel_for ||
3884 Kind == OMPD_target_parallel_for);
3885 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003886}
Michael Wong65f367f2015-07-21 13:44:28 +00003887
Samuel Antaocc10b852016-07-28 14:23:26 +00003888void CodeGenFunction::EmitOMPUseDevicePtrClause(
3889 const OMPClause &NC, OMPPrivateScope &PrivateScope,
3890 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
3891 const auto &C = cast<OMPUseDevicePtrClause>(NC);
3892 auto OrigVarIt = C.varlist_begin();
3893 auto InitIt = C.inits().begin();
3894 for (auto PvtVarIt : C.private_copies()) {
3895 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
3896 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
3897 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
3898
3899 // In order to identify the right initializer we need to match the
3900 // declaration used by the mapping logic. In some cases we may get
3901 // OMPCapturedExprDecl that refers to the original declaration.
3902 const ValueDecl *MatchingVD = OrigVD;
3903 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
3904 // OMPCapturedExprDecl are used to privative fields of the current
3905 // structure.
3906 auto *ME = cast<MemberExpr>(OED->getInit());
3907 assert(isa<CXXThisExpr>(ME->getBase()) &&
3908 "Base should be the current struct!");
3909 MatchingVD = ME->getMemberDecl();
3910 }
3911
3912 // If we don't have information about the current list item, move on to
3913 // the next one.
3914 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
3915 if (InitAddrIt == CaptureDeviceAddrMap.end())
3916 continue;
3917
3918 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
3919 // Initialize the temporary initialization variable with the address we
3920 // get from the runtime library. We have to cast the source address
3921 // because it is always a void *. References are materialized in the
3922 // privatization scope, so the initialization here disregards the fact
3923 // the original variable is a reference.
3924 QualType AddrQTy =
3925 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
3926 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
3927 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
3928 setAddrOfLocalVar(InitVD, InitAddr);
3929
3930 // Emit private declaration, it will be initialized by the value we
3931 // declaration we just added to the local declarations map.
3932 EmitDecl(*PvtVD);
3933
3934 // The initialization variables reached its purpose in the emission
3935 // ofthe previous declaration, so we don't need it anymore.
3936 LocalDeclMap.erase(InitVD);
3937
3938 // Return the address of the private variable.
3939 return GetAddrOfLocalVar(PvtVD);
3940 });
3941 assert(IsRegistered && "firstprivate var already registered as private");
3942 // Silence the warning about unused variable.
3943 (void)IsRegistered;
3944
3945 ++OrigVarIt;
3946 ++InitIt;
3947 }
3948}
3949
Michael Wong65f367f2015-07-21 13:44:28 +00003950// Generate the instructions for '#pragma omp target data' directive.
3951void CodeGenFunction::EmitOMPTargetDataDirective(
3952 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00003953 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
3954
3955 // Create a pre/post action to signal the privatization of the device pointer.
3956 // This action can be replaced by the OpenMP runtime code generation to
3957 // deactivate privatization.
3958 bool PrivatizeDevicePointers = false;
3959 class DevicePointerPrivActionTy : public PrePostActionTy {
3960 bool &PrivatizeDevicePointers;
3961
3962 public:
3963 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
3964 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
3965 void Enter(CodeGenFunction &CGF) override {
3966 PrivatizeDevicePointers = true;
3967 }
Samuel Antaodf158d52016-04-27 22:58:19 +00003968 };
Samuel Antaocc10b852016-07-28 14:23:26 +00003969 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
3970
3971 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
3972 CodeGenFunction &CGF, PrePostActionTy &Action) {
3973 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3974 CGF.EmitStmt(
3975 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3976 };
3977
3978 // Codegen that selects wheather to generate the privatization code or not.
3979 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
3980 &InnermostCodeGen](CodeGenFunction &CGF,
3981 PrePostActionTy &Action) {
3982 RegionCodeGenTy RCG(InnermostCodeGen);
3983 PrivatizeDevicePointers = false;
3984
3985 // Call the pre-action to change the status of PrivatizeDevicePointers if
3986 // needed.
3987 Action.Enter(CGF);
3988
3989 if (PrivatizeDevicePointers) {
3990 OMPPrivateScope PrivateScope(CGF);
3991 // Emit all instances of the use_device_ptr clause.
3992 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
3993 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
3994 Info.CaptureDeviceAddrMap);
3995 (void)PrivateScope.Privatize();
3996 RCG(CGF);
3997 } else
3998 RCG(CGF);
3999 };
4000
4001 // Forward the provided action to the privatization codegen.
4002 RegionCodeGenTy PrivRCG(PrivCodeGen);
4003 PrivRCG.setAction(Action);
4004
4005 // Notwithstanding the body of the region is emitted as inlined directive,
4006 // we don't use an inline scope as changes in the references inside the
4007 // region are expected to be visible outside, so we do not privative them.
4008 OMPLexicalScope Scope(CGF, S);
4009 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4010 PrivRCG);
4011 };
4012
4013 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004014
4015 // If we don't have target devices, don't bother emitting the data mapping
4016 // code.
4017 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004018 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004019 return;
4020 }
4021
4022 // Check if we have any if clause associated with the directive.
4023 const Expr *IfCond = nullptr;
4024 if (auto *C = S.getSingleClause<OMPIfClause>())
4025 IfCond = C->getCondition();
4026
4027 // Check if we have any device clause associated with the directive.
4028 const Expr *Device = nullptr;
4029 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4030 Device = C->getDevice();
4031
Samuel Antaocc10b852016-07-28 14:23:26 +00004032 // Set the action to signal privatization of device pointers.
4033 RCG.setAction(PrivAction);
4034
4035 // Emit region code.
4036 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4037 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004038}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004039
Samuel Antaodf67fc42016-01-19 19:15:56 +00004040void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4041 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004042 // If we don't have target devices, don't bother emitting the data mapping
4043 // code.
4044 if (CGM.getLangOpts().OMPTargetTriples.empty())
4045 return;
4046
4047 // Check if we have any if clause associated with the directive.
4048 const Expr *IfCond = nullptr;
4049 if (auto *C = S.getSingleClause<OMPIfClause>())
4050 IfCond = C->getCondition();
4051
4052 // Check if we have any device clause associated with the directive.
4053 const Expr *Device = nullptr;
4054 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4055 Device = C->getDevice();
4056
Samuel Antao8d2d7302016-05-26 18:30:22 +00004057 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004058}
4059
Samuel Antao72590762016-01-19 20:04:50 +00004060void CodeGenFunction::EmitOMPTargetExitDataDirective(
4061 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004062 // If we don't have target devices, don't bother emitting the data mapping
4063 // code.
4064 if (CGM.getLangOpts().OMPTargetTriples.empty())
4065 return;
4066
4067 // Check if we have any if clause associated with the directive.
4068 const Expr *IfCond = nullptr;
4069 if (auto *C = S.getSingleClause<OMPIfClause>())
4070 IfCond = C->getCondition();
4071
4072 // Check if we have any device clause associated with the directive.
4073 const Expr *Device = nullptr;
4074 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4075 Device = C->getDevice();
4076
Samuel Antao8d2d7302016-05-26 18:30:22 +00004077 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004078}
4079
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004080static void emitTargetParallelRegion(CodeGenFunction &CGF,
4081 const OMPTargetParallelDirective &S,
4082 PrePostActionTy &Action) {
4083 // Get the captured statement associated with the 'parallel' region.
4084 auto *CS = S.getCapturedStmt(OMPD_parallel);
4085 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004086 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
4087 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4088 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4089 CGF.EmitOMPPrivateClause(S, PrivateScope);
4090 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4091 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004092 // TODO: Add support for clauses.
4093 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004094 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004095 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004096 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4097 emitEmptyBoundParameters);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004098 emitPostUpdateForReductionClause(
4099 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004100}
4101
4102void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4103 CodeGenModule &CGM, StringRef ParentName,
4104 const OMPTargetParallelDirective &S) {
4105 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4106 emitTargetParallelRegion(CGF, S, Action);
4107 };
4108 llvm::Function *Fn;
4109 llvm::Constant *Addr;
4110 // Emit target region as a standalone region.
4111 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4112 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4113 assert(Fn && Addr && "Target device function emission failed.");
4114}
4115
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004116void CodeGenFunction::EmitOMPTargetParallelDirective(
4117 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004118 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4119 emitTargetParallelRegion(CGF, S, Action);
4120 };
4121 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004122}
4123
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004124static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4125 const OMPTargetParallelForDirective &S,
4126 PrePostActionTy &Action) {
4127 Action.Enter(CGF);
4128 // Emit directive as a combined directive that consists of two implicit
4129 // directives: 'parallel' with 'for' directive.
4130 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev2139ed62017-11-16 18:20:21 +00004131 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4132 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004133 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4134 emitDispatchForLoopBounds);
4135 };
4136 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4137 emitEmptyBoundParameters);
4138}
4139
4140void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4141 CodeGenModule &CGM, StringRef ParentName,
4142 const OMPTargetParallelForDirective &S) {
4143 // Emit SPMD target parallel for region as a standalone region.
4144 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4145 emitTargetParallelForRegion(CGF, S, Action);
4146 };
4147 llvm::Function *Fn;
4148 llvm::Constant *Addr;
4149 // Emit target region as a standalone region.
4150 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4151 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4152 assert(Fn && Addr && "Target device function emission failed.");
4153}
4154
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004155void CodeGenFunction::EmitOMPTargetParallelForDirective(
4156 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004157 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4158 emitTargetParallelForRegion(CGF, S, Action);
4159 };
4160 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004161}
4162
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004163static void
4164emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4165 const OMPTargetParallelForSimdDirective &S,
4166 PrePostActionTy &Action) {
4167 Action.Enter(CGF);
4168 // Emit directive as a combined directive that consists of two implicit
4169 // directives: 'parallel' with 'for' directive.
4170 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4171 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4172 emitDispatchForLoopBounds);
4173 };
4174 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4175 emitEmptyBoundParameters);
4176}
4177
4178void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4179 CodeGenModule &CGM, StringRef ParentName,
4180 const OMPTargetParallelForSimdDirective &S) {
4181 // Emit SPMD target parallel for region as a standalone region.
4182 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4183 emitTargetParallelForSimdRegion(CGF, S, Action);
4184 };
4185 llvm::Function *Fn;
4186 llvm::Constant *Addr;
4187 // Emit target region as a standalone region.
4188 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4189 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4190 assert(Fn && Addr && "Target device function emission failed.");
4191}
4192
4193void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4194 const OMPTargetParallelForSimdDirective &S) {
4195 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4196 emitTargetParallelForSimdRegion(CGF, S, Action);
4197 };
4198 emitCommonOMPTargetDirective(*this, S, CodeGen);
4199}
4200
Alexey Bataev7292c292016-04-25 12:22:29 +00004201/// Emit a helper variable and return corresponding lvalue.
4202static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4203 const ImplicitParamDecl *PVD,
4204 CodeGenFunction::OMPPrivateScope &Privates) {
4205 auto *VDecl = cast<VarDecl>(Helper->getDecl());
4206 Privates.addPrivate(
4207 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
4208}
4209
4210void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4211 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4212 // Emit outlined function for task construct.
4213 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
4214 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
4215 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4216 const Expr *IfCond = nullptr;
4217 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4218 if (C->getNameModifier() == OMPD_unknown ||
4219 C->getNameModifier() == OMPD_taskloop) {
4220 IfCond = C->getCondition();
4221 break;
4222 }
4223 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004224
4225 OMPTaskDataTy Data;
4226 // Check if taskloop must be emitted without taskgroup.
4227 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004228 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004229 Data.Tied = true;
4230 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004231 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4232 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004233 Data.Schedule.setInt(/*IntVal=*/false);
4234 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004235 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4236 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004237 Data.Schedule.setInt(/*IntVal=*/true);
4238 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004239 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004240
4241 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4242 // if (PreCond) {
4243 // for (IV in 0..LastIteration) BODY;
4244 // <Final counter/linear vars updates>;
4245 // }
4246 //
4247
4248 // Emit: if (PreCond) - begin.
4249 // If the condition constant folds and can be elided, avoid emitting the
4250 // whole loop.
4251 bool CondConstant;
4252 llvm::BasicBlock *ContBlock = nullptr;
4253 OMPLoopScope PreInitScope(CGF, S);
4254 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4255 if (!CondConstant)
4256 return;
4257 } else {
4258 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4259 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4260 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4261 CGF.getProfileCount(&S));
4262 CGF.EmitBlock(ThenBlock);
4263 CGF.incrementProfileCounter(&S);
4264 }
4265
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004266 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4267 CGF.EmitOMPSimdInit(S);
4268
Alexey Bataev7292c292016-04-25 12:22:29 +00004269 OMPPrivateScope LoopScope(CGF);
4270 // Emit helper vars inits.
4271 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4272 auto *I = CS->getCapturedDecl()->param_begin();
4273 auto *LBP = std::next(I, LowerBound);
4274 auto *UBP = std::next(I, UpperBound);
4275 auto *STP = std::next(I, Stride);
4276 auto *LIP = std::next(I, LastIter);
4277 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4278 LoopScope);
4279 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4280 LoopScope);
4281 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4282 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4283 LoopScope);
4284 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004285 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004286 (void)LoopScope.Privatize();
4287 // Emit the loop iteration variable.
4288 const Expr *IVExpr = S.getIterationVariable();
4289 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4290 CGF.EmitVarDecl(*IVDecl);
4291 CGF.EmitIgnoredExpr(S.getInit());
4292
4293 // Emit the iterations count variable.
4294 // If it is not a variable, Sema decided to calculate iterations count on
4295 // each iteration (e.g., it is foldable into a constant).
4296 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4297 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4298 // Emit calculation of the iterations count.
4299 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4300 }
4301
4302 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4303 S.getInc(),
4304 [&S](CodeGenFunction &CGF) {
4305 CGF.EmitOMPLoopBody(S, JumpDest());
4306 CGF.EmitStopPoint(&S);
4307 },
4308 [](CodeGenFunction &) {});
4309 // Emit: if (PreCond) - end.
4310 if (ContBlock) {
4311 CGF.EmitBranch(ContBlock);
4312 CGF.EmitBlock(ContBlock, true);
4313 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004314 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4315 if (HasLastprivateClause) {
4316 CGF.EmitOMPLastprivateClauseFinal(
4317 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4318 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4319 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4320 (*LIP)->getType(), S.getLocStart())));
4321 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004322 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004323 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4324 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4325 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004326 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4327 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004328 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4329 OutlinedFn, SharedsTy,
4330 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004331 };
4332 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4333 CodeGen);
4334 };
Alexey Bataev33446032017-07-12 18:09:32 +00004335 if (Data.Nogroup)
4336 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4337 else {
4338 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4339 *this,
4340 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4341 PrePostActionTy &Action) {
4342 Action.Enter(CGF);
4343 CGF.EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4344 },
4345 S.getLocStart());
4346 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004347}
4348
Alexey Bataev49f6e782015-12-01 04:18:41 +00004349void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004350 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004351}
4352
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004353void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4354 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004355 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004356}
Samuel Antao686c70c2016-05-26 17:30:50 +00004357
4358// Generate the instructions for '#pragma omp target update' directive.
4359void CodeGenFunction::EmitOMPTargetUpdateDirective(
4360 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00004361 // If we don't have target devices, don't bother emitting the data mapping
4362 // code.
4363 if (CGM.getLangOpts().OMPTargetTriples.empty())
4364 return;
4365
4366 // Check if we have any if clause associated with the directive.
4367 const Expr *IfCond = nullptr;
4368 if (auto *C = S.getSingleClause<OMPIfClause>())
4369 IfCond = C->getCondition();
4370
4371 // Check if we have any device clause associated with the directive.
4372 const Expr *Device = nullptr;
4373 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4374 Device = C->getDevice();
4375
4376 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00004377}