blob: ad4b6e5e11efc0e817fa43cb2cdc3c1ee60e64ec [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();
68 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
69 isCapturedVar(CGF, VD) ||
70 (CGF.CapturedStmtInfo &&
71 InlinedShareds.isGlobalVarCaptured(VD)),
72 VD->getType().getNonReferenceType(), VK_LValue,
73 SourceLocation());
74 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
75 return CGF.EmitLValue(&DRE).getAddress();
76 });
77 }
78 }
79 (void)InlinedShareds.Privatize();
80 }
81 }
Alexey Bataev3392d762016-02-16 11:18:12 +000082 }
83};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000084
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000085/// Lexical scope for OpenMP parallel construct, that handles correct codegen
86/// for captured expressions.
87class OMPParallelScope final : public OMPLexicalScope {
88 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
89 OpenMPDirectiveKind Kind = S.getDirectiveKind();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +000090 return !(isOpenMPTargetExecutionDirective(Kind) ||
91 isOpenMPLoopBoundSharingDirective(Kind)) &&
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000092 isOpenMPParallelDirective(Kind);
93 }
94
95public:
96 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
97 : OMPLexicalScope(CGF, S,
98 /*AsInlined=*/false,
99 /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
100};
101
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000102/// Lexical scope for OpenMP teams construct, that handles correct codegen
103/// for captured expressions.
104class OMPTeamsScope final : public OMPLexicalScope {
105 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
106 OpenMPDirectiveKind Kind = S.getDirectiveKind();
107 return !isOpenMPTargetExecutionDirective(Kind) &&
108 isOpenMPTeamsDirective(Kind);
109 }
110
111public:
112 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
113 : OMPLexicalScope(CGF, S,
114 /*AsInlined=*/false,
115 /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
116};
117
Alexey Bataev5a3af132016-03-29 08:58:54 +0000118/// Private scope for OpenMP loop-based directives, that supports capturing
119/// of used expression from loop statement.
120class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
121 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
122 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
123 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
124 for (const auto *I : PreInits->decls())
125 CGF.EmitVarDecl(cast<VarDecl>(*I));
126 }
127 }
128 }
129
130public:
131 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
132 : CodeGenFunction::RunCleanupsScope(CGF) {
133 emitPreInitStmt(CGF, S);
134 }
135};
136
Alexey Bataev3392d762016-02-16 11:18:12 +0000137} // namespace
138
Alexey Bataev1189bd02016-01-26 12:20:39 +0000139llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
140 auto &C = getContext();
141 llvm::Value *Size = nullptr;
142 auto SizeInChars = C.getTypeSizeInChars(Ty);
143 if (SizeInChars.isZero()) {
144 // getTypeSizeInChars() returns 0 for a VLA.
145 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
146 llvm::Value *ArraySize;
147 std::tie(ArraySize, Ty) = getVLASize(VAT);
148 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
149 }
150 SizeInChars = C.getTypeSizeInChars(Ty);
151 if (SizeInChars.isZero())
152 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
153 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
154 } else
155 Size = CGM.getSize(SizeInChars);
156 return Size;
157}
158
Alexey Bataev2377fe92015-09-10 08:12:02 +0000159void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000160 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000161 const RecordDecl *RD = S.getCapturedRecordDecl();
162 auto CurField = RD->field_begin();
163 auto CurCap = S.captures().begin();
164 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
165 E = S.capture_init_end();
166 I != E; ++I, ++CurField, ++CurCap) {
167 if (CurField->hasCapturedVLAType()) {
168 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000169 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000170 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000171 } else if (CurCap->capturesThis())
172 CapturedVars.push_back(CXXThisValue);
Samuel Antao6d004262016-06-16 18:39:34 +0000173 else if (CurCap->capturesVariableByCopy()) {
174 llvm::Value *CV =
175 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal();
176
177 // If the field is not a pointer, we need to save the actual value
178 // and load it as a void pointer.
179 if (!CurField->getType()->isAnyPointerType()) {
180 auto &Ctx = getContext();
181 auto DstAddr = CreateMemTemp(
182 Ctx.getUIntPtrType(),
183 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
184 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
185
186 auto *SrcAddrVal = EmitScalarConversion(
187 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
188 Ctx.getPointerType(CurField->getType()), SourceLocation());
189 LValue SrcLV =
190 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
191
192 // Store the value using the source type pointer.
193 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
194
195 // Load the value using the destination type pointer.
196 CV = EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
197 }
198 CapturedVars.push_back(CV);
199 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000200 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000201 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000202 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000203 }
204}
205
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000206static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
207 StringRef Name, LValue AddrLV,
208 bool isReferenceType = false) {
209 ASTContext &Ctx = CGF.getContext();
210
211 auto *CastedPtr = CGF.EmitScalarConversion(
212 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
213 Ctx.getPointerType(DstType), SourceLocation());
214 auto TmpAddr =
215 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
216 .getAddress();
217
218 // If we are dealing with references we need to return the address of the
219 // reference instead of the reference of the value.
220 if (isReferenceType) {
221 QualType RefType = Ctx.getLValueReferenceType(DstType);
222 auto *RefVal = TmpAddr.getPointer();
223 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
224 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
Akira Hatanaka642f7992016-10-18 19:05:41 +0000225 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000226 }
227
228 return TmpAddr;
229}
230
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000231static QualType getCanonicalParamType(ASTContext &C, QualType T) {
232 if (T->isLValueReferenceType()) {
233 return C.getLValueReferenceType(
234 getCanonicalParamType(C, T.getNonReferenceType()),
235 /*SpelledAsLValue=*/false);
236 }
237 if (T->isPointerType())
238 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
239 return C.getCanonicalParamType(T);
240}
241
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000242namespace {
243 /// Contains required data for proper outlined function codegen.
244 struct FunctionOptions {
245 /// Captured statement for which the function is generated.
246 const CapturedStmt *S = nullptr;
247 /// true if cast to/from UIntPtr is required for variables captured by
248 /// value.
249 bool UIntPtrCastRequired = true;
250 /// true if only casted argumefnts must be registered as local args or VLA
251 /// sizes.
252 bool RegisterCastedArgsOnly = false;
253 /// Name of the generated function.
254 StringRef FunctionName;
255 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
256 bool RegisterCastedArgsOnly,
257 StringRef FunctionName)
258 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
259 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
260 FunctionName(FunctionName) {}
261 };
262}
263
264static std::pair<llvm::Function *, bool> emitOutlinedFunctionPrologue(
265 CodeGenFunction &CGF, FunctionArgList &Args,
266 llvm::DenseMap<const Decl *, std::pair<const VarDecl *, Address>>
267 &LocalAddrs,
268 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
269 &VLASizes,
270 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
271 const CapturedDecl *CD = FO.S->getCapturedDecl();
272 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000273 assert(CD->hasBody() && "missing CapturedDecl body");
274
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000275 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000276 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000277 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000278 ASTContext &Ctx = CGM.getContext();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000279 bool HasUIntPtrArgs = false;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000280 Args.append(CD->param_begin(),
281 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000282 auto I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000283 for (auto *FD : RD->fields()) {
284 QualType ArgType = FD->getType();
285 IdentifierInfo *II = nullptr;
286 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000287
288 // If this is a capture by copy and the type is not a pointer, the outlined
289 // function argument type should be uintptr and the value properly casted to
290 // uintptr. This is necessary given that the runtime library is only able to
291 // deal with pointers. We can pass in the same way the VLA type sizes to the
292 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000293 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000294 I->capturesVariableArrayType()) {
295 HasUIntPtrArgs = true;
296 if (FO.UIntPtrCastRequired)
297 ArgType = Ctx.getUIntPtrType();
298 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000299
300 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000301 CapVar = I->getCapturedVar();
302 II = CapVar->getIdentifier();
303 } else if (I->capturesThis())
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000304 II = &Ctx.Idents.get("this");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000305 else {
306 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000307 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000308 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000309 if (ArgType->isVariablyModifiedType())
310 ArgType = getCanonicalParamType(Ctx, ArgType.getNonReferenceType());
311 Args.push_back(ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +0000312 FD->getLocation(), II, ArgType,
313 ImplicitParamDecl::Other));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000314 ++I;
315 }
316 Args.append(
317 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
318 CD->param_end());
319
320 // Create the function declaration.
321 FunctionType::ExtInfo ExtInfo;
322 const CGFunctionInfo &FuncInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000323 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000324 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
325
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000326 llvm::Function *F =
327 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
328 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000329 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
330 if (CD->isNothrow())
331 F->addFnAttr(llvm::Attribute::NoUnwind);
332
333 // Generate the function.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000334 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
335 CD->getBody()->getLocStart());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000336 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000337 I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000338 for (auto *FD : RD->fields()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000339 // If we are capturing a pointer by copy we don't need to do anything, just
340 // use the value that we get from the arguments.
341 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000342 const VarDecl *CurVD = I->getCapturedVar();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000343 Address LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
Samuel Antao403ffd42016-07-27 22:49:49 +0000344 // If the variable is a reference we need to materialize it here.
345 if (CurVD->getType()->isReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000346 Address RefAddr = CGF.CreateMemTemp(
347 CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
348 CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
349 /*Volatile=*/false, CurVD->getType());
Samuel Antao403ffd42016-07-27 22:49:49 +0000350 LocalAddr = RefAddr;
351 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000352 if (!FO.RegisterCastedArgsOnly)
353 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000354 ++Cnt;
355 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000356 continue;
357 }
358
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000359 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000360 LValue ArgLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(Args[Cnt]),
361 Args[Cnt]->getType(), BaseInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000362 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000363 if (FO.UIntPtrCastRequired) {
364 ArgLVal = CGF.MakeAddrLValue(castValueFromUintptr(CGF, FD->getType(),
365 Args[Cnt]->getName(),
366 ArgLVal),
367 FD->getType(), BaseInfo);
368 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000369 auto *ExprArg =
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000370 CGF.EmitLoadOfLValue(ArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000371 auto VAT = FD->getCapturedVLAType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000372 VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000373 } else if (I->capturesVariable()) {
374 auto *Var = I->getCapturedVar();
375 QualType VarTy = Var->getType();
376 Address ArgAddr = ArgLVal.getAddress();
377 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000378 if (ArgLVal.getType()->isLValueReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000379 ArgAddr = CGF.EmitLoadOfReference(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000380 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000381 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000382 assert(ArgLVal.getType()->isPointerType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000383 ArgAddr = CGF.EmitLoadOfPointer(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000384 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
385 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000386 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000387 if (!FO.RegisterCastedArgsOnly) {
388 LocalAddrs.insert(
389 {Args[Cnt],
390 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
391 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000392 } else if (I->capturesVariableByCopy()) {
393 assert(!FD->getType()->isAnyPointerType() &&
394 "Not expecting a captured pointer.");
395 auto *Var = I->getCapturedVar();
396 QualType VarTy = Var->getType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000397 LocalAddrs.insert(
398 {Args[Cnt],
399 {Var,
400 FO.UIntPtrCastRequired
401 ? castValueFromUintptr(CGF, FD->getType(), Args[Cnt]->getName(),
402 ArgLVal, VarTy->isReferenceType())
403 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000404 } else {
405 // If 'this' is captured, load it into CXXThisValue.
406 assert(I->capturesThis());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000407 CXXThisValue = CGF.EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation())
408 .getScalarVal();
409 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000410 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000411 ++Cnt;
412 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000413 }
414
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000415 return {F, HasUIntPtrArgs};
416}
417
418llvm::Function *
419CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
420 assert(
421 CapturedStmtInfo &&
422 "CapturedStmtInfo should be set when generating the captured function");
423 const CapturedDecl *CD = S.getCapturedDecl();
424 // Build the argument list.
425 bool NeedWrapperFunction =
426 getDebugInfo() &&
427 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
428 FunctionArgList Args;
429 llvm::DenseMap<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
430 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
431 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
432 CapturedStmtInfo->getHelperName());
433 llvm::Function *F;
434 bool HasUIntPtrArgs;
435 std::tie(F, HasUIntPtrArgs) = emitOutlinedFunctionPrologue(
436 *this, Args, LocalAddrs, VLASizes, CXXThisValue, FO);
437 for (const auto &LocalAddrPair : LocalAddrs) {
438 if (LocalAddrPair.second.first) {
439 setAddrOfLocalVar(LocalAddrPair.second.first,
440 LocalAddrPair.second.second);
441 }
442 }
443 for (const auto &VLASizePair : VLASizes)
444 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000445 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000446 CapturedStmtInfo->EmitBody(*this, CD->getBody());
447 FinishFunction(CD->getBodyRBrace());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000448 if (!NeedWrapperFunction || !HasUIntPtrArgs)
449 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000450
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000451 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
452 /*RegisterCastedArgsOnly=*/true,
453 ".nondebug_wrapper.");
454 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
455 WrapperCGF.disableDebugInfo();
456 Args.clear();
457 LocalAddrs.clear();
458 VLASizes.clear();
459 llvm::Function *WrapperF =
460 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
461 WrapperCGF.CXXThisValue, WrapperFO).first;
462 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
463 llvm::SmallVector<llvm::Value *, 4> CallArgs;
464 for (const auto *Arg : Args) {
465 llvm::Value *CallArg;
466 auto I = LocalAddrs.find(Arg);
467 if (I != LocalAddrs.end()) {
468 LValue LV =
469 WrapperCGF.MakeAddrLValue(I->second.second, Arg->getType(), BaseInfo);
470 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
471 } else {
472 auto EI = VLASizes.find(Arg);
473 if (EI != VLASizes.end())
474 CallArg = EI->second.second;
475 else {
476 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
477 Arg->getType(), BaseInfo);
478 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
479 }
480 }
481 CallArgs.emplace_back(CallArg);
482 }
483 WrapperCGF.Builder.CreateCall(F, CallArgs);
484 WrapperCGF.FinishFunction();
485 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000486}
487
Alexey Bataev9959db52014-05-06 10:08:46 +0000488//===----------------------------------------------------------------------===//
489// OpenMP Directive Emission
490//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000491void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000492 Address DestAddr, Address SrcAddr, QualType OriginalType,
493 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000494 // Perform element-by-element initialization.
495 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000496
497 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000498 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000499 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
500 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
501
502 auto SrcBegin = SrcAddr.getPointer();
503 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000504 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000505 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
506 // The basic structure here is a while-do loop.
507 auto BodyBB = createBasicBlock("omp.arraycpy.body");
508 auto DoneBB = createBasicBlock("omp.arraycpy.done");
509 auto IsEmpty =
510 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
511 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000512
Alexey Bataev420d45b2015-04-14 05:11:24 +0000513 // Enter the loop body, making that address the current address.
514 auto EntryBB = Builder.GetInsertBlock();
515 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000516
517 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
518
519 llvm::PHINode *SrcElementPHI =
520 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
521 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
522 Address SrcElementCurrent =
523 Address(SrcElementPHI,
524 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
525
526 llvm::PHINode *DestElementPHI =
527 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
528 DestElementPHI->addIncoming(DestBegin, EntryBB);
529 Address DestElementCurrent =
530 Address(DestElementPHI,
531 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000532
Alexey Bataev420d45b2015-04-14 05:11:24 +0000533 // Emit copy.
534 CopyGen(DestElementCurrent, SrcElementCurrent);
535
536 // Shift the address forward by one element.
537 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000538 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000539 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000540 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000541 // Check whether we've reached the end.
542 auto Done =
543 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
544 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000545 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
546 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000547
548 // Done.
549 EmitBlock(DoneBB, /*IsFinished=*/true);
550}
551
John McCall7f416cc2015-09-08 08:05:57 +0000552void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
553 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000554 const VarDecl *SrcVD, const Expr *Copy) {
555 if (OriginalType->isArrayType()) {
556 auto *BO = dyn_cast<BinaryOperator>(Copy);
557 if (BO && BO->getOpcode() == BO_Assign) {
558 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000559 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000560 } else {
561 // For arrays with complex element types perform element by element
562 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000563 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000564 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000565 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000566 // Working with the single array element, so have to remap
567 // destination and source variables to corresponding array
568 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000569 CodeGenFunction::OMPPrivateScope Remap(*this);
570 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000571 return DestElement;
572 });
573 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000574 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000575 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000576 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000577 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000578 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000579 } else {
580 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000581 CodeGenFunction::OMPPrivateScope Remap(*this);
582 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
583 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000584 (void)Remap.Privatize();
585 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000586 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000587 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000588}
589
Alexey Bataev69c62a92015-04-15 04:52:20 +0000590bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
591 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000592 if (!HaveInsertPoint())
593 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000594 bool FirstprivateIsLastprivate = false;
595 llvm::DenseSet<const VarDecl *> Lastprivates;
596 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
597 for (const auto *D : C->varlists())
598 Lastprivates.insert(
599 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
600 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000601 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000602 CGCapturedStmtInfo CapturesInfo(cast<CapturedStmt>(*D.getAssociatedStmt()));
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000603 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000604 auto IRef = C->varlist_begin();
605 auto InitsRef = C->inits().begin();
606 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000607 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000608 bool ThisFirstprivateIsLastprivate =
609 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000610 auto *CapFD = CapturesInfo.lookup(OrigVD);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000611 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9afe5752016-05-24 07:40:12 +0000612 if (!ThisFirstprivateIsLastprivate && FD && (FD == CapFD) &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000613 !FD->getType()->isReferenceType()) {
614 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
615 ++IRef;
616 ++InitsRef;
617 continue;
618 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000619 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000620 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000621 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000622 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
623 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
624 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000625 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
626 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
627 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000628 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000629 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000630 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000631 // Emit VarDecl with copy init for arrays.
632 // Get the address of the original variable captured in current
633 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000634 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000635 auto Emission = EmitAutoVarAlloca(*VD);
636 auto *Init = VD->getInit();
637 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
638 // Perform simple memcpy.
639 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000640 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000641 } else {
642 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000643 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000644 [this, VDInit, Init](Address DestElement,
645 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000646 // Clean up any temporaries needed by the initialization.
647 RunCleanupsScope InitScope(*this);
648 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000649 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000650 EmitAnyExprToMem(Init, DestElement,
651 Init->getType().getQualifiers(),
652 /*IsInitializer*/ false);
653 LocalDeclMap.erase(VDInit);
654 });
655 }
656 EmitAutoVarCleanups(Emission);
657 return Emission.getAllocatedAddress();
658 });
659 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000660 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000661 // Emit private VarDecl with copy init.
662 // Remap temp VDInit variable to the address of the original
663 // variable
664 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000665 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000666 EmitDecl(*VD);
667 LocalDeclMap.erase(VDInit);
668 return GetAddrOfLocalVar(VD);
669 });
670 }
671 assert(IsRegistered &&
672 "firstprivate var already registered as private");
673 // Silence the warning about unused variable.
674 (void)IsRegistered;
675 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000676 ++IRef;
677 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000678 }
679 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000680 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000681}
682
Alexey Bataev03b340a2014-10-21 03:16:40 +0000683void CodeGenFunction::EmitOMPPrivateClause(
684 const OMPExecutableDirective &D,
685 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000686 if (!HaveInsertPoint())
687 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000688 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000689 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000690 auto IRef = C->varlist_begin();
691 for (auto IInit : C->private_copies()) {
692 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000693 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
694 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
695 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000696 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000697 // Emit private VarDecl with copy init.
698 EmitDecl(*VD);
699 return GetAddrOfLocalVar(VD);
700 });
701 assert(IsRegistered && "private var already registered as private");
702 // Silence the warning about unused variable.
703 (void)IsRegistered;
704 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000705 ++IRef;
706 }
707 }
708}
709
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000710bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000711 if (!HaveInsertPoint())
712 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000713 // threadprivate_var1 = master_threadprivate_var1;
714 // operator=(threadprivate_var2, master_threadprivate_var2);
715 // ...
716 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000717 llvm::DenseSet<const VarDecl *> CopiedVars;
718 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000719 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000720 auto IRef = C->varlist_begin();
721 auto ISrcRef = C->source_exprs().begin();
722 auto IDestRef = C->destination_exprs().begin();
723 for (auto *AssignOp : C->assignment_ops()) {
724 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000725 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000726 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000727 // Get the address of the master variable. If we are emitting code with
728 // TLS support, the address is passed from the master as field in the
729 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000730 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000731 if (getLangOpts().OpenMPUseTLS &&
732 getContext().getTargetInfo().isTLSSupported()) {
733 assert(CapturedStmtInfo->lookup(VD) &&
734 "Copyin threadprivates should have been captured!");
735 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
736 VK_LValue, (*IRef)->getExprLoc());
737 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000738 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000739 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000740 MasterAddr =
741 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
742 : CGM.GetAddrOfGlobal(VD),
743 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000744 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000745 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000746 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000747 if (CopiedVars.size() == 1) {
748 // At first check if current thread is a master thread. If it is, no
749 // need to copy data.
750 CopyBegin = createBasicBlock("copyin.not.master");
751 CopyEnd = createBasicBlock("copyin.not.master.end");
752 Builder.CreateCondBr(
753 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000754 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
755 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000756 CopyBegin, CopyEnd);
757 EmitBlock(CopyBegin);
758 }
759 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
760 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000761 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000762 }
763 ++IRef;
764 ++ISrcRef;
765 ++IDestRef;
766 }
767 }
768 if (CopyEnd) {
769 // Exit out of copying procedure for non-master thread.
770 EmitBlock(CopyEnd, /*IsFinished=*/true);
771 return true;
772 }
773 return false;
774}
775
Alexey Bataev38e89532015-04-16 04:54:05 +0000776bool CodeGenFunction::EmitOMPLastprivateClauseInit(
777 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000778 if (!HaveInsertPoint())
779 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000780 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000781 llvm::DenseSet<const VarDecl *> SIMDLCVs;
782 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
783 auto *LoopDirective = cast<OMPLoopDirective>(&D);
784 for (auto *C : LoopDirective->counters()) {
785 SIMDLCVs.insert(
786 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
787 }
788 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000789 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000790 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000791 HasAtLeastOneLastprivate = true;
Alexey Bataevf93095a2016-05-05 08:46:22 +0000792 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()))
793 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000794 auto IRef = C->varlist_begin();
795 auto IDestRef = C->destination_exprs().begin();
796 for (auto *IInit : C->private_copies()) {
797 // Keep the address of the original variable for future update at the end
798 // of the loop.
799 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000800 // Taskloops do not require additional initialization, it is done in
801 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000802 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
803 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000804 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000805 DeclRefExpr DRE(
806 const_cast<VarDecl *>(OrigVD),
807 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
808 OrigVD) != nullptr,
809 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
810 return EmitLValue(&DRE).getAddress();
811 });
812 // Check if the variable is also a firstprivate: in this case IInit is
813 // not generated. Initialization of this variable will happen in codegen
814 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000815 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000816 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000817 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
818 // Emit private VarDecl with copy init.
819 EmitDecl(*VD);
820 return GetAddrOfLocalVar(VD);
821 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000822 assert(IsRegistered &&
823 "lastprivate var already registered as private");
824 (void)IsRegistered;
825 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000826 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000827 ++IRef;
828 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000829 }
830 }
831 return HasAtLeastOneLastprivate;
832}
833
834void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000835 const OMPExecutableDirective &D, bool NoFinals,
836 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000837 if (!HaveInsertPoint())
838 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000839 // Emit following code:
840 // if (<IsLastIterCond>) {
841 // orig_var1 = private_orig_var1;
842 // ...
843 // orig_varn = private_orig_varn;
844 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000845 llvm::BasicBlock *ThenBB = nullptr;
846 llvm::BasicBlock *DoneBB = nullptr;
847 if (IsLastIterCond) {
848 ThenBB = createBasicBlock(".omp.lastprivate.then");
849 DoneBB = createBasicBlock(".omp.lastprivate.done");
850 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
851 EmitBlock(ThenBB);
852 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000853 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
854 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000855 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000856 auto IC = LoopDirective->counters().begin();
857 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000858 auto *D =
859 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
860 if (NoFinals)
861 AlreadyEmittedVars.insert(D);
862 else
863 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000864 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000865 }
866 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000867 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
868 auto IRef = C->varlist_begin();
869 auto ISrcRef = C->source_exprs().begin();
870 auto IDestRef = C->destination_exprs().begin();
871 for (auto *AssignOp : C->assignment_ops()) {
872 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
873 QualType Type = PrivateVD->getType();
874 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
875 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
876 // If lastprivate variable is a loop control variable for loop-based
877 // directive, update its value before copyin back to original
878 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000879 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
880 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000881 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
882 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
883 // Get the address of the original variable.
884 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
885 // Get the address of the private variable.
886 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
887 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
888 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000889 Address(Builder.CreateLoad(PrivateAddr),
890 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000891 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000892 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000893 ++IRef;
894 ++ISrcRef;
895 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000896 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000897 if (auto *PostUpdate = C->getPostUpdateExpr())
898 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000899 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000900 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000901 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000902}
903
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000904void CodeGenFunction::EmitOMPReductionClauseInit(
905 const OMPExecutableDirective &D,
906 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000907 if (!HaveInsertPoint())
908 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000909 SmallVector<const Expr *, 4> Shareds;
910 SmallVector<const Expr *, 4> Privates;
911 SmallVector<const Expr *, 4> ReductionOps;
912 SmallVector<const Expr *, 4> LHSs;
913 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000914 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000915 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000916 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000917 auto ILHS = C->lhs_exprs().begin();
918 auto IRHS = C->rhs_exprs().begin();
919 for (const auto *Ref : C->varlists()) {
920 Shareds.emplace_back(Ref);
921 Privates.emplace_back(*IPriv);
922 ReductionOps.emplace_back(*IRed);
923 LHSs.emplace_back(*ILHS);
924 RHSs.emplace_back(*IRHS);
925 std::advance(IPriv, 1);
926 std::advance(IRed, 1);
927 std::advance(ILHS, 1);
928 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000929 }
930 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000931 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
932 unsigned Count = 0;
933 auto ILHS = LHSs.begin();
934 auto IRHS = RHSs.begin();
935 auto IPriv = Privates.begin();
936 for (const auto *IRef : Shareds) {
937 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
938 // Emit private VarDecl with reduction init.
939 RedCG.emitSharedLValue(*this, Count);
940 RedCG.emitAggregateType(*this, Count);
941 auto Emission = EmitAutoVarAlloca(*PrivateVD);
942 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
943 RedCG.getSharedLValue(Count),
944 [&Emission](CodeGenFunction &CGF) {
945 CGF.EmitAutoVarInit(Emission);
946 return true;
947 });
948 EmitAutoVarCleanups(Emission);
949 Address BaseAddr = RedCG.adjustPrivateAddress(
950 *this, Count, Emission.getAllocatedAddress());
951 bool IsRegistered = PrivateScope.addPrivate(
952 RedCG.getBaseDecl(Count), [BaseAddr]() -> Address { return BaseAddr; });
953 assert(IsRegistered && "private var already registered as private");
954 // Silence the warning about unused variable.
955 (void)IsRegistered;
956
957 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
958 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Eric Christopher7aba9782017-07-14 01:42:57 +0000959 if (isa<OMPArraySectionExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000960 // Store the address of the original variable associated with the LHS
961 // implicit variable.
962 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
963 return RedCG.getSharedLValue(Count).getAddress();
964 });
965 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
966 return GetAddrOfLocalVar(PrivateVD);
967 });
Eric Christopher7aba9782017-07-14 01:42:57 +0000968 } else if (isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000969 // Store the address of the original variable associated with the LHS
970 // implicit variable.
971 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
972 return RedCG.getSharedLValue(Count).getAddress();
973 });
974 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
975 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
976 ConvertTypeForMem(RHSVD->getType()),
977 "rhs.begin");
978 });
979 } else {
980 QualType Type = PrivateVD->getType();
981 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
982 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
983 // Store the address of the original variable associated with the LHS
984 // implicit variable.
985 if (IsArray) {
986 OriginalAddr = Builder.CreateElementBitCast(
987 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
988 }
989 PrivateScope.addPrivate(
990 LHSVD, [OriginalAddr]() -> Address { return OriginalAddr; });
991 PrivateScope.addPrivate(
992 RHSVD, [this, PrivateVD, RHSVD, IsArray]() -> Address {
993 return IsArray
994 ? Builder.CreateElementBitCast(
995 GetAddrOfLocalVar(PrivateVD),
996 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
997 : GetAddrOfLocalVar(PrivateVD);
998 });
999 }
1000 ++ILHS;
1001 ++IRHS;
1002 ++IPriv;
1003 ++Count;
1004 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001005}
1006
1007void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001008 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001009 if (!HaveInsertPoint())
1010 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001011 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001012 llvm::SmallVector<const Expr *, 8> LHSExprs;
1013 llvm::SmallVector<const Expr *, 8> RHSExprs;
1014 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001015 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001016 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001017 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001018 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001019 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1020 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1021 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1022 }
1023 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001024 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1025 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1026 D.getDirectiveKind() == OMPD_simd;
1027 bool SimpleReduction = D.getDirectiveKind() == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001028 // Emit nowait reduction if nowait clause is present or directive is a
1029 // parallel directive (it always has implicit barrier).
1030 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001031 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001032 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001033 }
1034}
1035
Alexey Bataev61205072016-03-02 04:57:40 +00001036static void emitPostUpdateForReductionClause(
1037 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1038 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1039 if (!CGF.HaveInsertPoint())
1040 return;
1041 llvm::BasicBlock *DoneBB = nullptr;
1042 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1043 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1044 if (!DoneBB) {
1045 if (auto *Cond = CondGen(CGF)) {
1046 // If the first post-update expression is found, emit conditional
1047 // block if it was requested.
1048 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1049 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1050 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1051 CGF.EmitBlock(ThenBB);
1052 }
1053 }
1054 CGF.EmitIgnoredExpr(PostUpdate);
1055 }
1056 }
1057 if (DoneBB)
1058 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1059}
1060
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001061namespace {
1062/// Codegen lambda for appending distribute lower and upper bounds to outlined
1063/// parallel function. This is necessary for combined constructs such as
1064/// 'distribute parallel for'
1065typedef llvm::function_ref<void(CodeGenFunction &,
1066 const OMPExecutableDirective &,
1067 llvm::SmallVectorImpl<llvm::Value *> &)>
1068 CodeGenBoundParametersTy;
1069} // anonymous namespace
1070
1071static void emitCommonOMPParallelDirective(
1072 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1073 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1074 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001075 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1076 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1077 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001078 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001079 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001080 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1081 /*IgnoreResultAssign*/ true);
1082 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1083 CGF, NumThreads, NumThreadsClause->getLocStart());
1084 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001085 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001086 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001087 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1088 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1089 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001090 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001091 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1092 if (C->getNameModifier() == OMPD_unknown ||
1093 C->getNameModifier() == OMPD_parallel) {
1094 IfCond = C->getCondition();
1095 break;
1096 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001097 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001098
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001099 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001100 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001101 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1102 // lower and upper bounds with the pragma 'for' chunking mechanism.
1103 // The following lambda takes care of appending the lower and upper bound
1104 // parameters when necessary
1105 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001106 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001107 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001108 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001109}
1110
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001111static void emitEmptyBoundParameters(CodeGenFunction &,
1112 const OMPExecutableDirective &,
1113 llvm::SmallVectorImpl<llvm::Value *> &) {}
1114
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001115void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001116 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001117 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001118 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001119 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001120 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1121 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001122 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001123 // propagation master's thread values of threadprivate variables to local
1124 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001125 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1126 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1127 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001128 }
1129 CGF.EmitOMPPrivateClause(S, PrivateScope);
1130 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1131 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001132 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001133 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001134 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001135 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1136 emitEmptyBoundParameters);
Alexey Bataev61205072016-03-02 04:57:40 +00001137 emitPostUpdateForReductionClause(
1138 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001139}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001140
Alexey Bataev0f34da12015-07-02 04:17:07 +00001141void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1142 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001143 RunCleanupsScope BodyScope(*this);
1144 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001145 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001146 EmitIgnoredExpr(I);
1147 }
Alexander Musman3276a272015-03-21 10:12:56 +00001148 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001149 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001150 for (auto *U : C->updates())
Alexander Musman3276a272015-03-21 10:12:56 +00001151 EmitIgnoredExpr(U);
Alexander Musman3276a272015-03-21 10:12:56 +00001152 }
1153
Alexander Musmana5f070a2014-10-01 06:03:56 +00001154 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001155 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001156 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001157 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001158 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001159 // The end (updates/cleanups).
1160 EmitBlock(Continue.getBlock());
1161 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001162}
1163
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001164void CodeGenFunction::EmitOMPInnerLoop(
1165 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1166 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001167 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1168 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001169 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001170
1171 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001172 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001173 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001174 const SourceRange &R = S.getSourceRange();
1175 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1176 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001177
1178 // If there are any cleanups between here and the loop-exit scope,
1179 // create a block to stage a loop exit along.
1180 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001181 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001182 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001183
Alexander Musmand196ef22014-10-07 08:57:09 +00001184 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001185
Alexey Bataev2df54a02015-03-12 08:53:29 +00001186 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001187 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001188 if (ExitBlock != LoopExit.getBlock()) {
1189 EmitBlock(ExitBlock);
1190 EmitBranchThroughCleanup(LoopExit);
1191 }
1192
1193 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001194 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001195
1196 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001197 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001198 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1199
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001200 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001201
1202 // Emit "IV = IV + 1" and a back-edge to the condition block.
1203 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001204 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001205 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001206 BreakContinueStack.pop_back();
1207 EmitBranch(CondBlock);
1208 LoopStack.pop();
1209 // Emit the fall-through block.
1210 EmitBlock(LoopExit.getBlock());
1211}
1212
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001213void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001214 if (!HaveInsertPoint())
1215 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001216 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001217 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001218 for (auto *Init : C->inits()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001219 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001220 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1221 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1222 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1223 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1224 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1225 VD->getInit()->getType(), VK_LValue,
1226 VD->getInit()->getExprLoc());
1227 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1228 VD->getType()),
1229 /*capturedByInit=*/false);
1230 EmitAutoVarCleanups(Emission);
1231 } else
1232 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001233 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001234 // Emit the linear steps for the linear clauses.
1235 // If a step is not constant, it is pre-calculated before the loop.
1236 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1237 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001238 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001239 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001240 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001241 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001242 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001243}
1244
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001245void CodeGenFunction::EmitOMPLinearClauseFinal(
1246 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001247 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001248 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001249 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001250 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001251 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001252 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001253 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001254 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001255 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001256 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001257 // If the first post-update expression is found, emit conditional
1258 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001259 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1260 DoneBB = createBasicBlock(".omp.linear.pu.done");
1261 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1262 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001263 }
1264 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001265 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1266 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001267 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001268 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001269 Address OrigAddr = EmitLValue(&DRE).getAddress();
1270 CodeGenFunction::OMPPrivateScope VarScope(*this);
1271 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001272 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001273 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001274 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001275 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001276 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001277 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001278 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001279 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001280 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001281}
1282
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001283static void emitAlignedClause(CodeGenFunction &CGF,
1284 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001285 if (!CGF.HaveInsertPoint())
1286 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001287 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001288 unsigned ClauseAlignment = 0;
1289 if (auto AlignmentExpr = Clause->getAlignment()) {
1290 auto AlignmentCI =
1291 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1292 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001293 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001294 for (auto E : Clause->varlists()) {
1295 unsigned Alignment = ClauseAlignment;
1296 if (Alignment == 0) {
1297 // OpenMP [2.8.1, Description]
1298 // If no optional parameter is specified, implementation-defined default
1299 // alignments for SIMD instructions on the target platforms are assumed.
1300 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001301 CGF.getContext()
1302 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1303 E->getType()->getPointeeType()))
1304 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001305 }
1306 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1307 "alignment is not power of 2");
1308 if (Alignment != 0) {
1309 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1310 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1311 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001312 }
1313 }
1314}
1315
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001316void CodeGenFunction::EmitOMPPrivateLoopCounters(
1317 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1318 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001319 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001320 auto I = S.private_counters().begin();
1321 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001322 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1323 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001324 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001325 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001326 if (!LocalDeclMap.count(PrivateVD)) {
1327 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1328 EmitAutoVarCleanups(VarEmission);
1329 }
1330 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1331 /*RefersToEnclosingVariableOrCapture=*/false,
1332 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1333 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001334 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001335 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1336 VD->hasGlobalStorage()) {
1337 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1338 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1339 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1340 E->getType(), VK_LValue, E->getExprLoc());
1341 return EmitLValue(&DRE).getAddress();
1342 });
1343 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001344 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001345 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001346}
1347
Alexey Bataev62dbb972015-04-22 11:59:37 +00001348static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1349 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1350 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001351 if (!CGF.HaveInsertPoint())
1352 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001353 {
1354 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001355 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001356 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001357 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001358 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001359 CGF.EmitIgnoredExpr(I);
1360 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001361 }
1362 // Check that loop is executed at least one time.
1363 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1364}
1365
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001366void CodeGenFunction::EmitOMPLinearClause(
1367 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1368 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001369 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001370 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1371 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1372 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1373 for (auto *C : LoopDirective->counters()) {
1374 SIMDLCVs.insert(
1375 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1376 }
1377 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001378 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001379 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001380 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001381 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1382 auto *PrivateVD =
1383 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001384 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1385 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1386 // Emit private VarDecl with copy init.
1387 EmitVarDecl(*PrivateVD);
1388 return GetAddrOfLocalVar(PrivateVD);
1389 });
1390 assert(IsRegistered && "linear var already registered as private");
1391 // Silence the warning about unused variable.
1392 (void)IsRegistered;
1393 } else
1394 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001395 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001396 }
1397 }
1398}
1399
Alexey Bataev45bfad52015-08-21 12:19:04 +00001400static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001401 const OMPExecutableDirective &D,
1402 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001403 if (!CGF.HaveInsertPoint())
1404 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001405 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001406 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1407 /*ignoreResult=*/true);
1408 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1409 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1410 // In presence of finite 'safelen', it may be unsafe to mark all
1411 // the memory instructions parallel, because loop-carried
1412 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001413 if (!IsMonotonic)
1414 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001415 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001416 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1417 /*ignoreResult=*/true);
1418 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001419 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001420 // In presence of finite 'safelen', it may be unsafe to mark all
1421 // the memory instructions parallel, because loop-carried
1422 // dependences of 'safelen' iterations are possible.
1423 CGF.LoopStack.setParallel(false);
1424 }
1425}
1426
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001427void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1428 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001429 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001430 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001431 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001432 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001433}
1434
Alexey Bataevef549a82016-03-09 09:49:09 +00001435void CodeGenFunction::EmitOMPSimdFinal(
1436 const OMPLoopDirective &D,
1437 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001438 if (!HaveInsertPoint())
1439 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001440 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001441 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001442 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001443 for (auto F : D.finals()) {
1444 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001445 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1446 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1447 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1448 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001449 if (!DoneBB) {
1450 if (auto *Cond = CondGen(*this)) {
1451 // If the first post-update expression is found, emit conditional
1452 // block if it was requested.
1453 auto *ThenBB = createBasicBlock(".omp.final.then");
1454 DoneBB = createBasicBlock(".omp.final.done");
1455 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1456 EmitBlock(ThenBB);
1457 }
1458 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001459 Address OrigAddr = Address::invalid();
1460 if (CED)
1461 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1462 else {
1463 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1464 /*RefersToEnclosingVariableOrCapture=*/false,
1465 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1466 OrigAddr = EmitLValue(&DRE).getAddress();
1467 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001468 OMPPrivateScope VarScope(*this);
1469 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001470 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001471 (void)VarScope.Privatize();
1472 EmitIgnoredExpr(F);
1473 }
1474 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001475 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001476 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001477 if (DoneBB)
1478 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001479}
1480
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001481static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1482 const OMPLoopDirective &S,
1483 CodeGenFunction::JumpDest LoopExit) {
1484 CGF.EmitOMPLoopBody(S, LoopExit);
1485 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001486}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001487
Alexander Musman515ad8c2014-05-22 08:54:05 +00001488void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001489 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00001490 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001491 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001492 // for (IV in 0..LastIteration) BODY;
1493 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001494 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001495 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001496
Alexey Bataev62dbb972015-04-22 11:59:37 +00001497 // Emit: if (PreCond) - begin.
1498 // If the condition constant folds and can be elided, avoid emitting the
1499 // whole loop.
1500 bool CondConstant;
1501 llvm::BasicBlock *ContBlock = nullptr;
1502 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1503 if (!CondConstant)
1504 return;
1505 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001506 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1507 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001508 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1509 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001510 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001511 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001512 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001513
1514 // Emit the loop iteration variable.
1515 const Expr *IVExpr = S.getIterationVariable();
1516 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1517 CGF.EmitVarDecl(*IVDecl);
1518 CGF.EmitIgnoredExpr(S.getInit());
1519
1520 // Emit the iterations count variable.
1521 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001522 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001523 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1524 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1525 // Emit calculation of the iterations count.
1526 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001527 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001528
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001529 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001530
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001531 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001532 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001533 {
1534 OMPPrivateScope LoopScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001535 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1536 CGF.EmitOMPLinearClause(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001537 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001538 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001539 bool HasLastprivateClause =
1540 CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001541 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001542 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1543 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001544 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001545 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001546 CGF.EmitStopPoint(&S);
1547 },
1548 [](CodeGenFunction &) {});
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001549 CGF.EmitOMPSimdFinal(
1550 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001551 // Emit final copy of the lastprivate variables at the end of loops.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001552 if (HasLastprivateClause)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001553 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001554 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
Alexey Bataev61205072016-03-02 04:57:40 +00001555 emitPostUpdateForReductionClause(
1556 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001557 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001558 CGF.EmitOMPLinearClauseFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001559 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001560 // Emit: if (PreCond) - end.
1561 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001562 CGF.EmitBranch(ContBlock);
1563 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001564 }
1565 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00001566 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001567 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001568}
1569
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001570void CodeGenFunction::EmitOMPOuterLoop(
1571 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1572 CodeGenFunction::OMPPrivateScope &LoopScope,
1573 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1574 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1575 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001576 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001577
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001578 const Expr *IVExpr = S.getIterationVariable();
1579 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1580 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1581
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001582 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1583
1584 // Start the loop with a block that tests the condition.
1585 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1586 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001587 const SourceRange &R = S.getSourceRange();
1588 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1589 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001590
1591 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001592 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001593 // UB = min(UB, GlobalUB) or
1594 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1595 // 'distribute parallel for')
1596 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001597 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001598 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001599 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001600 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001601 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001602 BoolCondVal =
1603 RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1604 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001605 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001606
1607 // If there are any cleanups between here and the loop-exit scope,
1608 // create a block to stage a loop exit along.
1609 auto ExitBlock = LoopExit.getBlock();
1610 if (LoopScope.requiresCleanups())
1611 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1612
1613 auto LoopBody = createBasicBlock("omp.dispatch.body");
1614 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1615 if (ExitBlock != LoopExit.getBlock()) {
1616 EmitBlock(ExitBlock);
1617 EmitBranchThroughCleanup(LoopExit);
1618 }
1619 EmitBlock(LoopBody);
1620
Alexander Musman92bdaab2015-03-12 13:37:50 +00001621 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1622 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001623 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001624 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001625
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001626 // Create a block for the increment.
1627 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1628 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1629
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001630 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1631 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001632 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1633 LoopStack.setParallel(!IsMonotonic);
1634 else
1635 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001636
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001637 SourceLocation Loc = S.getLocStart();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001638
1639 // when 'distribute' is not combined with a 'for':
1640 // while (idx <= UB) { BODY; ++idx; }
1641 // when 'distribute' is combined with a 'for'
1642 // (e.g. 'distribute parallel for')
1643 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1644 EmitOMPInnerLoop(
1645 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1646 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1647 CodeGenLoop(CGF, S, LoopExit);
1648 },
1649 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1650 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1651 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001652
1653 EmitBlock(Continue.getBlock());
1654 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001655 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001656 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001657 EmitIgnoredExpr(LoopArgs.NextLB);
1658 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001659 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001660
1661 EmitBranch(CondBlock);
1662 LoopStack.pop();
1663 // Emit the fall-through block.
1664 EmitBlock(LoopExit.getBlock());
1665
1666 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001667 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1668 if (!DynamicOrOrdered)
1669 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
1670 };
1671 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001672}
1673
1674void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001675 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001676 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001677 const OMPLoopArguments &LoopArgs,
1678 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001679 auto &RT = CGM.getOpenMPRuntime();
1680
1681 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001682 const bool DynamicOrOrdered =
1683 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001684
1685 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001686 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001687 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001688 "static non-chunked schedule does not need outer loop");
1689
1690 // Emit outer loop.
1691 //
1692 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1693 // When schedule(dynamic,chunk_size) is specified, the iterations are
1694 // distributed to threads in the team in chunks as the threads request them.
1695 // Each thread executes a chunk of iterations, then requests another chunk,
1696 // until no chunks remain to be distributed. Each chunk contains chunk_size
1697 // iterations, except for the last chunk to be distributed, which may have
1698 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1699 //
1700 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1701 // to threads in the team in chunks as the executing threads request them.
1702 // Each thread executes a chunk of iterations, then requests another chunk,
1703 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1704 // each chunk is proportional to the number of unassigned iterations divided
1705 // by the number of threads in the team, decreasing to 1. For a chunk_size
1706 // with value k (greater than 1), the size of each chunk is determined in the
1707 // same way, with the restriction that the chunks do not contain fewer than k
1708 // iterations (except for the last chunk to be assigned, which may have fewer
1709 // than k iterations).
1710 //
1711 // When schedule(auto) is specified, the decision regarding scheduling is
1712 // delegated to the compiler and/or runtime system. The programmer gives the
1713 // implementation the freedom to choose any possible mapping of iterations to
1714 // threads in the team.
1715 //
1716 // When schedule(runtime) is specified, the decision regarding scheduling is
1717 // deferred until run time, and the schedule and chunk size are taken from the
1718 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1719 // implementation defined
1720 //
1721 // while(__kmpc_dispatch_next(&LB, &UB)) {
1722 // idx = LB;
1723 // while (idx <= UB) { BODY; ++idx;
1724 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1725 // } // inner loop
1726 // }
1727 //
1728 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1729 // When schedule(static, chunk_size) is specified, iterations are divided into
1730 // chunks of size chunk_size, and the chunks are assigned to the threads in
1731 // the team in a round-robin fashion in the order of the thread number.
1732 //
1733 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1734 // while (idx <= UB) { BODY; ++idx; } // inner loop
1735 // LB = LB + ST;
1736 // UB = UB + ST;
1737 // }
1738 //
1739
1740 const Expr *IVExpr = S.getIterationVariable();
1741 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1742 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1743
1744 if (DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001745 auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1746 llvm::Value *LBVal = DispatchBounds.first;
1747 llvm::Value *UBVal = DispatchBounds.second;
1748 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1749 LoopArgs.Chunk};
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001750 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001751 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001752 } else {
1753 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001754 Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1755 LoopArgs.ST, LoopArgs.Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001756 }
1757
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001758 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1759 const unsigned IVSize,
1760 const bool IVSigned) {
1761 if (Ordered) {
1762 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1763 IVSigned);
1764 }
1765 };
1766
1767 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1768 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1769 OuterLoopArgs.IncExpr = S.getInc();
1770 OuterLoopArgs.Init = S.getInit();
1771 OuterLoopArgs.Cond = S.getCond();
1772 OuterLoopArgs.NextLB = S.getNextLowerBound();
1773 OuterLoopArgs.NextUB = S.getNextUpperBound();
1774 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1775 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001776}
1777
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001778static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1779 const unsigned IVSize, const bool IVSigned) {}
1780
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001781void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001782 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1783 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1784 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001785
1786 auto &RT = CGM.getOpenMPRuntime();
1787
1788 // Emit outer loop.
1789 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1790 // dynamic
1791 //
1792
1793 const Expr *IVExpr = S.getIterationVariable();
1794 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1795 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1796
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001797 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize,
1798 IVSigned, /* Ordered = */ false, LoopArgs.IL,
1799 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1800 LoopArgs.Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001801
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001802 // for combined 'distribute' and 'for' the increment expression of distribute
1803 // is store in DistInc. For 'distribute' alone, it is in Inc.
1804 Expr *IncExpr;
1805 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1806 IncExpr = S.getDistInc();
1807 else
1808 IncExpr = S.getInc();
1809
1810 // this routine is shared by 'omp distribute parallel for' and
1811 // 'omp distribute': select the right EUB expression depending on the
1812 // directive
1813 OMPLoopArguments OuterLoopArgs;
1814 OuterLoopArgs.LB = LoopArgs.LB;
1815 OuterLoopArgs.UB = LoopArgs.UB;
1816 OuterLoopArgs.ST = LoopArgs.ST;
1817 OuterLoopArgs.IL = LoopArgs.IL;
1818 OuterLoopArgs.Chunk = LoopArgs.Chunk;
1819 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1820 ? S.getCombinedEnsureUpperBound()
1821 : S.getEnsureUpperBound();
1822 OuterLoopArgs.IncExpr = IncExpr;
1823 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1824 ? S.getCombinedInit()
1825 : S.getInit();
1826 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1827 ? S.getCombinedCond()
1828 : S.getCond();
1829 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1830 ? S.getCombinedNextLowerBound()
1831 : S.getNextLowerBound();
1832 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1833 ? S.getCombinedNextUpperBound()
1834 : S.getNextUpperBound();
1835
1836 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
1837 LoopScope, OuterLoopArgs, CodeGenLoopContent,
1838 emitEmptyOrdered);
1839}
1840
1841/// Emit a helper variable and return corresponding lvalue.
1842static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1843 const DeclRefExpr *Helper) {
1844 auto VDecl = cast<VarDecl>(Helper->getDecl());
1845 CGF.EmitVarDecl(*VDecl);
1846 return CGF.EmitLValue(Helper);
1847}
1848
1849static std::pair<LValue, LValue>
1850emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
1851 const OMPExecutableDirective &S) {
1852 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1853 LValue LB =
1854 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
1855 LValue UB =
1856 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
1857
1858 // When composing 'distribute' with 'for' (e.g. as in 'distribute
1859 // parallel for') we need to use the 'distribute'
1860 // chunk lower and upper bounds rather than the whole loop iteration
1861 // space. These are parameters to the outlined function for 'parallel'
1862 // and we copy the bounds of the previous schedule into the
1863 // the current ones.
1864 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
1865 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
1866 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(PrevLB, SourceLocation());
1867 PrevLBVal = CGF.EmitScalarConversion(
1868 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
1869 LS.getIterationVariable()->getType(), SourceLocation());
1870 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(PrevUB, SourceLocation());
1871 PrevUBVal = CGF.EmitScalarConversion(
1872 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
1873 LS.getIterationVariable()->getType(), SourceLocation());
1874
1875 CGF.EmitStoreOfScalar(PrevLBVal, LB);
1876 CGF.EmitStoreOfScalar(PrevUBVal, UB);
1877
1878 return {LB, UB};
1879}
1880
1881/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
1882/// we need to use the LB and UB expressions generated by the worksharing
1883/// code generation support, whereas in non combined situations we would
1884/// just emit 0 and the LastIteration expression
1885/// This function is necessary due to the difference of the LB and UB
1886/// types for the RT emission routines for 'for_static_init' and
1887/// 'for_dispatch_init'
1888static std::pair<llvm::Value *, llvm::Value *>
1889emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
1890 const OMPExecutableDirective &S,
1891 Address LB, Address UB) {
1892 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1893 const Expr *IVExpr = LS.getIterationVariable();
1894 // when implementing a dynamic schedule for a 'for' combined with a
1895 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
1896 // is not normalized as each team only executes its own assigned
1897 // distribute chunk
1898 QualType IteratorTy = IVExpr->getType();
1899 llvm::Value *LBVal = CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy,
1900 SourceLocation());
1901 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy,
1902 SourceLocation());
1903 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00001904}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001905
1906static void emitDistributeParallelForDistributeInnerBoundParams(
1907 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1908 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
1909 const auto &Dir = cast<OMPLoopDirective>(S);
1910 LValue LB =
1911 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
1912 auto LBCast = CGF.Builder.CreateIntCast(
1913 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
1914 CapturedVars.push_back(LBCast);
1915 LValue UB =
1916 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
1917
1918 auto UBCast = CGF.Builder.CreateIntCast(
1919 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
1920 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00001921}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001922
1923static void
1924emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
1925 const OMPLoopDirective &S,
1926 CodeGenFunction::JumpDest LoopExit) {
1927 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
1928 PrePostActionTy &) {
1929 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
1930 emitDistributeParallelForInnerBounds,
1931 emitDistributeParallelForDispatchBounds);
1932 };
1933
1934 emitCommonOMPParallelDirective(
1935 CGF, S, OMPD_for, CGInlinedWorksharingLoop,
1936 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001937}
1938
Carlo Bertolli9925f152016-06-27 14:55:37 +00001939void CodeGenFunction::EmitOMPDistributeParallelForDirective(
1940 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001941 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1942 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
1943 S.getDistInc());
1944 };
Carlo Bertolli9925f152016-06-27 14:55:37 +00001945 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001946 OMPCancelStackRAII CancelRegion(*this, OMPD_distribute_parallel_for,
1947 /*HasCancel=*/false);
1948 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
1949 /*HasCancel=*/false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00001950}
1951
Kelvin Li4a39add2016-07-05 05:00:15 +00001952void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
1953 const OMPDistributeParallelForSimdDirective &S) {
1954 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1955 CGM.getOpenMPRuntime().emitInlinedDirective(
1956 *this, OMPD_distribute_parallel_for_simd,
1957 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1958 OMPLoopScope PreInitScope(CGF, S);
1959 CGF.EmitStmt(
1960 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1961 });
1962}
Kelvin Li787f3fc2016-07-06 04:45:38 +00001963
1964void CodeGenFunction::EmitOMPDistributeSimdDirective(
1965 const OMPDistributeSimdDirective &S) {
1966 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1967 CGM.getOpenMPRuntime().emitInlinedDirective(
1968 *this, OMPD_distribute_simd,
1969 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1970 OMPLoopScope PreInitScope(CGF, S);
1971 CGF.EmitStmt(
1972 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1973 });
1974}
1975
Kelvin Lia579b912016-07-14 02:54:56 +00001976void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
1977 const OMPTargetParallelForSimdDirective &S) {
1978 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1979 CGM.getOpenMPRuntime().emitInlinedDirective(
1980 *this, OMPD_target_parallel_for_simd,
1981 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1982 OMPLoopScope PreInitScope(CGF, S);
1983 CGF.EmitStmt(
1984 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1985 });
1986}
1987
Kelvin Li986330c2016-07-20 22:57:10 +00001988void CodeGenFunction::EmitOMPTargetSimdDirective(
1989 const OMPTargetSimdDirective &S) {
1990 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1991 CGM.getOpenMPRuntime().emitInlinedDirective(
1992 *this, OMPD_target_simd, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1993 OMPLoopScope PreInitScope(CGF, S);
1994 CGF.EmitStmt(
1995 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1996 });
1997}
1998
Kelvin Li02532872016-08-05 14:37:37 +00001999void CodeGenFunction::EmitOMPTeamsDistributeDirective(
2000 const OMPTeamsDistributeDirective &S) {
2001 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2002 CGM.getOpenMPRuntime().emitInlinedDirective(
2003 *this, OMPD_teams_distribute,
2004 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2005 OMPLoopScope PreInitScope(CGF, S);
2006 CGF.EmitStmt(
2007 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2008 });
2009}
2010
Kelvin Li4e325f72016-10-25 12:50:55 +00002011void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
2012 const OMPTeamsDistributeSimdDirective &S) {
2013 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2014 CGM.getOpenMPRuntime().emitInlinedDirective(
2015 *this, OMPD_teams_distribute_simd,
2016 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2017 OMPLoopScope PreInitScope(CGF, S);
2018 CGF.EmitStmt(
2019 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2020 });
2021}
2022
Kelvin Li579e41c2016-11-30 23:51:03 +00002023void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
2024 const OMPTeamsDistributeParallelForSimdDirective &S) {
2025 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2026 CGM.getOpenMPRuntime().emitInlinedDirective(
2027 *this, OMPD_teams_distribute_parallel_for_simd,
2028 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2029 OMPLoopScope PreInitScope(CGF, S);
2030 CGF.EmitStmt(
2031 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2032 });
2033}
Kelvin Li4e325f72016-10-25 12:50:55 +00002034
Kelvin Li7ade93f2016-12-09 03:24:30 +00002035void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
2036 const OMPTeamsDistributeParallelForDirective &S) {
2037 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2038 CGM.getOpenMPRuntime().emitInlinedDirective(
2039 *this, OMPD_teams_distribute_parallel_for,
2040 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2041 OMPLoopScope PreInitScope(CGF, S);
2042 CGF.EmitStmt(
2043 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2044 });
2045}
2046
Kelvin Li83c451e2016-12-25 04:52:54 +00002047void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
2048 const OMPTargetTeamsDistributeDirective &S) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002049 CGM.getOpenMPRuntime().emitInlinedDirective(
2050 *this, OMPD_target_teams_distribute,
Kelvin Li83c451e2016-12-25 04:52:54 +00002051 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002052 CGF.EmitStmt(
2053 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Kelvin Li83c451e2016-12-25 04:52:54 +00002054 });
2055}
2056
Kelvin Li80e8f562016-12-29 22:16:30 +00002057void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
2058 const OMPTargetTeamsDistributeParallelForDirective &S) {
2059 CGM.getOpenMPRuntime().emitInlinedDirective(
2060 *this, OMPD_target_teams_distribute_parallel_for,
2061 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2062 CGF.EmitStmt(
2063 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2064 });
2065}
2066
Kelvin Li1851df52017-01-03 05:23:48 +00002067void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2068 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
2069 CGM.getOpenMPRuntime().emitInlinedDirective(
2070 *this, OMPD_target_teams_distribute_parallel_for_simd,
2071 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2072 CGF.EmitStmt(
2073 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2074 });
2075}
2076
Kelvin Lida681182017-01-10 18:08:18 +00002077void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
2078 const OMPTargetTeamsDistributeSimdDirective &S) {
2079 CGM.getOpenMPRuntime().emitInlinedDirective(
2080 *this, OMPD_target_teams_distribute_simd,
2081 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2082 CGF.EmitStmt(
2083 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2084 });
2085}
2086
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002087namespace {
2088 struct ScheduleKindModifiersTy {
2089 OpenMPScheduleClauseKind Kind;
2090 OpenMPScheduleClauseModifier M1;
2091 OpenMPScheduleClauseModifier M2;
2092 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2093 OpenMPScheduleClauseModifier M1,
2094 OpenMPScheduleClauseModifier M2)
2095 : Kind(Kind), M1(M1), M2(M2) {}
2096 };
2097} // namespace
2098
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002099bool CodeGenFunction::EmitOMPWorksharingLoop(
2100 const OMPLoopDirective &S, Expr *EUB,
2101 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2102 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002103 // Emit the loop iteration variable.
2104 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2105 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2106 EmitVarDecl(*IVDecl);
2107
2108 // Emit the iterations count variable.
2109 // If it is not a variable, Sema decided to calculate iterations count on each
2110 // iteration (e.g., it is foldable into a constant).
2111 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2112 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2113 // Emit calculation of the iterations count.
2114 EmitIgnoredExpr(S.getCalcLastIteration());
2115 }
2116
2117 auto &RT = CGM.getOpenMPRuntime();
2118
Alexey Bataev38e89532015-04-16 04:54:05 +00002119 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002120 // Check pre-condition.
2121 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002122 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002123 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002124 // If the condition constant folds and can be elided, avoid emitting the
2125 // whole loop.
2126 bool CondConstant;
2127 llvm::BasicBlock *ContBlock = nullptr;
2128 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2129 if (!CondConstant)
2130 return false;
2131 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002132 auto *ThenBlock = createBasicBlock("omp.precond.then");
2133 ContBlock = createBasicBlock("omp.precond.end");
2134 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002135 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002136 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002137 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002138 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002139
Alexey Bataev8b427062016-05-25 12:36:08 +00002140 bool Ordered = false;
2141 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2142 if (OrderedClause->getNumForLoops())
2143 RT.emitDoacrossInit(*this, S);
2144 else
2145 Ordered = true;
2146 }
2147
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002148 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002149 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002150 EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002151 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002152
2153 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2154 LValue LB = Bounds.first;
2155 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002156 LValue ST =
2157 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2158 LValue IL =
2159 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2160
Alexander Musmanc6388682014-12-15 07:07:06 +00002161 // Emit 'then' code.
2162 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002163 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002164 if (EmitOMPFirstprivateClause(S, LoopScope)) {
2165 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002166 // initialization of firstprivate variables and post-update of
2167 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002168 CGM.getOpenMPRuntime().emitBarrierCall(
2169 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2170 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002171 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002172 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002173 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002174 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002175 EmitOMPPrivateLoopCounters(S, LoopScope);
2176 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002177 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002178
2179 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002180 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002181 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002182 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002183 ScheduleKind.Schedule = C->getScheduleKind();
2184 ScheduleKind.M1 = C->getFirstScheduleModifier();
2185 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002186 if (const auto *Ch = C->getChunkSize()) {
2187 Chunk = EmitScalarExpr(Ch);
2188 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2189 S.getIterationVariable()->getType(),
2190 S.getLocStart());
2191 }
2192 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002193 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2194 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002195 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2196 // If the static schedule kind is specified or if the ordered clause is
2197 // specified, and if no monotonic modifier is specified, the effect will
2198 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002199 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002200 /* Chunked */ Chunk != nullptr) &&
2201 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002202 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2203 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002204 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2205 // When no chunk_size is specified, the iteration space is divided into
2206 // chunks that are approximately equal in size, and at most one chunk is
2207 // distributed to each thread. Note that the size of the chunks is
2208 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00002209 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
2210 IVSize, IVSigned, Ordered,
2211 IL.getAddress(), LB.getAddress(),
2212 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002213 auto LoopExit =
2214 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002215 // UB = min(UB, GlobalUB);
2216 EmitIgnoredExpr(S.getEnsureUpperBound());
2217 // IV = LB;
2218 EmitIgnoredExpr(S.getInit());
2219 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002220 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2221 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002222 [&S, LoopExit](CodeGenFunction &CGF) {
2223 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002224 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002225 },
2226 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002227 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002228 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002229 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2230 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
2231 };
2232 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002233 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002234 const bool IsMonotonic =
2235 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2236 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2237 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2238 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002239 // Emit the outer loop, which requests its work chunk [LB..UB] from
2240 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002241 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2242 ST.getAddress(), IL.getAddress(),
2243 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002244 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002245 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002246 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002247 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2248 EmitOMPSimdFinal(S,
2249 [&](CodeGenFunction &CGF) -> llvm::Value * {
2250 return CGF.Builder.CreateIsNotNull(
2251 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2252 });
2253 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002254 EmitOMPReductionClauseFinal(
2255 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2256 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2257 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002258 // Emit post-update of the reduction variables if IsLastIter != 0.
2259 emitPostUpdateForReductionClause(
2260 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2261 return CGF.Builder.CreateIsNotNull(
2262 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2263 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002264 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2265 if (HasLastprivateClause)
2266 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002267 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2268 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002269 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002270 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002271 return CGF.Builder.CreateIsNotNull(
2272 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2273 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002274 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002275 if (ContBlock) {
2276 EmitBranch(ContBlock);
2277 EmitBlock(ContBlock, true);
2278 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002279 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002280 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002281}
2282
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002283/// The following two functions generate expressions for the loop lower
2284/// and upper bounds in case of static and dynamic (dispatch) schedule
2285/// of the associated 'for' or 'distribute' loop.
2286static std::pair<LValue, LValue>
2287emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2288 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2289 LValue LB =
2290 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2291 LValue UB =
2292 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2293 return {LB, UB};
2294}
2295
2296/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2297/// consider the lower and upper bound expressions generated by the
2298/// worksharing loop support, but we use 0 and the iteration space size as
2299/// constants
2300static std::pair<llvm::Value *, llvm::Value *>
2301emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2302 Address LB, Address UB) {
2303 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2304 const Expr *IVExpr = LS.getIterationVariable();
2305 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2306 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2307 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2308 return {LBVal, UBVal};
2309}
2310
Alexander Musmanc6388682014-12-15 07:07:06 +00002311void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002312 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002313 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2314 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002315 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002316 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2317 emitForLoopBounds,
2318 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002319 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002320 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002321 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002322 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2323 S.hasCancel());
2324 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002325
2326 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002327 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002328 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2329 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002330}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002331
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002332void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002333 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002334 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2335 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002336 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2337 emitForLoopBounds,
2338 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002339 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002340 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002341 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002342 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2343 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002344
2345 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002346 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002347 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2348 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002349}
2350
Alexey Bataev2df54a02015-03-12 08:53:29 +00002351static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2352 const Twine &Name,
2353 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002354 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002355 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002356 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002357 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002358}
2359
Alexey Bataev3392d762016-02-16 11:18:12 +00002360void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00002361 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2362 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002363 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002364 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2365 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002366 auto &C = CGF.CGM.getContext();
2367 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2368 // Emit helper vars inits.
2369 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2370 CGF.Builder.getInt32(0));
2371 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2372 : CGF.Builder.getInt32(0);
2373 LValue UB =
2374 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2375 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2376 CGF.Builder.getInt32(1));
2377 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2378 CGF.Builder.getInt32(0));
2379 // Loop counter.
2380 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2381 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2382 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2383 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2384 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2385 // Generate condition for loop.
2386 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002387 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002388 // Increment for loop counter.
2389 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2390 S.getLocStart());
2391 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2392 // Iterate through all sections and emit a switch construct:
2393 // switch (IV) {
2394 // case 0:
2395 // <SectionStmt[0]>;
2396 // break;
2397 // ...
2398 // case <NumSection> - 1:
2399 // <SectionStmt[<NumSection> - 1]>;
2400 // break;
2401 // }
2402 // .omp.sections.exit:
2403 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2404 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2405 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2406 CS == nullptr ? 1 : CS->size());
2407 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002408 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002409 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002410 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2411 CGF.EmitBlock(CaseBB);
2412 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002413 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002414 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002415 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002416 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002417 } else {
2418 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2419 CGF.EmitBlock(CaseBB);
2420 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2421 CGF.EmitStmt(Stmt);
2422 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002423 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002424 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002425 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002426
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002427 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2428 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002429 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002430 // initialization of firstprivate variables and post-update of lastprivate
2431 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002432 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2433 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2434 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002435 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002436 CGF.EmitOMPPrivateClause(S, LoopScope);
2437 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2438 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2439 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002440
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002441 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002442 OpenMPScheduleTy ScheduleKind;
2443 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002444 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002445 CGF, S.getLocStart(), ScheduleKind, /*IVSize=*/32,
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002446 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
2447 UB.getAddress(), ST.getAddress());
2448 // UB = min(UB, GlobalUB);
2449 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2450 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2451 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2452 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2453 // IV = LB;
2454 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2455 // while (idx <= UB) { BODY; ++idx; }
2456 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2457 [](CodeGenFunction &) {});
2458 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002459 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2460 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
2461 };
2462 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002463 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002464 // Emit post-update of the reduction variables if IsLastIter != 0.
2465 emitPostUpdateForReductionClause(
2466 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2467 return CGF.Builder.CreateIsNotNull(
2468 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2469 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002470
2471 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2472 if (HasLastprivates)
2473 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002474 S, /*NoFinals=*/false,
2475 CGF.Builder.CreateIsNotNull(
2476 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002477 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002478
2479 bool HasCancel = false;
2480 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2481 HasCancel = OSD->hasCancel();
2482 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2483 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002484 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002485 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2486 HasCancel);
2487 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2488 // clause. Otherwise the barrier will be generated by the codegen for the
2489 // directive.
2490 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002491 // Emit implicit barrier to synchronize threads and avoid data races on
2492 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002493 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2494 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002495 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002496}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002497
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002498void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002499 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002500 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002501 EmitSections(S);
2502 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002503 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002504 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002505 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2506 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002507 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002508}
2509
2510void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002511 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002512 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002513 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002514 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002515 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2516 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002517}
2518
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002519void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002520 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002521 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002522 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002523 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002524 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002525 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002526 // Build a list of copyprivate variables along with helper expressions
2527 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002528 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002529 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002530 DestExprs.append(C->destination_exprs().begin(),
2531 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002532 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002533 AssignmentOps.append(C->assignment_ops().begin(),
2534 C->assignment_ops().end());
2535 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002536 // Emit code for 'single' region along with 'copyprivate' clauses
2537 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2538 Action.Enter(CGF);
2539 OMPPrivateScope SingleScope(CGF);
2540 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2541 CGF.EmitOMPPrivateClause(S, SingleScope);
2542 (void)SingleScope.Privatize();
2543 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2544 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002545 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002546 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002547 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2548 CopyprivateVars, DestExprs,
2549 SrcExprs, AssignmentOps);
2550 }
2551 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2552 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002553 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002554 CGM.getOpenMPRuntime().emitBarrierCall(
2555 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002556 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002557 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002558}
2559
Alexey Bataev8d690652014-12-04 07:23:53 +00002560void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002561 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2562 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002563 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002564 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002565 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002566 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002567}
2568
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002569void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002570 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2571 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002572 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002573 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002574 Expr *Hint = nullptr;
2575 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2576 Hint = HintClause->getHint();
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002577 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002578 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2579 S.getDirectiveName().getAsString(),
2580 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002581}
2582
Alexey Bataev671605e2015-04-13 05:28:11 +00002583void CodeGenFunction::EmitOMPParallelForDirective(
2584 const OMPParallelForDirective &S) {
2585 // Emit directive as a combined directive that consists of two implicit
2586 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002587 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002588 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002589 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2590 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002591 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002592 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2593 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002594}
2595
Alexander Musmane4e893b2014-09-23 09:33:00 +00002596void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002597 const OMPParallelForSimdDirective &S) {
2598 // Emit directive as a combined directive that consists of two implicit
2599 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002600 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002601 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2602 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002603 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002604 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2605 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002606}
2607
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002608void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002609 const OMPParallelSectionsDirective &S) {
2610 // Emit directive as a combined directive that consists of two implicit
2611 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002612 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2613 CGF.EmitSections(S);
2614 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002615 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2616 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002617}
2618
Alexey Bataev7292c292016-04-25 12:22:29 +00002619void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2620 const RegionCodeGenTy &BodyGen,
2621 const TaskGenTy &TaskGen,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002622 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002623 // Emit outlined function for task construct.
2624 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002625 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002626 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002627 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002628 // Check if the task is final
2629 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2630 // If the condition constant folds and can be elided, try to avoid emitting
2631 // the condition and the dead arm of the if/else.
2632 auto *Cond = Clause->getCondition();
2633 bool CondConstant;
2634 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2635 Data.Final.setInt(CondConstant);
2636 else
2637 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2638 } else {
2639 // By default the task is not final.
2640 Data.Final.setInt(/*IntVal=*/false);
2641 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002642 // Check if the task has 'priority' clause.
2643 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002644 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002645 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002646 Data.Priority.setPointer(EmitScalarConversion(
2647 EmitScalarExpr(Prio), Prio->getType(),
2648 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2649 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002650 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002651 // The first function argument for tasks is a thread id, the second one is a
2652 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002653 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2654 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002655 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002656 auto IRef = C->varlist_begin();
2657 for (auto *IInit : C->private_copies()) {
2658 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2659 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002660 Data.PrivateVars.push_back(*IRef);
2661 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002662 }
2663 ++IRef;
2664 }
2665 }
2666 EmittedAsPrivate.clear();
2667 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002668 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002669 auto IRef = C->varlist_begin();
2670 auto IElemInitRef = C->inits().begin();
2671 for (auto *IInit : C->private_copies()) {
2672 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2673 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002674 Data.FirstprivateVars.push_back(*IRef);
2675 Data.FirstprivateCopies.push_back(IInit);
2676 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002677 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002678 ++IRef;
2679 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002680 }
2681 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002682 // Get list of lastprivate variables (for taskloops).
2683 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2684 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2685 auto IRef = C->varlist_begin();
2686 auto ID = C->destination_exprs().begin();
2687 for (auto *IInit : C->private_copies()) {
2688 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2689 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2690 Data.LastprivateVars.push_back(*IRef);
2691 Data.LastprivateCopies.push_back(IInit);
2692 }
2693 LastprivateDstsOrigs.insert(
2694 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2695 cast<DeclRefExpr>(*IRef)});
2696 ++IRef;
2697 ++ID;
2698 }
2699 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002700 SmallVector<const Expr *, 4> LHSs;
2701 SmallVector<const Expr *, 4> RHSs;
2702 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2703 auto IPriv = C->privates().begin();
2704 auto IRed = C->reduction_ops().begin();
2705 auto ILHS = C->lhs_exprs().begin();
2706 auto IRHS = C->rhs_exprs().begin();
2707 for (const auto *Ref : C->varlists()) {
2708 Data.ReductionVars.emplace_back(Ref);
2709 Data.ReductionCopies.emplace_back(*IPriv);
2710 Data.ReductionOps.emplace_back(*IRed);
2711 LHSs.emplace_back(*ILHS);
2712 RHSs.emplace_back(*IRHS);
2713 std::advance(IPriv, 1);
2714 std::advance(IRed, 1);
2715 std::advance(ILHS, 1);
2716 std::advance(IRHS, 1);
2717 }
2718 }
2719 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2720 *this, S.getLocStart(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002721 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002722 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2723 for (auto *IRef : C->varlists())
2724 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002725 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs](
Alexey Bataevf93095a2016-05-05 08:46:22 +00002726 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002727 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002728 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002729 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2730 !Data.LastprivateVars.empty()) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002731 auto *CopyFn = CGF.Builder.CreateLoad(
2732 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2733 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2734 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2735 // Map privates.
2736 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2737 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2738 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002739 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002740 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2741 Address PrivatePtr = CGF.CreateMemTemp(
2742 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2743 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2744 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002745 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002746 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002747 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2748 Address PrivatePtr =
2749 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2750 ".firstpriv.ptr.addr");
2751 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2752 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002753 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002754 for (auto *E : Data.LastprivateVars) {
2755 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2756 Address PrivatePtr =
2757 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2758 ".lastpriv.ptr.addr");
2759 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2760 CallArgs.push_back(PrivatePtr.getPointer());
2761 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002762 CGF.EmitRuntimeCall(CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002763 for (auto &&Pair : LastprivateDstsOrigs) {
2764 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2765 DeclRefExpr DRE(
2766 const_cast<VarDecl *>(OrigVD),
2767 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2768 OrigVD) != nullptr,
2769 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2770 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2771 return CGF.EmitLValue(&DRE).getAddress();
2772 });
2773 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002774 for (auto &&Pair : PrivatePtrs) {
2775 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2776 CGF.getContext().getDeclAlign(Pair.first));
2777 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2778 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002779 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002780 if (Data.Reductions) {
2781 OMPLexicalScope LexScope(CGF, S, /*AsInlined=*/true);
2782 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2783 Data.ReductionOps);
2784 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2785 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2786 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2787 RedCG.emitSharedLValue(CGF, Cnt);
2788 RedCG.emitAggregateType(CGF, Cnt);
2789 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2790 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2791 Replacement =
2792 Address(CGF.EmitScalarConversion(
2793 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2794 CGF.getContext().getPointerType(
2795 Data.ReductionCopies[Cnt]->getType()),
2796 SourceLocation()),
2797 Replacement.getAlignment());
2798 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2799 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2800 [Replacement]() { return Replacement; });
2801 // FIXME: This must removed once the runtime library is fixed.
2802 // Emit required threadprivate variables for
2803 // initilizer/combiner/finalizer.
2804 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2805 RedCG, Cnt);
2806 }
2807 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002808 (void)Scope.Privatize();
2809
2810 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002811 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002812 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002813 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2814 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2815 Data.NumberOfParts);
2816 OMPLexicalScope Scope(*this, S);
2817 TaskGen(*this, OutlinedFn, Data);
2818}
2819
2820void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2821 // Emit outlined function for task construct.
2822 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2823 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002824 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002825 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002826 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2827 if (C->getNameModifier() == OMPD_unknown ||
2828 C->getNameModifier() == OMPD_task) {
2829 IfCond = C->getCondition();
2830 break;
2831 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002832 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002833
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002834 OMPTaskDataTy Data;
2835 // Check if we should emit tied or untied task.
2836 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00002837 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
2838 CGF.EmitStmt(CS->getCapturedStmt());
2839 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002840 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00002841 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002842 const OMPTaskDataTy &Data) {
2843 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
2844 SharedsTy, CapturedStruct, IfCond,
2845 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00002846 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002847 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002848}
2849
Alexey Bataev9f797f32015-02-05 05:57:51 +00002850void CodeGenFunction::EmitOMPTaskyieldDirective(
2851 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002852 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002853}
2854
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002855void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002856 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002857}
2858
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002859void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2860 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002861}
2862
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002863void CodeGenFunction::EmitOMPTaskgroupDirective(
2864 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002865 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2866 Action.Enter(CGF);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002867 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002868 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002869 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002870 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2871}
2872
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002873void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002874 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002875 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002876 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2877 FlushClause->varlist_end());
2878 }
2879 return llvm::None;
2880 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002881}
2882
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002883void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
2884 const CodeGenLoopTy &CodeGenLoop,
2885 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002886 // Emit the loop iteration variable.
2887 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2888 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2889 EmitVarDecl(*IVDecl);
2890
2891 // Emit the iterations count variable.
2892 // If it is not a variable, Sema decided to calculate iterations count on each
2893 // iteration (e.g., it is foldable into a constant).
2894 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2895 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2896 // Emit calculation of the iterations count.
2897 EmitIgnoredExpr(S.getCalcLastIteration());
2898 }
2899
2900 auto &RT = CGM.getOpenMPRuntime();
2901
Carlo Bertolli962bb802017-01-03 18:24:42 +00002902 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002903 // Check pre-condition.
2904 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002905 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002906 // Skip the entire loop if we don't meet the precondition.
2907 // If the condition constant folds and can be elided, avoid emitting the
2908 // whole loop.
2909 bool CondConstant;
2910 llvm::BasicBlock *ContBlock = nullptr;
2911 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2912 if (!CondConstant)
2913 return;
2914 } else {
2915 auto *ThenBlock = createBasicBlock("omp.precond.then");
2916 ContBlock = createBasicBlock("omp.precond.end");
2917 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
2918 getProfileCount(&S));
2919 EmitBlock(ThenBlock);
2920 incrementProfileCounter(&S);
2921 }
2922
2923 // Emit 'then' code.
2924 {
2925 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002926
2927 LValue LB = EmitOMPHelperVar(
2928 *this, cast<DeclRefExpr>(
2929 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2930 ? S.getCombinedLowerBoundVariable()
2931 : S.getLowerBoundVariable())));
2932 LValue UB = EmitOMPHelperVar(
2933 *this, cast<DeclRefExpr>(
2934 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2935 ? S.getCombinedUpperBoundVariable()
2936 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002937 LValue ST =
2938 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2939 LValue IL =
2940 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2941
2942 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00002943 if (EmitOMPFirstprivateClause(S, LoopScope)) {
2944 // Emit implicit barrier to synchronize threads and avoid data races on
2945 // initialization of firstprivate variables and post-update of
2946 // lastprivate variables.
2947 CGM.getOpenMPRuntime().emitBarrierCall(
2948 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2949 /*ForceSimpleCall=*/true);
2950 }
2951 EmitOMPPrivateClause(S, LoopScope);
2952 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002953 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002954 (void)LoopScope.Privatize();
2955
2956 // Detect the distribute schedule kind and chunk.
2957 llvm::Value *Chunk = nullptr;
2958 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
2959 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
2960 ScheduleKind = C->getDistScheduleKind();
2961 if (const auto *Ch = C->getChunkSize()) {
2962 Chunk = EmitScalarExpr(Ch);
2963 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2964 S.getIterationVariable()->getType(),
2965 S.getLocStart());
2966 }
2967 }
2968 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2969 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2970
2971 // OpenMP [2.10.8, distribute Construct, Description]
2972 // If dist_schedule is specified, kind must be static. If specified,
2973 // iterations are divided into chunks of size chunk_size, chunks are
2974 // assigned to the teams of the league in a round-robin fashion in the
2975 // order of the team number. When no chunk_size is specified, the
2976 // iteration space is divided into chunks that are approximately equal
2977 // in size, and at most one chunk is distributed to each team of the
2978 // league. The size of the chunks is unspecified in this case.
2979 if (RT.isStaticNonchunked(ScheduleKind,
2980 /* Chunked */ Chunk != nullptr)) {
2981 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
2982 IVSize, IVSigned, /* Ordered = */ false,
2983 IL.getAddress(), LB.getAddress(),
2984 UB.getAddress(), ST.getAddress());
2985 auto LoopExit =
2986 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
2987 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002988 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2989 ? S.getCombinedEnsureUpperBound()
2990 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002991 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002992 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2993 ? S.getCombinedInit()
2994 : S.getInit());
2995
2996 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2997 ? S.getCombinedCond()
2998 : S.getCond();
2999
3000 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003001 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003002 // when combined with 'for' (e.g. as in 'distribute parallel for')
3003 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3004 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3005 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3006 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003007 },
3008 [](CodeGenFunction &) {});
3009 EmitBlock(LoopExit.getBlock());
3010 // Tell the runtime we are done.
3011 RT.emitForStaticFinish(*this, S.getLocStart());
3012 } else {
3013 // Emit the outer loop, which requests its work chunk [LB..UB] from
3014 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003015 const OMPLoopArguments LoopArguments = {
3016 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3017 Chunk};
3018 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3019 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003020 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00003021
3022 // Emit final copy of the lastprivate variables if IsLastIter != 0.
3023 if (HasLastprivateClause)
3024 EmitOMPLastprivateClauseFinal(
3025 S, /*NoFinals=*/false,
3026 Builder.CreateIsNotNull(
3027 EmitLoadOfScalar(IL, S.getLocStart())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003028 }
3029
3030 // We're now done with the loop, so jump to the continuation block.
3031 if (ContBlock) {
3032 EmitBranch(ContBlock);
3033 EmitBlock(ContBlock, true);
3034 }
3035 }
3036}
3037
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003038void CodeGenFunction::EmitOMPDistributeDirective(
3039 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003040 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003041
3042 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003043 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003044 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003045 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
3046 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003047}
3048
Alexey Bataev5f600d62015-09-29 03:48:57 +00003049static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3050 const CapturedStmt *S) {
3051 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3052 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3053 CGF.CapturedStmtInfo = &CapStmtInfo;
3054 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3055 Fn->addFnAttr(llvm::Attribute::NoInline);
3056 return Fn;
3057}
3058
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003059void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8b427062016-05-25 12:36:08 +00003060 if (!S.getAssociatedStmt()) {
3061 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3062 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003063 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003064 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003065 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003066 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3067 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003068 if (C) {
3069 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3070 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3071 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3072 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
3073 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
3074 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003075 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003076 CGF.EmitStmt(
3077 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3078 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003079 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003080 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003081 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003082}
3083
Alexey Bataevb57056f2015-01-22 06:17:56 +00003084static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003085 QualType SrcType, QualType DestType,
3086 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003087 assert(CGF.hasScalarEvaluationKind(DestType) &&
3088 "DestType must have scalar evaluation kind.");
3089 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3090 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003091 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3092 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00003093 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003094 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003095}
3096
3097static CodeGenFunction::ComplexPairTy
3098convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003099 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003100 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3101 "DestType must have complex evaluation kind.");
3102 CodeGenFunction::ComplexPairTy ComplexVal;
3103 if (Val.isScalar()) {
3104 // Convert the input element to the element type of the complex.
3105 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003106 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3107 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003108 ComplexVal = CodeGenFunction::ComplexPairTy(
3109 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3110 } else {
3111 assert(Val.isComplex() && "Must be a scalar or complex.");
3112 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3113 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3114 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003115 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003116 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003117 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003118 }
3119 return ComplexVal;
3120}
3121
Alexey Bataev5e018f92015-04-23 06:35:10 +00003122static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3123 LValue LVal, RValue RVal) {
3124 if (LVal.isGlobalReg()) {
3125 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3126 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003127 CGF.EmitAtomicStore(RVal, LVal,
3128 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3129 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003130 LVal.isVolatile(), /*IsInit=*/false);
3131 }
3132}
3133
Alexey Bataev8524d152016-01-21 12:35:58 +00003134void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3135 QualType RValTy, SourceLocation Loc) {
3136 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003137 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003138 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3139 *this, RVal, RValTy, LVal.getType(), Loc)),
3140 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003141 break;
3142 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003143 EmitStoreOfComplex(
3144 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003145 /*isInit=*/false);
3146 break;
3147 case TEK_Aggregate:
3148 llvm_unreachable("Must be a scalar or complex.");
3149 }
3150}
3151
Alexey Bataevb57056f2015-01-22 06:17:56 +00003152static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3153 const Expr *X, const Expr *V,
3154 SourceLocation Loc) {
3155 // v = x;
3156 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3157 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3158 LValue XLValue = CGF.EmitLValue(X);
3159 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003160 RValue Res = XLValue.isGlobalReg()
3161 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003162 : CGF.EmitAtomicLoad(
3163 XLValue, Loc,
3164 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3165 : llvm::AtomicOrdering::Monotonic,
3166 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003167 // OpenMP, 2.12.6, atomic Construct
3168 // Any atomic construct with a seq_cst clause forces the atomically
3169 // performed operation to include an implicit flush operation without a
3170 // list.
3171 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003172 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003173 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003174}
3175
Alexey Bataevb8329262015-02-27 06:33:30 +00003176static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3177 const Expr *X, const Expr *E,
3178 SourceLocation Loc) {
3179 // x = expr;
3180 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003181 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003182 // OpenMP, 2.12.6, atomic Construct
3183 // Any atomic construct with a seq_cst clause forces the atomically
3184 // performed operation to include an implicit flush operation without a
3185 // list.
3186 if (IsSeqCst)
3187 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3188}
3189
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003190static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3191 RValue Update,
3192 BinaryOperatorKind BO,
3193 llvm::AtomicOrdering AO,
3194 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003195 auto &Context = CGF.CGM.getContext();
3196 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003197 // expression is simple and atomic is allowed for the given type for the
3198 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003199 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003200 !Update.getScalarVal()->getType()->isIntegerTy() ||
3201 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3202 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003203 X.getAddress().getElementType())) ||
3204 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003205 !Context.getTargetInfo().hasBuiltinAtomic(
3206 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003207 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003208
3209 llvm::AtomicRMWInst::BinOp RMWOp;
3210 switch (BO) {
3211 case BO_Add:
3212 RMWOp = llvm::AtomicRMWInst::Add;
3213 break;
3214 case BO_Sub:
3215 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003216 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003217 RMWOp = llvm::AtomicRMWInst::Sub;
3218 break;
3219 case BO_And:
3220 RMWOp = llvm::AtomicRMWInst::And;
3221 break;
3222 case BO_Or:
3223 RMWOp = llvm::AtomicRMWInst::Or;
3224 break;
3225 case BO_Xor:
3226 RMWOp = llvm::AtomicRMWInst::Xor;
3227 break;
3228 case BO_LT:
3229 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3230 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3231 : llvm::AtomicRMWInst::Max)
3232 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3233 : llvm::AtomicRMWInst::UMax);
3234 break;
3235 case BO_GT:
3236 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3237 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3238 : llvm::AtomicRMWInst::Min)
3239 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3240 : llvm::AtomicRMWInst::UMin);
3241 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003242 case BO_Assign:
3243 RMWOp = llvm::AtomicRMWInst::Xchg;
3244 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003245 case BO_Mul:
3246 case BO_Div:
3247 case BO_Rem:
3248 case BO_Shl:
3249 case BO_Shr:
3250 case BO_LAnd:
3251 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003252 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003253 case BO_PtrMemD:
3254 case BO_PtrMemI:
3255 case BO_LE:
3256 case BO_GE:
3257 case BO_EQ:
3258 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003259 case BO_AddAssign:
3260 case BO_SubAssign:
3261 case BO_AndAssign:
3262 case BO_OrAssign:
3263 case BO_XorAssign:
3264 case BO_MulAssign:
3265 case BO_DivAssign:
3266 case BO_RemAssign:
3267 case BO_ShlAssign:
3268 case BO_ShrAssign:
3269 case BO_Comma:
3270 llvm_unreachable("Unsupported atomic update operation");
3271 }
3272 auto *UpdateVal = Update.getScalarVal();
3273 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3274 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003275 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003276 X.getType()->hasSignedIntegerRepresentation());
3277 }
John McCall7f416cc2015-09-08 08:05:57 +00003278 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003279 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003280}
3281
Alexey Bataev5e018f92015-04-23 06:35:10 +00003282std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003283 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3284 llvm::AtomicOrdering AO, SourceLocation Loc,
3285 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3286 // Update expressions are allowed to have the following forms:
3287 // x binop= expr; -> xrval + expr;
3288 // x++, ++x -> xrval + 1;
3289 // x--, --x -> xrval - 1;
3290 // x = x binop expr; -> xrval binop expr
3291 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003292 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3293 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003294 if (X.isGlobalReg()) {
3295 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3296 // 'xrval'.
3297 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3298 } else {
3299 // Perform compare-and-swap procedure.
3300 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003301 }
3302 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003303 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003304}
3305
3306static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3307 const Expr *X, const Expr *E,
3308 const Expr *UE, bool IsXLHSInRHSPart,
3309 SourceLocation Loc) {
3310 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3311 "Update expr in 'atomic update' must be a binary operator.");
3312 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3313 // Update expressions are allowed to have the following forms:
3314 // x binop= expr; -> xrval + expr;
3315 // x++, ++x -> xrval + 1;
3316 // x--, --x -> xrval - 1;
3317 // x = x binop expr; -> xrval binop expr
3318 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003319 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003320 LValue XLValue = CGF.EmitLValue(X);
3321 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003322 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3323 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003324 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3325 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3326 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3327 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3328 auto Gen =
3329 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3330 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3331 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3332 return CGF.EmitAnyExpr(UE);
3333 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003334 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3335 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3336 // OpenMP, 2.12.6, atomic Construct
3337 // Any atomic construct with a seq_cst clause forces the atomically
3338 // performed operation to include an implicit flush operation without a
3339 // list.
3340 if (IsSeqCst)
3341 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3342}
3343
3344static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003345 QualType SourceType, QualType ResType,
3346 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003347 switch (CGF.getEvaluationKind(ResType)) {
3348 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003349 return RValue::get(
3350 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003351 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003352 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003353 return RValue::getComplex(Res.first, Res.second);
3354 }
3355 case TEK_Aggregate:
3356 break;
3357 }
3358 llvm_unreachable("Must be a scalar or complex.");
3359}
3360
3361static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3362 bool IsPostfixUpdate, const Expr *V,
3363 const Expr *X, const Expr *E,
3364 const Expr *UE, bool IsXLHSInRHSPart,
3365 SourceLocation Loc) {
3366 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3367 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3368 RValue NewVVal;
3369 LValue VLValue = CGF.EmitLValue(V);
3370 LValue XLValue = CGF.EmitLValue(X);
3371 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003372 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3373 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003374 QualType NewVValType;
3375 if (UE) {
3376 // 'x' is updated with some additional value.
3377 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3378 "Update expr in 'atomic capture' must be a binary operator.");
3379 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3380 // Update expressions are allowed to have the following forms:
3381 // x binop= expr; -> xrval + expr;
3382 // x++, ++x -> xrval + 1;
3383 // x--, --x -> xrval - 1;
3384 // x = x binop expr; -> xrval binop expr
3385 // x = expr Op x; - > expr binop xrval;
3386 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3387 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3388 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3389 NewVValType = XRValExpr->getType();
3390 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3391 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003392 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003393 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3394 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3395 RValue Res = CGF.EmitAnyExpr(UE);
3396 NewVVal = IsPostfixUpdate ? XRValue : Res;
3397 return Res;
3398 };
3399 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3400 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3401 if (Res.first) {
3402 // 'atomicrmw' instruction was generated.
3403 if (IsPostfixUpdate) {
3404 // Use old value from 'atomicrmw'.
3405 NewVVal = Res.second;
3406 } else {
3407 // 'atomicrmw' does not provide new value, so evaluate it using old
3408 // value of 'x'.
3409 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3410 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3411 NewVVal = CGF.EmitAnyExpr(UE);
3412 }
3413 }
3414 } else {
3415 // 'x' is simply rewritten with some 'expr'.
3416 NewVValType = X->getType().getNonReferenceType();
3417 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003418 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003419 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003420 NewVVal = XRValue;
3421 return ExprRValue;
3422 };
3423 // Try to perform atomicrmw xchg, otherwise simple exchange.
3424 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3425 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3426 Loc, Gen);
3427 if (Res.first) {
3428 // 'atomicrmw' instruction was generated.
3429 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3430 }
3431 }
3432 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003433 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003434 // OpenMP, 2.12.6, atomic Construct
3435 // Any atomic construct with a seq_cst clause forces the atomically
3436 // performed operation to include an implicit flush operation without a
3437 // list.
3438 if (IsSeqCst)
3439 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3440}
3441
Alexey Bataevb57056f2015-01-22 06:17:56 +00003442static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003443 bool IsSeqCst, bool IsPostfixUpdate,
3444 const Expr *X, const Expr *V, const Expr *E,
3445 const Expr *UE, bool IsXLHSInRHSPart,
3446 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003447 switch (Kind) {
3448 case OMPC_read:
3449 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3450 break;
3451 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003452 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3453 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003454 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003455 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003456 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3457 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003458 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003459 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3460 IsXLHSInRHSPart, Loc);
3461 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003462 case OMPC_if:
3463 case OMPC_final:
3464 case OMPC_num_threads:
3465 case OMPC_private:
3466 case OMPC_firstprivate:
3467 case OMPC_lastprivate:
3468 case OMPC_reduction:
3469 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003470 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003471 case OMPC_collapse:
3472 case OMPC_default:
3473 case OMPC_seq_cst:
3474 case OMPC_shared:
3475 case OMPC_linear:
3476 case OMPC_aligned:
3477 case OMPC_copyin:
3478 case OMPC_copyprivate:
3479 case OMPC_flush:
3480 case OMPC_proc_bind:
3481 case OMPC_schedule:
3482 case OMPC_ordered:
3483 case OMPC_nowait:
3484 case OMPC_untied:
3485 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003486 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003487 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003488 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003489 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003490 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003491 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003492 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003493 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003494 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003495 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003496 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003497 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003498 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003499 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003500 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003501 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003502 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003503 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003504 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003505 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003506 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3507 }
3508}
3509
3510void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003511 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003512 OpenMPClauseKind Kind = OMPC_unknown;
3513 for (auto *C : S.clauses()) {
3514 // Find first clause (skip seq_cst clause, if it is first).
3515 if (C->getClauseKind() != OMPC_seq_cst) {
3516 Kind = C->getClauseKind();
3517 break;
3518 }
3519 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003520
3521 const auto *CS =
3522 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003523 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003524 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003525 }
3526 // Processing for statements under 'atomic capture'.
3527 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3528 for (const auto *C : Compound->body()) {
3529 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3530 enterFullExpression(EWC);
3531 }
3532 }
3533 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003534
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003535 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3536 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003537 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003538 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3539 S.getV(), S.getExpr(), S.getUpdateExpr(),
3540 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003541 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003542 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003543 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003544}
3545
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003546static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3547 const OMPExecutableDirective &S,
3548 const RegionCodeGenTy &CodeGen) {
3549 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3550 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00003551 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
3552
Samuel Antaoee8fb302016-01-06 13:42:12 +00003553 llvm::Function *Fn = nullptr;
3554 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003555
Samuel Antaobed3c462015-10-02 16:14:20 +00003556 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003557 // Check for the at most one if clause associated with the target region.
3558 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3559 if (C->getNameModifier() == OMPD_unknown ||
3560 C->getNameModifier() == OMPD_target) {
3561 IfCond = C->getCondition();
3562 break;
3563 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003564 }
3565
3566 // Check if we have any device clause associated with the directive.
3567 const Expr *Device = nullptr;
3568 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3569 Device = C->getDevice();
3570 }
3571
Samuel Antaoee8fb302016-01-06 13:42:12 +00003572 // Check if we have an if clause whose conditional always evaluates to false
3573 // or if we do not have any targets specified. If so the target region is not
3574 // an offload entry point.
3575 bool IsOffloadEntry = true;
3576 if (IfCond) {
3577 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003578 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003579 IsOffloadEntry = false;
3580 }
3581 if (CGM.getLangOpts().OMPTargetTriples.empty())
3582 IsOffloadEntry = false;
3583
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003584 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003585 StringRef ParentName;
3586 // In case we have Ctors/Dtors we use the complete type variant to produce
3587 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003588 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003589 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003590 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003591 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3592 else
3593 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003594 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003595
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003596 // Emit target region as a standalone region.
3597 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3598 IsOffloadEntry, CodeGen);
3599 OMPLexicalScope Scope(CGF, S);
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003600 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3601 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003602 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003603 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003604}
3605
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003606static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3607 PrePostActionTy &Action) {
3608 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3609 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3610 CGF.EmitOMPPrivateClause(S, PrivateScope);
3611 (void)PrivateScope.Privatize();
3612
3613 Action.Enter(CGF);
3614 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3615}
3616
3617void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3618 StringRef ParentName,
3619 const OMPTargetDirective &S) {
3620 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3621 emitTargetRegion(CGF, S, Action);
3622 };
3623 llvm::Function *Fn;
3624 llvm::Constant *Addr;
3625 // Emit target region as a standalone region.
3626 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3627 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3628 assert(Fn && Addr && "Target device function emission failed.");
3629}
3630
3631void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3632 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3633 emitTargetRegion(CGF, S, Action);
3634 };
3635 emitCommonOMPTargetDirective(*this, S, CodeGen);
3636}
3637
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003638static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3639 const OMPExecutableDirective &S,
3640 OpenMPDirectiveKind InnermostKind,
3641 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003642 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
3643 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
3644 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003645
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003646 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
3647 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003648 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003649 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3650 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003651
Carlo Bertollic6872252016-04-04 15:55:02 +00003652 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3653 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003654 }
3655
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003656 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003657 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3658 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003659 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3660 CapturedVars);
3661}
3662
3663void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00003664 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003665 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003666 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003667 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3668 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003669 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003670 (void)PrivateScope.Privatize();
3671 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003672 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003673 };
3674 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003675 emitPostUpdateForReductionClause(
3676 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00003677}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003678
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003679static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
3680 const OMPTargetTeamsDirective &S) {
3681 auto *CS = S.getCapturedStmt(OMPD_teams);
3682 Action.Enter(CGF);
3683 auto &&CodeGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3684 // TODO: Add support for clauses.
3685 CGF.EmitStmt(CS->getCapturedStmt());
3686 };
3687 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
3688}
3689
3690void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
3691 CodeGenModule &CGM, StringRef ParentName,
3692 const OMPTargetTeamsDirective &S) {
3693 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3694 emitTargetTeamsRegion(CGF, Action, S);
3695 };
3696 llvm::Function *Fn;
3697 llvm::Constant *Addr;
3698 // Emit target region as a standalone region.
3699 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3700 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3701 assert(Fn && Addr && "Target device function emission failed.");
3702}
3703
3704void CodeGenFunction::EmitOMPTargetTeamsDirective(
3705 const OMPTargetTeamsDirective &S) {
3706 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3707 emitTargetTeamsRegion(CGF, Action, S);
3708 };
3709 emitCommonOMPTargetDirective(*this, S, CodeGen);
3710}
3711
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003712void CodeGenFunction::EmitOMPCancellationPointDirective(
3713 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00003714 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
3715 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003716}
3717
Alexey Bataev80909872015-07-02 11:25:17 +00003718void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003719 const Expr *IfCond = nullptr;
3720 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3721 if (C->getNameModifier() == OMPD_unknown ||
3722 C->getNameModifier() == OMPD_cancel) {
3723 IfCond = C->getCondition();
3724 break;
3725 }
3726 }
3727 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003728 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00003729}
3730
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003731CodeGenFunction::JumpDest
3732CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00003733 if (Kind == OMPD_parallel || Kind == OMPD_task ||
3734 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003735 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003736 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00003737 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
3738 Kind == OMPD_distribute_parallel_for ||
3739 Kind == OMPD_target_parallel_for);
3740 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003741}
Michael Wong65f367f2015-07-21 13:44:28 +00003742
Samuel Antaocc10b852016-07-28 14:23:26 +00003743void CodeGenFunction::EmitOMPUseDevicePtrClause(
3744 const OMPClause &NC, OMPPrivateScope &PrivateScope,
3745 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
3746 const auto &C = cast<OMPUseDevicePtrClause>(NC);
3747 auto OrigVarIt = C.varlist_begin();
3748 auto InitIt = C.inits().begin();
3749 for (auto PvtVarIt : C.private_copies()) {
3750 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
3751 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
3752 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
3753
3754 // In order to identify the right initializer we need to match the
3755 // declaration used by the mapping logic. In some cases we may get
3756 // OMPCapturedExprDecl that refers to the original declaration.
3757 const ValueDecl *MatchingVD = OrigVD;
3758 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
3759 // OMPCapturedExprDecl are used to privative fields of the current
3760 // structure.
3761 auto *ME = cast<MemberExpr>(OED->getInit());
3762 assert(isa<CXXThisExpr>(ME->getBase()) &&
3763 "Base should be the current struct!");
3764 MatchingVD = ME->getMemberDecl();
3765 }
3766
3767 // If we don't have information about the current list item, move on to
3768 // the next one.
3769 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
3770 if (InitAddrIt == CaptureDeviceAddrMap.end())
3771 continue;
3772
3773 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
3774 // Initialize the temporary initialization variable with the address we
3775 // get from the runtime library. We have to cast the source address
3776 // because it is always a void *. References are materialized in the
3777 // privatization scope, so the initialization here disregards the fact
3778 // the original variable is a reference.
3779 QualType AddrQTy =
3780 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
3781 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
3782 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
3783 setAddrOfLocalVar(InitVD, InitAddr);
3784
3785 // Emit private declaration, it will be initialized by the value we
3786 // declaration we just added to the local declarations map.
3787 EmitDecl(*PvtVD);
3788
3789 // The initialization variables reached its purpose in the emission
3790 // ofthe previous declaration, so we don't need it anymore.
3791 LocalDeclMap.erase(InitVD);
3792
3793 // Return the address of the private variable.
3794 return GetAddrOfLocalVar(PvtVD);
3795 });
3796 assert(IsRegistered && "firstprivate var already registered as private");
3797 // Silence the warning about unused variable.
3798 (void)IsRegistered;
3799
3800 ++OrigVarIt;
3801 ++InitIt;
3802 }
3803}
3804
Michael Wong65f367f2015-07-21 13:44:28 +00003805// Generate the instructions for '#pragma omp target data' directive.
3806void CodeGenFunction::EmitOMPTargetDataDirective(
3807 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00003808 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
3809
3810 // Create a pre/post action to signal the privatization of the device pointer.
3811 // This action can be replaced by the OpenMP runtime code generation to
3812 // deactivate privatization.
3813 bool PrivatizeDevicePointers = false;
3814 class DevicePointerPrivActionTy : public PrePostActionTy {
3815 bool &PrivatizeDevicePointers;
3816
3817 public:
3818 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
3819 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
3820 void Enter(CodeGenFunction &CGF) override {
3821 PrivatizeDevicePointers = true;
3822 }
Samuel Antaodf158d52016-04-27 22:58:19 +00003823 };
Samuel Antaocc10b852016-07-28 14:23:26 +00003824 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
3825
3826 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
3827 CodeGenFunction &CGF, PrePostActionTy &Action) {
3828 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3829 CGF.EmitStmt(
3830 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3831 };
3832
3833 // Codegen that selects wheather to generate the privatization code or not.
3834 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
3835 &InnermostCodeGen](CodeGenFunction &CGF,
3836 PrePostActionTy &Action) {
3837 RegionCodeGenTy RCG(InnermostCodeGen);
3838 PrivatizeDevicePointers = false;
3839
3840 // Call the pre-action to change the status of PrivatizeDevicePointers if
3841 // needed.
3842 Action.Enter(CGF);
3843
3844 if (PrivatizeDevicePointers) {
3845 OMPPrivateScope PrivateScope(CGF);
3846 // Emit all instances of the use_device_ptr clause.
3847 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
3848 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
3849 Info.CaptureDeviceAddrMap);
3850 (void)PrivateScope.Privatize();
3851 RCG(CGF);
3852 } else
3853 RCG(CGF);
3854 };
3855
3856 // Forward the provided action to the privatization codegen.
3857 RegionCodeGenTy PrivRCG(PrivCodeGen);
3858 PrivRCG.setAction(Action);
3859
3860 // Notwithstanding the body of the region is emitted as inlined directive,
3861 // we don't use an inline scope as changes in the references inside the
3862 // region are expected to be visible outside, so we do not privative them.
3863 OMPLexicalScope Scope(CGF, S);
3864 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
3865 PrivRCG);
3866 };
3867
3868 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00003869
3870 // If we don't have target devices, don't bother emitting the data mapping
3871 // code.
3872 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00003873 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00003874 return;
3875 }
3876
3877 // Check if we have any if clause associated with the directive.
3878 const Expr *IfCond = nullptr;
3879 if (auto *C = S.getSingleClause<OMPIfClause>())
3880 IfCond = C->getCondition();
3881
3882 // Check if we have any device clause associated with the directive.
3883 const Expr *Device = nullptr;
3884 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3885 Device = C->getDevice();
3886
Samuel Antaocc10b852016-07-28 14:23:26 +00003887 // Set the action to signal privatization of device pointers.
3888 RCG.setAction(PrivAction);
3889
3890 // Emit region code.
3891 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
3892 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00003893}
Alexey Bataev49f6e782015-12-01 04:18:41 +00003894
Samuel Antaodf67fc42016-01-19 19:15:56 +00003895void CodeGenFunction::EmitOMPTargetEnterDataDirective(
3896 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00003897 // If we don't have target devices, don't bother emitting the data mapping
3898 // code.
3899 if (CGM.getLangOpts().OMPTargetTriples.empty())
3900 return;
3901
3902 // Check if we have any if clause associated with the directive.
3903 const Expr *IfCond = nullptr;
3904 if (auto *C = S.getSingleClause<OMPIfClause>())
3905 IfCond = C->getCondition();
3906
3907 // Check if we have any device clause associated with the directive.
3908 const Expr *Device = nullptr;
3909 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3910 Device = C->getDevice();
3911
Samuel Antao8d2d7302016-05-26 18:30:22 +00003912 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003913}
3914
Samuel Antao72590762016-01-19 20:04:50 +00003915void CodeGenFunction::EmitOMPTargetExitDataDirective(
3916 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00003917 // If we don't have target devices, don't bother emitting the data mapping
3918 // code.
3919 if (CGM.getLangOpts().OMPTargetTriples.empty())
3920 return;
3921
3922 // Check if we have any if clause associated with the directive.
3923 const Expr *IfCond = nullptr;
3924 if (auto *C = S.getSingleClause<OMPIfClause>())
3925 IfCond = C->getCondition();
3926
3927 // Check if we have any device clause associated with the directive.
3928 const Expr *Device = nullptr;
3929 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3930 Device = C->getDevice();
3931
Samuel Antao8d2d7302016-05-26 18:30:22 +00003932 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00003933}
3934
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003935static void emitTargetParallelRegion(CodeGenFunction &CGF,
3936 const OMPTargetParallelDirective &S,
3937 PrePostActionTy &Action) {
3938 // Get the captured statement associated with the 'parallel' region.
3939 auto *CS = S.getCapturedStmt(OMPD_parallel);
3940 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003941 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
3942 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3943 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3944 CGF.EmitOMPPrivateClause(S, PrivateScope);
3945 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3946 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003947 // TODO: Add support for clauses.
3948 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003949 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003950 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003951 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
3952 emitEmptyBoundParameters);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003953 emitPostUpdateForReductionClause(
3954 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003955}
3956
3957void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
3958 CodeGenModule &CGM, StringRef ParentName,
3959 const OMPTargetParallelDirective &S) {
3960 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3961 emitTargetParallelRegion(CGF, S, Action);
3962 };
3963 llvm::Function *Fn;
3964 llvm::Constant *Addr;
3965 // Emit target region as a standalone region.
3966 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3967 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3968 assert(Fn && Addr && "Target device function emission failed.");
3969}
3970
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003971void CodeGenFunction::EmitOMPTargetParallelDirective(
3972 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003973 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3974 emitTargetParallelRegion(CGF, S, Action);
3975 };
3976 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003977}
3978
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003979void CodeGenFunction::EmitOMPTargetParallelForDirective(
3980 const OMPTargetParallelForDirective &S) {
3981 // TODO: codegen for target parallel for.
3982}
3983
Alexey Bataev7292c292016-04-25 12:22:29 +00003984/// Emit a helper variable and return corresponding lvalue.
3985static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
3986 const ImplicitParamDecl *PVD,
3987 CodeGenFunction::OMPPrivateScope &Privates) {
3988 auto *VDecl = cast<VarDecl>(Helper->getDecl());
3989 Privates.addPrivate(
3990 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
3991}
3992
3993void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
3994 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
3995 // Emit outlined function for task construct.
3996 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3997 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
3998 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3999 const Expr *IfCond = nullptr;
4000 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4001 if (C->getNameModifier() == OMPD_unknown ||
4002 C->getNameModifier() == OMPD_taskloop) {
4003 IfCond = C->getCondition();
4004 break;
4005 }
4006 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004007
4008 OMPTaskDataTy Data;
4009 // Check if taskloop must be emitted without taskgroup.
4010 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004011 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004012 Data.Tied = true;
4013 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004014 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4015 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004016 Data.Schedule.setInt(/*IntVal=*/false);
4017 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004018 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4019 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004020 Data.Schedule.setInt(/*IntVal=*/true);
4021 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004022 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004023
4024 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4025 // if (PreCond) {
4026 // for (IV in 0..LastIteration) BODY;
4027 // <Final counter/linear vars updates>;
4028 // }
4029 //
4030
4031 // Emit: if (PreCond) - begin.
4032 // If the condition constant folds and can be elided, avoid emitting the
4033 // whole loop.
4034 bool CondConstant;
4035 llvm::BasicBlock *ContBlock = nullptr;
4036 OMPLoopScope PreInitScope(CGF, S);
4037 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4038 if (!CondConstant)
4039 return;
4040 } else {
4041 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4042 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4043 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4044 CGF.getProfileCount(&S));
4045 CGF.EmitBlock(ThenBlock);
4046 CGF.incrementProfileCounter(&S);
4047 }
4048
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004049 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4050 CGF.EmitOMPSimdInit(S);
4051
Alexey Bataev7292c292016-04-25 12:22:29 +00004052 OMPPrivateScope LoopScope(CGF);
4053 // Emit helper vars inits.
4054 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4055 auto *I = CS->getCapturedDecl()->param_begin();
4056 auto *LBP = std::next(I, LowerBound);
4057 auto *UBP = std::next(I, UpperBound);
4058 auto *STP = std::next(I, Stride);
4059 auto *LIP = std::next(I, LastIter);
4060 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4061 LoopScope);
4062 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4063 LoopScope);
4064 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4065 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4066 LoopScope);
4067 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004068 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004069 (void)LoopScope.Privatize();
4070 // Emit the loop iteration variable.
4071 const Expr *IVExpr = S.getIterationVariable();
4072 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4073 CGF.EmitVarDecl(*IVDecl);
4074 CGF.EmitIgnoredExpr(S.getInit());
4075
4076 // Emit the iterations count variable.
4077 // If it is not a variable, Sema decided to calculate iterations count on
4078 // each iteration (e.g., it is foldable into a constant).
4079 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4080 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4081 // Emit calculation of the iterations count.
4082 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4083 }
4084
4085 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4086 S.getInc(),
4087 [&S](CodeGenFunction &CGF) {
4088 CGF.EmitOMPLoopBody(S, JumpDest());
4089 CGF.EmitStopPoint(&S);
4090 },
4091 [](CodeGenFunction &) {});
4092 // Emit: if (PreCond) - end.
4093 if (ContBlock) {
4094 CGF.EmitBranch(ContBlock);
4095 CGF.EmitBlock(ContBlock, true);
4096 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004097 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4098 if (HasLastprivateClause) {
4099 CGF.EmitOMPLastprivateClauseFinal(
4100 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4101 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4102 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4103 (*LIP)->getType(), S.getLocStart())));
4104 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004105 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004106 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4107 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4108 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004109 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4110 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004111 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4112 OutlinedFn, SharedsTy,
4113 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004114 };
4115 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4116 CodeGen);
4117 };
Alexey Bataev33446032017-07-12 18:09:32 +00004118 if (Data.Nogroup)
4119 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4120 else {
4121 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4122 *this,
4123 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4124 PrePostActionTy &Action) {
4125 Action.Enter(CGF);
4126 CGF.EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4127 },
4128 S.getLocStart());
4129 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004130}
4131
Alexey Bataev49f6e782015-12-01 04:18:41 +00004132void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004133 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004134}
4135
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004136void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4137 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004138 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004139}
Samuel Antao686c70c2016-05-26 17:30:50 +00004140
4141// Generate the instructions for '#pragma omp target update' directive.
4142void CodeGenFunction::EmitOMPTargetUpdateDirective(
4143 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00004144 // If we don't have target devices, don't bother emitting the data mapping
4145 // code.
4146 if (CGM.getLangOpts().OMPTargetTriples.empty())
4147 return;
4148
4149 // Check if we have any if clause associated with the directive.
4150 const Expr *IfCond = nullptr;
4151 if (auto *C = S.getSingleClause<OMPIfClause>())
4152 IfCond = C->getCondition();
4153
4154 // Check if we have any device clause associated with the directive.
4155 const Expr *Device = nullptr;
4156 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4157 Device = C->getDevice();
4158
4159 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00004160}