blob: f9861735832bfee4bed5d0104bb2e32480239c98 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit OpenMP nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Alexey Bataev3392d762016-02-16 11:18:12 +000014#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "CGOpenMPRuntime.h"
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000018#include "TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Stmt.h"
20#include "clang/AST/StmtOpenMP.h"
Alexey Bataev2bbf7212016-03-03 03:52:24 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000022#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023using namespace clang;
24using namespace CodeGen;
25
Alexey Bataev3392d762016-02-16 11:18:12 +000026namespace {
27/// Lexical scope for OpenMP executable constructs, that handles correct codegen
28/// for captured expressions.
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000029class OMPLexicalScope : public CodeGenFunction::LexicalScope {
Alexey Bataev3392d762016-02-16 11:18:12 +000030 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
31 for (const auto *C : S.clauses()) {
32 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
33 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000034 for (const auto *I : PreInit->decls()) {
35 if (!I->hasAttr<OMPCaptureNoInitAttr>())
36 CGF.EmitVarDecl(cast<VarDecl>(*I));
37 else {
38 CodeGenFunction::AutoVarEmission Emission =
39 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
40 CGF.EmitAutoVarCleanups(Emission);
41 }
42 }
Alexey Bataev3392d762016-02-16 11:18:12 +000043 }
44 }
45 }
46 }
Alexey Bataev4ba78a42016-04-27 07:56:03 +000047 CodeGenFunction::OMPPrivateScope InlinedShareds;
48
49 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
50 return CGF.LambdaCaptureFields.lookup(VD) ||
51 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
52 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
53 }
Alexey Bataev3392d762016-02-16 11:18:12 +000054
Alexey Bataev3392d762016-02-16 11:18:12 +000055public:
Alexey Bataev4ba78a42016-04-27 07:56:03 +000056 OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S,
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000057 bool AsInlined = false, bool EmitPreInitStmt = true)
Alexey Bataev4ba78a42016-04-27 07:56:03 +000058 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
59 InlinedShareds(CGF) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000060 if (EmitPreInitStmt)
61 emitPreInitStmt(CGF, S);
Alexey Bataev4ba78a42016-04-27 07:56:03 +000062 if (AsInlined) {
63 if (S.hasAssociatedStmt()) {
64 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
65 for (auto &C : CS->captures()) {
66 if (C.capturesVariable() || C.capturesVariableByCopy()) {
67 auto *VD = C.getCapturedVar();
Alexey Bataev6a71f362017-08-22 17:54:52 +000068 assert(VD == VD->getCanonicalDecl() &&
69 "Canonical decl must be captured.");
Alexey Bataev4ba78a42016-04-27 07:56:03 +000070 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
71 isCapturedVar(CGF, VD) ||
72 (CGF.CapturedStmtInfo &&
73 InlinedShareds.isGlobalVarCaptured(VD)),
74 VD->getType().getNonReferenceType(), VK_LValue,
75 SourceLocation());
76 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
77 return CGF.EmitLValue(&DRE).getAddress();
78 });
79 }
80 }
81 (void)InlinedShareds.Privatize();
82 }
83 }
Alexey Bataev3392d762016-02-16 11:18:12 +000084 }
85};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000086
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000087/// Lexical scope for OpenMP parallel construct, that handles correct codegen
88/// for captured expressions.
89class OMPParallelScope final : public OMPLexicalScope {
90 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
91 OpenMPDirectiveKind Kind = S.getDirectiveKind();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +000092 return !(isOpenMPTargetExecutionDirective(Kind) ||
93 isOpenMPLoopBoundSharingDirective(Kind)) &&
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000094 isOpenMPParallelDirective(Kind);
95 }
96
97public:
98 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
99 : OMPLexicalScope(CGF, S,
100 /*AsInlined=*/false,
101 /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
102};
103
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000104/// Lexical scope for OpenMP teams construct, that handles correct codegen
105/// for captured expressions.
106class OMPTeamsScope final : public OMPLexicalScope {
107 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
108 OpenMPDirectiveKind Kind = S.getDirectiveKind();
109 return !isOpenMPTargetExecutionDirective(Kind) &&
110 isOpenMPTeamsDirective(Kind);
111 }
112
113public:
114 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
115 : OMPLexicalScope(CGF, S,
116 /*AsInlined=*/false,
117 /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
118};
119
Alexey Bataev5a3af132016-03-29 08:58:54 +0000120/// Private scope for OpenMP loop-based directives, that supports capturing
121/// of used expression from loop statement.
122class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
123 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
Alexey Bataevc2e88a82017-12-04 21:30:42 +0000124 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeve83b3e82017-12-08 20:18:58 +0000125 for (auto *E : S.counters()) {
126 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
127 (void)PreCondScope.addPrivate(VD, [&CGF, VD]() {
128 return CGF.CreateMemTemp(VD->getType().getNonReferenceType());
129 });
130 }
Alexey Bataevc2e88a82017-12-04 21:30:42 +0000131 (void)PreCondScope.Privatize();
Alexey Bataev5a3af132016-03-29 08:58:54 +0000132 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
133 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
134 for (const auto *I : PreInits->decls())
135 CGF.EmitVarDecl(cast<VarDecl>(*I));
136 }
137 }
138 }
139
140public:
141 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
142 : CodeGenFunction::RunCleanupsScope(CGF) {
143 emitPreInitStmt(CGF, S);
144 }
145};
146
Alexey Bataev3392d762016-02-16 11:18:12 +0000147} // namespace
148
Alexey Bataevf8365372017-11-17 17:57:25 +0000149static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
150 const OMPExecutableDirective &S,
151 const RegionCodeGenTy &CodeGen);
152
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000153LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
154 if (auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
155 if (auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
156 OrigVD = OrigVD->getCanonicalDecl();
157 bool IsCaptured =
158 LambdaCaptureFields.lookup(OrigVD) ||
159 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
160 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
161 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), IsCaptured,
162 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
163 return EmitLValue(&DRE);
164 }
165 }
166 return EmitLValue(E);
167}
168
Alexey Bataev1189bd02016-01-26 12:20:39 +0000169llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
170 auto &C = getContext();
171 llvm::Value *Size = nullptr;
172 auto SizeInChars = C.getTypeSizeInChars(Ty);
173 if (SizeInChars.isZero()) {
174 // getTypeSizeInChars() returns 0 for a VLA.
175 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
176 llvm::Value *ArraySize;
177 std::tie(ArraySize, Ty) = getVLASize(VAT);
178 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
179 }
180 SizeInChars = C.getTypeSizeInChars(Ty);
181 if (SizeInChars.isZero())
182 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
183 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
184 } else
185 Size = CGM.getSize(SizeInChars);
186 return Size;
187}
188
Alexey Bataev2377fe92015-09-10 08:12:02 +0000189void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000190 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000191 const RecordDecl *RD = S.getCapturedRecordDecl();
192 auto CurField = RD->field_begin();
193 auto CurCap = S.captures().begin();
194 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
195 E = S.capture_init_end();
196 I != E; ++I, ++CurField, ++CurCap) {
197 if (CurField->hasCapturedVLAType()) {
198 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000199 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000200 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000201 } else if (CurCap->capturesThis())
202 CapturedVars.push_back(CXXThisValue);
Samuel Antao6d004262016-06-16 18:39:34 +0000203 else if (CurCap->capturesVariableByCopy()) {
204 llvm::Value *CV =
205 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal();
206
207 // If the field is not a pointer, we need to save the actual value
208 // and load it as a void pointer.
209 if (!CurField->getType()->isAnyPointerType()) {
210 auto &Ctx = getContext();
211 auto DstAddr = CreateMemTemp(
212 Ctx.getUIntPtrType(),
213 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
214 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
215
216 auto *SrcAddrVal = EmitScalarConversion(
217 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
218 Ctx.getPointerType(CurField->getType()), SourceLocation());
219 LValue SrcLV =
220 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
221
222 // Store the value using the source type pointer.
223 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
224
225 // Load the value using the destination type pointer.
226 CV = EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
227 }
228 CapturedVars.push_back(CV);
229 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000230 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000231 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000232 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000233 }
234}
235
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000236static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
237 StringRef Name, LValue AddrLV,
238 bool isReferenceType = false) {
239 ASTContext &Ctx = CGF.getContext();
240
241 auto *CastedPtr = CGF.EmitScalarConversion(
242 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
243 Ctx.getPointerType(DstType), SourceLocation());
244 auto TmpAddr =
245 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
246 .getAddress();
247
248 // If we are dealing with references we need to return the address of the
249 // reference instead of the reference of the value.
250 if (isReferenceType) {
251 QualType RefType = Ctx.getLValueReferenceType(DstType);
252 auto *RefVal = TmpAddr.getPointer();
253 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
254 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
Akira Hatanaka642f7992016-10-18 19:05:41 +0000255 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000256 }
257
258 return TmpAddr;
259}
260
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000261static QualType getCanonicalParamType(ASTContext &C, QualType T) {
262 if (T->isLValueReferenceType()) {
263 return C.getLValueReferenceType(
264 getCanonicalParamType(C, T.getNonReferenceType()),
265 /*SpelledAsLValue=*/false);
266 }
267 if (T->isPointerType())
268 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000269 if (auto *A = T->getAsArrayTypeUnsafe()) {
270 if (auto *VLA = dyn_cast<VariableArrayType>(A))
271 return getCanonicalParamType(C, VLA->getElementType());
272 else if (!A->isVariablyModifiedType())
273 return C.getCanonicalType(T);
274 }
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000275 return C.getCanonicalParamType(T);
276}
277
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000278namespace {
279 /// Contains required data for proper outlined function codegen.
280 struct FunctionOptions {
281 /// Captured statement for which the function is generated.
282 const CapturedStmt *S = nullptr;
283 /// true if cast to/from UIntPtr is required for variables captured by
284 /// value.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000285 const bool UIntPtrCastRequired = true;
Alexey Bataeve754b182017-08-09 19:38:53 +0000286 /// true if only casted arguments must be registered as local args or VLA
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000287 /// sizes.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000288 const bool RegisterCastedArgsOnly = false;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000289 /// Name of the generated function.
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000290 const StringRef FunctionName;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000291 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
292 bool RegisterCastedArgsOnly,
Alexey Bataev4aa19052017-08-08 16:45:36 +0000293 StringRef FunctionName)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000294 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
295 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
Alexey Bataev4aa19052017-08-08 16:45:36 +0000296 FunctionName(FunctionName) {}
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000297 };
298}
299
Alexey Bataeve754b182017-08-09 19:38:53 +0000300static llvm::Function *emitOutlinedFunctionPrologue(
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000301 CodeGenFunction &CGF, FunctionArgList &Args,
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000302 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000303 &LocalAddrs,
304 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
305 &VLASizes,
306 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
307 const CapturedDecl *CD = FO.S->getCapturedDecl();
308 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000309 assert(CD->hasBody() && "missing CapturedDecl body");
310
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000311 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000312 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000313 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000314 ASTContext &Ctx = CGM.getContext();
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000315 FunctionArgList TargetArgs;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000316 Args.append(CD->param_begin(),
317 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000318 TargetArgs.append(
319 CD->param_begin(),
320 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000321 auto I = FO.S->captures().begin();
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000322 FunctionDecl *DebugFunctionDecl = nullptr;
323 if (!FO.UIntPtrCastRequired) {
324 FunctionProtoType::ExtProtoInfo EPI;
325 DebugFunctionDecl = FunctionDecl::Create(
326 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getLocStart(),
327 SourceLocation(), DeclarationName(), Ctx.VoidTy,
328 Ctx.getTrivialTypeSourceInfo(
329 Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI)),
330 SC_Static, /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
331 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000332 for (auto *FD : RD->fields()) {
333 QualType ArgType = FD->getType();
334 IdentifierInfo *II = nullptr;
335 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000336
337 // If this is a capture by copy and the type is not a pointer, the outlined
338 // function argument type should be uintptr and the value properly casted to
339 // uintptr. This is necessary given that the runtime library is only able to
340 // deal with pointers. We can pass in the same way the VLA type sizes to the
341 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000342 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000343 I->capturesVariableArrayType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000344 if (FO.UIntPtrCastRequired)
345 ArgType = Ctx.getUIntPtrType();
346 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000347
348 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000349 CapVar = I->getCapturedVar();
350 II = CapVar->getIdentifier();
351 } else if (I->capturesThis())
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000352 II = &Ctx.Idents.get("this");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000353 else {
354 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000355 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000356 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000357 if (ArgType->isVariablyModifiedType())
Alexey Bataev1b48c5e2017-10-24 19:52:31 +0000358 ArgType = getCanonicalParamType(Ctx, ArgType);
Alexey Bataevb45d43c2017-11-22 16:02:03 +0000359 VarDecl *Arg;
360 if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
361 Arg = ParmVarDecl::Create(
362 Ctx, DebugFunctionDecl,
363 CapVar ? CapVar->getLocStart() : FD->getLocStart(),
364 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
365 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
366 } else {
367 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
368 II, ArgType, ImplicitParamDecl::Other);
369 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000370 Args.emplace_back(Arg);
371 // Do not cast arguments if we emit function with non-original types.
372 TargetArgs.emplace_back(
373 FO.UIntPtrCastRequired
374 ? Arg
375 : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000376 ++I;
377 }
378 Args.append(
379 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
380 CD->param_end());
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000381 TargetArgs.append(
382 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
383 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000384
385 // Create the function declaration.
Alexey Bataev2377fe92015-09-10 08:12:02 +0000386 const CGFunctionInfo &FuncInfo =
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000387 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000388 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
389
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000390 llvm::Function *F =
391 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
392 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000393 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
394 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000395 F->setDoesNotThrow();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000396
397 // Generate the function.
Alexey Bataev6e01dc12017-08-14 16:03:47 +0000398 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
399 FO.S->getLocStart(), CD->getBody()->getLocStart());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000400 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000401 I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000402 for (auto *FD : RD->fields()) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000403 // Do not map arguments if we emit function with non-original types.
404 Address LocalAddr(Address::invalid());
405 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
406 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
407 TargetArgs[Cnt]);
408 } else {
409 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
410 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000411 // If we are capturing a pointer by copy we don't need to do anything, just
412 // use the value that we get from the arguments.
413 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000414 const VarDecl *CurVD = I->getCapturedVar();
Samuel Antao403ffd42016-07-27 22:49:49 +0000415 // If the variable is a reference we need to materialize it here.
416 if (CurVD->getType()->isReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000417 Address RefAddr = CGF.CreateMemTemp(
418 CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
419 CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
420 /*Volatile=*/false, CurVD->getType());
Samuel Antao403ffd42016-07-27 22:49:49 +0000421 LocalAddr = RefAddr;
422 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000423 if (!FO.RegisterCastedArgsOnly)
424 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000425 ++Cnt;
426 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000427 continue;
428 }
429
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000430 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
431 AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000432 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000433 if (FO.UIntPtrCastRequired) {
434 ArgLVal = CGF.MakeAddrLValue(castValueFromUintptr(CGF, FD->getType(),
435 Args[Cnt]->getName(),
436 ArgLVal),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000437 FD->getType(), AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000438 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000439 auto *ExprArg =
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000440 CGF.EmitLoadOfLValue(ArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000441 auto VAT = FD->getCapturedVLAType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000442 VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000443 } else if (I->capturesVariable()) {
444 auto *Var = I->getCapturedVar();
445 QualType VarTy = Var->getType();
446 Address ArgAddr = ArgLVal.getAddress();
447 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000448 if (ArgLVal.getType()->isLValueReferenceType()) {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +0000449 ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000450 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000451 assert(ArgLVal.getType()->isPointerType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000452 ArgAddr = CGF.EmitLoadOfPointer(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000453 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
454 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000455 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000456 if (!FO.RegisterCastedArgsOnly) {
457 LocalAddrs.insert(
458 {Args[Cnt],
459 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
460 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000461 } else if (I->capturesVariableByCopy()) {
462 assert(!FD->getType()->isAnyPointerType() &&
463 "Not expecting a captured pointer.");
464 auto *Var = I->getCapturedVar();
465 QualType VarTy = Var->getType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000466 LocalAddrs.insert(
467 {Args[Cnt],
468 {Var,
469 FO.UIntPtrCastRequired
470 ? castValueFromUintptr(CGF, FD->getType(), Args[Cnt]->getName(),
471 ArgLVal, VarTy->isReferenceType())
472 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000473 } else {
474 // If 'this' is captured, load it into CXXThisValue.
475 assert(I->capturesThis());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000476 CXXThisValue = CGF.EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation())
477 .getScalarVal();
478 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000479 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000480 ++Cnt;
481 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000482 }
483
Alexey Bataeve754b182017-08-09 19:38:53 +0000484 return F;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000485}
486
487llvm::Function *
488CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
489 assert(
490 CapturedStmtInfo &&
491 "CapturedStmtInfo should be set when generating the captured function");
492 const CapturedDecl *CD = S.getCapturedDecl();
493 // Build the argument list.
494 bool NeedWrapperFunction =
495 getDebugInfo() &&
496 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
497 FunctionArgList Args;
Alexey Bataev3b8d5582017-08-08 18:04:06 +0000498 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000499 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve754b182017-08-09 19:38:53 +0000500 SmallString<256> Buffer;
501 llvm::raw_svector_ostream Out(Buffer);
502 Out << CapturedStmtInfo->getHelperName();
503 if (NeedWrapperFunction)
504 Out << "_debug__";
Alexey Bataev4aa19052017-08-08 16:45:36 +0000505 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
Alexey Bataeve754b182017-08-09 19:38:53 +0000506 Out.str());
507 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
508 VLASizes, CXXThisValue, FO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000509 for (const auto &LocalAddrPair : LocalAddrs) {
510 if (LocalAddrPair.second.first) {
511 setAddrOfLocalVar(LocalAddrPair.second.first,
512 LocalAddrPair.second.second);
513 }
514 }
515 for (const auto &VLASizePair : VLASizes)
516 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000517 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000518 CapturedStmtInfo->EmitBody(*this, CD->getBody());
519 FinishFunction(CD->getBodyRBrace());
Alexey Bataeve754b182017-08-09 19:38:53 +0000520 if (!NeedWrapperFunction)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000521 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000522
Alexey Bataevefd884d2017-08-04 21:26:25 +0000523 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
Alexey Bataeve754b182017-08-09 19:38:53 +0000524 /*RegisterCastedArgsOnly=*/true,
525 CapturedStmtInfo->getHelperName());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000526 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000527 Args.clear();
528 LocalAddrs.clear();
529 VLASizes.clear();
530 llvm::Function *WrapperF =
531 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
Alexey Bataeve754b182017-08-09 19:38:53 +0000532 WrapperCGF.CXXThisValue, WrapperFO);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000533 llvm::SmallVector<llvm::Value *, 4> CallArgs;
534 for (const auto *Arg : Args) {
535 llvm::Value *CallArg;
536 auto I = LocalAddrs.find(Arg);
537 if (I != LocalAddrs.end()) {
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000538 LValue LV = WrapperCGF.MakeAddrLValue(
539 I->second.second,
540 I->second.first ? I->second.first->getType() : Arg->getType(),
541 AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000542 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
543 } else {
544 auto EI = VLASizes.find(Arg);
545 if (EI != VLASizes.end())
546 CallArg = EI->second.second;
547 else {
548 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000549 Arg->getType(),
550 AlignmentSource::Decl);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000551 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
552 }
553 }
Alexey Bataev7ba57af2017-10-17 16:47:34 +0000554 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000555 }
Alexey Bataev3c595a62017-08-14 15:01:03 +0000556 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getLocStart(),
557 F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000558 WrapperCGF.FinishFunction();
559 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000560}
561
Alexey Bataev9959db52014-05-06 10:08:46 +0000562//===----------------------------------------------------------------------===//
563// OpenMP Directive Emission
564//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000565void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000566 Address DestAddr, Address SrcAddr, QualType OriginalType,
567 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000568 // Perform element-by-element initialization.
569 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000570
571 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000572 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000573 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
574 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
575
576 auto SrcBegin = SrcAddr.getPointer();
577 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000578 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000579 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
580 // The basic structure here is a while-do loop.
581 auto BodyBB = createBasicBlock("omp.arraycpy.body");
582 auto DoneBB = createBasicBlock("omp.arraycpy.done");
583 auto IsEmpty =
584 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
585 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000586
Alexey Bataev420d45b2015-04-14 05:11:24 +0000587 // Enter the loop body, making that address the current address.
588 auto EntryBB = Builder.GetInsertBlock();
589 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000590
591 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
592
593 llvm::PHINode *SrcElementPHI =
594 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
595 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
596 Address SrcElementCurrent =
597 Address(SrcElementPHI,
598 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
599
600 llvm::PHINode *DestElementPHI =
601 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
602 DestElementPHI->addIncoming(DestBegin, EntryBB);
603 Address DestElementCurrent =
604 Address(DestElementPHI,
605 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000606
Alexey Bataev420d45b2015-04-14 05:11:24 +0000607 // Emit copy.
608 CopyGen(DestElementCurrent, SrcElementCurrent);
609
610 // Shift the address forward by one element.
611 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000612 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000613 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000614 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000615 // Check whether we've reached the end.
616 auto Done =
617 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
618 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000619 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
620 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000621
622 // Done.
623 EmitBlock(DoneBB, /*IsFinished=*/true);
624}
625
John McCall7f416cc2015-09-08 08:05:57 +0000626void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
627 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000628 const VarDecl *SrcVD, const Expr *Copy) {
629 if (OriginalType->isArrayType()) {
630 auto *BO = dyn_cast<BinaryOperator>(Copy);
631 if (BO && BO->getOpcode() == BO_Assign) {
632 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000633 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000634 } else {
635 // For arrays with complex element types perform element by element
636 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000637 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000638 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000639 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000640 // Working with the single array element, so have to remap
641 // destination and source variables to corresponding array
642 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000643 CodeGenFunction::OMPPrivateScope Remap(*this);
644 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000645 return DestElement;
646 });
647 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000648 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000649 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000650 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000651 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000652 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000653 } else {
654 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000655 CodeGenFunction::OMPPrivateScope Remap(*this);
656 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
657 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000658 (void)Remap.Privatize();
659 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000660 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000661 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000662}
663
Alexey Bataev69c62a92015-04-15 04:52:20 +0000664bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
665 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000666 if (!HaveInsertPoint())
667 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000668 bool FirstprivateIsLastprivate = false;
669 llvm::DenseSet<const VarDecl *> Lastprivates;
670 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
671 for (const auto *D : C->varlists())
672 Lastprivates.insert(
673 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
674 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000675 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000676 CGCapturedStmtInfo CapturesInfo(cast<CapturedStmt>(*D.getAssociatedStmt()));
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000677 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000678 auto IRef = C->varlist_begin();
679 auto InitsRef = C->inits().begin();
680 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000681 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000682 bool ThisFirstprivateIsLastprivate =
683 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000684 auto *CapFD = CapturesInfo.lookup(OrigVD);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000685 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9afe5752016-05-24 07:40:12 +0000686 if (!ThisFirstprivateIsLastprivate && FD && (FD == CapFD) &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000687 !FD->getType()->isReferenceType()) {
688 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
689 ++IRef;
690 ++InitsRef;
691 continue;
692 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000693 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000694 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000695 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000696 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
697 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
698 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000699 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
700 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
701 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000702 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000703 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000704 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000705 // Emit VarDecl with copy init for arrays.
706 // Get the address of the original variable captured in current
707 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000708 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000709 auto Emission = EmitAutoVarAlloca(*VD);
710 auto *Init = VD->getInit();
711 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
712 // Perform simple memcpy.
713 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000714 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000715 } else {
716 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000717 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000718 [this, VDInit, Init](Address DestElement,
719 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000720 // Clean up any temporaries needed by the initialization.
721 RunCleanupsScope InitScope(*this);
722 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000723 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000724 EmitAnyExprToMem(Init, DestElement,
725 Init->getType().getQualifiers(),
726 /*IsInitializer*/ false);
727 LocalDeclMap.erase(VDInit);
728 });
729 }
730 EmitAutoVarCleanups(Emission);
731 return Emission.getAllocatedAddress();
732 });
733 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000734 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000735 // Emit private VarDecl with copy init.
736 // Remap temp VDInit variable to the address of the original
737 // variable
738 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000739 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000740 EmitDecl(*VD);
741 LocalDeclMap.erase(VDInit);
742 return GetAddrOfLocalVar(VD);
743 });
744 }
745 assert(IsRegistered &&
746 "firstprivate var already registered as private");
747 // Silence the warning about unused variable.
748 (void)IsRegistered;
749 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000750 ++IRef;
751 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000752 }
753 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000754 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000755}
756
Alexey Bataev03b340a2014-10-21 03:16:40 +0000757void CodeGenFunction::EmitOMPPrivateClause(
758 const OMPExecutableDirective &D,
759 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000760 if (!HaveInsertPoint())
761 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000762 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000763 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000764 auto IRef = C->varlist_begin();
765 for (auto IInit : C->private_copies()) {
766 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000767 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
768 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
769 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000770 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000771 // Emit private VarDecl with copy init.
772 EmitDecl(*VD);
773 return GetAddrOfLocalVar(VD);
774 });
775 assert(IsRegistered && "private var already registered as private");
776 // Silence the warning about unused variable.
777 (void)IsRegistered;
778 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000779 ++IRef;
780 }
781 }
782}
783
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000784bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000785 if (!HaveInsertPoint())
786 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000787 // threadprivate_var1 = master_threadprivate_var1;
788 // operator=(threadprivate_var2, master_threadprivate_var2);
789 // ...
790 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000791 llvm::DenseSet<const VarDecl *> CopiedVars;
792 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000793 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000794 auto IRef = C->varlist_begin();
795 auto ISrcRef = C->source_exprs().begin();
796 auto IDestRef = C->destination_exprs().begin();
797 for (auto *AssignOp : C->assignment_ops()) {
798 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000799 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000800 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000801 // Get the address of the master variable. If we are emitting code with
802 // TLS support, the address is passed from the master as field in the
803 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000804 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000805 if (getLangOpts().OpenMPUseTLS &&
806 getContext().getTargetInfo().isTLSSupported()) {
807 assert(CapturedStmtInfo->lookup(VD) &&
808 "Copyin threadprivates should have been captured!");
809 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
810 VK_LValue, (*IRef)->getExprLoc());
811 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000812 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000813 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000814 MasterAddr =
815 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
816 : CGM.GetAddrOfGlobal(VD),
817 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000818 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000819 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000820 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000821 if (CopiedVars.size() == 1) {
822 // At first check if current thread is a master thread. If it is, no
823 // need to copy data.
824 CopyBegin = createBasicBlock("copyin.not.master");
825 CopyEnd = createBasicBlock("copyin.not.master.end");
826 Builder.CreateCondBr(
827 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000828 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
829 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000830 CopyBegin, CopyEnd);
831 EmitBlock(CopyBegin);
832 }
833 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
834 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000835 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000836 }
837 ++IRef;
838 ++ISrcRef;
839 ++IDestRef;
840 }
841 }
842 if (CopyEnd) {
843 // Exit out of copying procedure for non-master thread.
844 EmitBlock(CopyEnd, /*IsFinished=*/true);
845 return true;
846 }
847 return false;
848}
849
Alexey Bataev38e89532015-04-16 04:54:05 +0000850bool CodeGenFunction::EmitOMPLastprivateClauseInit(
851 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000852 if (!HaveInsertPoint())
853 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000854 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000855 llvm::DenseSet<const VarDecl *> SIMDLCVs;
856 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
857 auto *LoopDirective = cast<OMPLoopDirective>(&D);
858 for (auto *C : LoopDirective->counters()) {
859 SIMDLCVs.insert(
860 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
861 }
862 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000863 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000864 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000865 HasAtLeastOneLastprivate = true;
Alexey Bataevf93095a2016-05-05 08:46:22 +0000866 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()))
867 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000868 auto IRef = C->varlist_begin();
869 auto IDestRef = C->destination_exprs().begin();
870 for (auto *IInit : C->private_copies()) {
871 // Keep the address of the original variable for future update at the end
872 // of the loop.
873 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000874 // Taskloops do not require additional initialization, it is done in
875 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000876 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
877 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000878 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000879 DeclRefExpr DRE(
880 const_cast<VarDecl *>(OrigVD),
881 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
882 OrigVD) != nullptr,
883 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
884 return EmitLValue(&DRE).getAddress();
885 });
886 // Check if the variable is also a firstprivate: in this case IInit is
887 // not generated. Initialization of this variable will happen in codegen
888 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000889 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000890 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000891 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
892 // Emit private VarDecl with copy init.
893 EmitDecl(*VD);
894 return GetAddrOfLocalVar(VD);
895 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000896 assert(IsRegistered &&
897 "lastprivate var already registered as private");
898 (void)IsRegistered;
899 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000900 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000901 ++IRef;
902 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000903 }
904 }
905 return HasAtLeastOneLastprivate;
906}
907
908void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000909 const OMPExecutableDirective &D, bool NoFinals,
910 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000911 if (!HaveInsertPoint())
912 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000913 // Emit following code:
914 // if (<IsLastIterCond>) {
915 // orig_var1 = private_orig_var1;
916 // ...
917 // orig_varn = private_orig_varn;
918 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000919 llvm::BasicBlock *ThenBB = nullptr;
920 llvm::BasicBlock *DoneBB = nullptr;
921 if (IsLastIterCond) {
922 ThenBB = createBasicBlock(".omp.lastprivate.then");
923 DoneBB = createBasicBlock(".omp.lastprivate.done");
924 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
925 EmitBlock(ThenBB);
926 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000927 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
928 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000929 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000930 auto IC = LoopDirective->counters().begin();
931 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000932 auto *D =
933 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
934 if (NoFinals)
935 AlreadyEmittedVars.insert(D);
936 else
937 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000938 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000939 }
940 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000941 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
942 auto IRef = C->varlist_begin();
943 auto ISrcRef = C->source_exprs().begin();
944 auto IDestRef = C->destination_exprs().begin();
945 for (auto *AssignOp : C->assignment_ops()) {
946 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
947 QualType Type = PrivateVD->getType();
948 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
949 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
950 // If lastprivate variable is a loop control variable for loop-based
951 // directive, update its value before copyin back to original
952 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000953 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
954 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000955 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
956 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
957 // Get the address of the original variable.
958 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
959 // Get the address of the private variable.
960 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
961 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
962 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000963 Address(Builder.CreateLoad(PrivateAddr),
964 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000965 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000966 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000967 ++IRef;
968 ++ISrcRef;
969 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000970 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000971 if (auto *PostUpdate = C->getPostUpdateExpr())
972 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000973 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000974 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000975 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000976}
977
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000978void CodeGenFunction::EmitOMPReductionClauseInit(
979 const OMPExecutableDirective &D,
980 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000981 if (!HaveInsertPoint())
982 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000983 SmallVector<const Expr *, 4> Shareds;
984 SmallVector<const Expr *, 4> Privates;
985 SmallVector<const Expr *, 4> ReductionOps;
986 SmallVector<const Expr *, 4> LHSs;
987 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000988 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000989 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000990 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000991 auto ILHS = C->lhs_exprs().begin();
992 auto IRHS = C->rhs_exprs().begin();
993 for (const auto *Ref : C->varlists()) {
994 Shareds.emplace_back(Ref);
995 Privates.emplace_back(*IPriv);
996 ReductionOps.emplace_back(*IRed);
997 LHSs.emplace_back(*ILHS);
998 RHSs.emplace_back(*IRHS);
999 std::advance(IPriv, 1);
1000 std::advance(IRed, 1);
1001 std::advance(ILHS, 1);
1002 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001003 }
1004 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001005 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1006 unsigned Count = 0;
1007 auto ILHS = LHSs.begin();
1008 auto IRHS = RHSs.begin();
1009 auto IPriv = Privates.begin();
1010 for (const auto *IRef : Shareds) {
1011 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
1012 // Emit private VarDecl with reduction init.
1013 RedCG.emitSharedLValue(*this, Count);
1014 RedCG.emitAggregateType(*this, Count);
1015 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1016 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1017 RedCG.getSharedLValue(Count),
1018 [&Emission](CodeGenFunction &CGF) {
1019 CGF.EmitAutoVarInit(Emission);
1020 return true;
1021 });
1022 EmitAutoVarCleanups(Emission);
1023 Address BaseAddr = RedCG.adjustPrivateAddress(
1024 *this, Count, Emission.getAllocatedAddress());
1025 bool IsRegistered = PrivateScope.addPrivate(
1026 RedCG.getBaseDecl(Count), [BaseAddr]() -> Address { return BaseAddr; });
1027 assert(IsRegistered && "private var already registered as private");
1028 // Silence the warning about unused variable.
1029 (void)IsRegistered;
1030
1031 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1032 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001033 QualType Type = PrivateVD->getType();
1034 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1035 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001036 // Store the address of the original variable associated with the LHS
1037 // implicit variable.
1038 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1039 return RedCG.getSharedLValue(Count).getAddress();
1040 });
1041 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1042 return GetAddrOfLocalVar(PrivateVD);
1043 });
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001044 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1045 isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001046 // Store the address of the original variable associated with the LHS
1047 // implicit variable.
1048 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1049 return RedCG.getSharedLValue(Count).getAddress();
1050 });
1051 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1052 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1053 ConvertTypeForMem(RHSVD->getType()),
1054 "rhs.begin");
1055 });
1056 } else {
1057 QualType Type = PrivateVD->getType();
1058 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1059 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1060 // Store the address of the original variable associated with the LHS
1061 // implicit variable.
1062 if (IsArray) {
1063 OriginalAddr = Builder.CreateElementBitCast(
1064 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1065 }
1066 PrivateScope.addPrivate(
1067 LHSVD, [OriginalAddr]() -> Address { return OriginalAddr; });
1068 PrivateScope.addPrivate(
1069 RHSVD, [this, PrivateVD, RHSVD, IsArray]() -> Address {
1070 return IsArray
1071 ? Builder.CreateElementBitCast(
1072 GetAddrOfLocalVar(PrivateVD),
1073 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1074 : GetAddrOfLocalVar(PrivateVD);
1075 });
1076 }
1077 ++ILHS;
1078 ++IRHS;
1079 ++IPriv;
1080 ++Count;
1081 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001082}
1083
1084void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001085 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001086 if (!HaveInsertPoint())
1087 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001088 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001089 llvm::SmallVector<const Expr *, 8> LHSExprs;
1090 llvm::SmallVector<const Expr *, 8> RHSExprs;
1091 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001092 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001093 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001094 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001095 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001096 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1097 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1098 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1099 }
1100 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001101 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1102 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1103 D.getDirectiveKind() == OMPD_simd;
Alexey Bataev617db5f2017-12-04 15:38:33 +00001104 bool SimpleReduction = D.getDirectiveKind() == OMPD_simd ||
1105 D.getDirectiveKind() == OMPD_distribute_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001106 // Emit nowait reduction if nowait clause is present or directive is a
1107 // parallel directive (it always has implicit barrier).
1108 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001109 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001110 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001111 }
1112}
1113
Alexey Bataev61205072016-03-02 04:57:40 +00001114static void emitPostUpdateForReductionClause(
1115 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1116 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1117 if (!CGF.HaveInsertPoint())
1118 return;
1119 llvm::BasicBlock *DoneBB = nullptr;
1120 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1121 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1122 if (!DoneBB) {
1123 if (auto *Cond = CondGen(CGF)) {
1124 // If the first post-update expression is found, emit conditional
1125 // block if it was requested.
1126 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1127 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1128 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1129 CGF.EmitBlock(ThenBB);
1130 }
1131 }
1132 CGF.EmitIgnoredExpr(PostUpdate);
1133 }
1134 }
1135 if (DoneBB)
1136 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1137}
1138
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001139namespace {
1140/// Codegen lambda for appending distribute lower and upper bounds to outlined
1141/// parallel function. This is necessary for combined constructs such as
1142/// 'distribute parallel for'
1143typedef llvm::function_ref<void(CodeGenFunction &,
1144 const OMPExecutableDirective &,
1145 llvm::SmallVectorImpl<llvm::Value *> &)>
1146 CodeGenBoundParametersTy;
1147} // anonymous namespace
1148
1149static void emitCommonOMPParallelDirective(
1150 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1151 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1152 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001153 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1154 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1155 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001156 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001157 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001158 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1159 /*IgnoreResultAssign*/ true);
1160 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1161 CGF, NumThreads, NumThreadsClause->getLocStart());
1162 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001163 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001164 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001165 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1166 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1167 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001168 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001169 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1170 if (C->getNameModifier() == OMPD_unknown ||
1171 C->getNameModifier() == OMPD_parallel) {
1172 IfCond = C->getCondition();
1173 break;
1174 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001175 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001176
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001177 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001178 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001179 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1180 // lower and upper bounds with the pragma 'for' chunking mechanism.
1181 // The following lambda takes care of appending the lower and upper bound
1182 // parameters when necessary
1183 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001184 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001185 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001186 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001187}
1188
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001189static void emitEmptyBoundParameters(CodeGenFunction &,
1190 const OMPExecutableDirective &,
1191 llvm::SmallVectorImpl<llvm::Value *> &) {}
1192
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001193void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001194 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001195 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001196 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001197 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001198 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1199 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001200 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001201 // propagation master's thread values of threadprivate variables to local
1202 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001203 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1204 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1205 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001206 }
1207 CGF.EmitOMPPrivateClause(S, PrivateScope);
1208 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1209 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001210 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001211 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001212 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001213 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1214 emitEmptyBoundParameters);
Alexey Bataev61205072016-03-02 04:57:40 +00001215 emitPostUpdateForReductionClause(
1216 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001217}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001218
Alexey Bataev0f34da12015-07-02 04:17:07 +00001219void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1220 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001221 RunCleanupsScope BodyScope(*this);
1222 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001223 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001224 EmitIgnoredExpr(I);
1225 }
Alexander Musman3276a272015-03-21 10:12:56 +00001226 // Update the linear variables.
Alexey Bataev617db5f2017-12-04 15:38:33 +00001227 // In distribute directives only loop counters may be marked as linear, no
1228 // need to generate the code for them.
1229 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1230 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1231 for (auto *U : C->updates())
1232 EmitIgnoredExpr(U);
1233 }
Alexander Musman3276a272015-03-21 10:12:56 +00001234 }
1235
Alexander Musmana5f070a2014-10-01 06:03:56 +00001236 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001237 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001238 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001239 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001240 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001241 // The end (updates/cleanups).
1242 EmitBlock(Continue.getBlock());
1243 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001244}
1245
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001246void CodeGenFunction::EmitOMPInnerLoop(
1247 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1248 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001249 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1250 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001251 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001252
1253 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001254 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001255 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001256 const SourceRange &R = S.getSourceRange();
1257 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1258 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001259
1260 // If there are any cleanups between here and the loop-exit scope,
1261 // create a block to stage a loop exit along.
1262 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001263 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001264 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001265
Alexander Musmand196ef22014-10-07 08:57:09 +00001266 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001267
Alexey Bataev2df54a02015-03-12 08:53:29 +00001268 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001269 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001270 if (ExitBlock != LoopExit.getBlock()) {
1271 EmitBlock(ExitBlock);
1272 EmitBranchThroughCleanup(LoopExit);
1273 }
1274
1275 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001276 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001277
1278 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001279 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001280 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1281
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001282 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001283
1284 // Emit "IV = IV + 1" and a back-edge to the condition block.
1285 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001286 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001287 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001288 BreakContinueStack.pop_back();
1289 EmitBranch(CondBlock);
1290 LoopStack.pop();
1291 // Emit the fall-through block.
1292 EmitBlock(LoopExit.getBlock());
1293}
1294
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001295bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001296 if (!HaveInsertPoint())
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001297 return false;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001298 // Emit inits for the linear variables.
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001299 bool HasLinears = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001300 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001301 for (auto *Init : C->inits()) {
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001302 HasLinears = true;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001303 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001304 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1305 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1306 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1307 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1308 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1309 VD->getInit()->getType(), VK_LValue,
1310 VD->getInit()->getExprLoc());
1311 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1312 VD->getType()),
1313 /*capturedByInit=*/false);
1314 EmitAutoVarCleanups(Emission);
1315 } else
1316 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001317 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001318 // Emit the linear steps for the linear clauses.
1319 // If a step is not constant, it is pre-calculated before the loop.
1320 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1321 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001322 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001323 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001324 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001325 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001326 }
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00001327 return HasLinears;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001328}
1329
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001330void CodeGenFunction::EmitOMPLinearClauseFinal(
1331 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001332 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001333 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001334 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001335 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001336 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001337 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001338 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001339 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001340 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001341 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001342 // If the first post-update expression is found, emit conditional
1343 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001344 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1345 DoneBB = createBasicBlock(".omp.linear.pu.done");
1346 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1347 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001348 }
1349 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001350 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1351 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001352 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001353 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001354 Address OrigAddr = EmitLValue(&DRE).getAddress();
1355 CodeGenFunction::OMPPrivateScope VarScope(*this);
1356 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001357 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001358 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001359 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001360 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001361 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001362 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001363 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001364 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001365 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001366}
1367
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001368static void emitAlignedClause(CodeGenFunction &CGF,
1369 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001370 if (!CGF.HaveInsertPoint())
1371 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001372 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001373 unsigned ClauseAlignment = 0;
1374 if (auto AlignmentExpr = Clause->getAlignment()) {
1375 auto AlignmentCI =
1376 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1377 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001378 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001379 for (auto E : Clause->varlists()) {
1380 unsigned Alignment = ClauseAlignment;
1381 if (Alignment == 0) {
1382 // OpenMP [2.8.1, Description]
1383 // If no optional parameter is specified, implementation-defined default
1384 // alignments for SIMD instructions on the target platforms are assumed.
1385 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001386 CGF.getContext()
1387 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1388 E->getType()->getPointeeType()))
1389 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001390 }
1391 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1392 "alignment is not power of 2");
1393 if (Alignment != 0) {
1394 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1395 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1396 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001397 }
1398 }
1399}
1400
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001401void CodeGenFunction::EmitOMPPrivateLoopCounters(
1402 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1403 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001404 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001405 auto I = S.private_counters().begin();
1406 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001407 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1408 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001409 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001410 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001411 if (!LocalDeclMap.count(PrivateVD)) {
1412 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1413 EmitAutoVarCleanups(VarEmission);
1414 }
1415 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1416 /*RefersToEnclosingVariableOrCapture=*/false,
1417 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1418 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001419 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001420 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1421 VD->hasGlobalStorage()) {
1422 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1423 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1424 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1425 E->getType(), VK_LValue, E->getExprLoc());
1426 return EmitLValue(&DRE).getAddress();
1427 });
1428 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001429 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001430 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001431}
1432
Alexey Bataev62dbb972015-04-22 11:59:37 +00001433static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1434 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1435 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001436 if (!CGF.HaveInsertPoint())
1437 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001438 {
1439 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001440 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001441 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001442 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001443 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001444 CGF.EmitIgnoredExpr(I);
1445 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001446 }
1447 // Check that loop is executed at least one time.
1448 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1449}
1450
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001451void CodeGenFunction::EmitOMPLinearClause(
1452 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1453 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001454 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001455 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1456 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1457 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1458 for (auto *C : LoopDirective->counters()) {
1459 SIMDLCVs.insert(
1460 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1461 }
1462 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001463 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001464 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001465 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001466 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1467 auto *PrivateVD =
1468 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001469 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1470 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1471 // Emit private VarDecl with copy init.
1472 EmitVarDecl(*PrivateVD);
1473 return GetAddrOfLocalVar(PrivateVD);
1474 });
1475 assert(IsRegistered && "linear var already registered as private");
1476 // Silence the warning about unused variable.
1477 (void)IsRegistered;
1478 } else
1479 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001480 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001481 }
1482 }
1483}
1484
Alexey Bataev45bfad52015-08-21 12:19:04 +00001485static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001486 const OMPExecutableDirective &D,
1487 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001488 if (!CGF.HaveInsertPoint())
1489 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001490 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001491 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1492 /*ignoreResult=*/true);
1493 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1494 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1495 // In presence of finite 'safelen', it may be unsafe to mark all
1496 // the memory instructions parallel, because loop-carried
1497 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001498 if (!IsMonotonic)
1499 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001500 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001501 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1502 /*ignoreResult=*/true);
1503 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001504 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001505 // In presence of finite 'safelen', it may be unsafe to mark all
1506 // the memory instructions parallel, because loop-carried
1507 // dependences of 'safelen' iterations are possible.
1508 CGF.LoopStack.setParallel(false);
1509 }
1510}
1511
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001512void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1513 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001514 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001515 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001516 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001517 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001518}
1519
Alexey Bataevef549a82016-03-09 09:49:09 +00001520void CodeGenFunction::EmitOMPSimdFinal(
1521 const OMPLoopDirective &D,
1522 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001523 if (!HaveInsertPoint())
1524 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001525 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001526 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001527 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001528 for (auto F : D.finals()) {
1529 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001530 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1531 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1532 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1533 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001534 if (!DoneBB) {
1535 if (auto *Cond = CondGen(*this)) {
1536 // If the first post-update expression is found, emit conditional
1537 // block if it was requested.
1538 auto *ThenBB = createBasicBlock(".omp.final.then");
1539 DoneBB = createBasicBlock(".omp.final.done");
1540 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1541 EmitBlock(ThenBB);
1542 }
1543 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001544 Address OrigAddr = Address::invalid();
1545 if (CED)
1546 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1547 else {
1548 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1549 /*RefersToEnclosingVariableOrCapture=*/false,
1550 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1551 OrigAddr = EmitLValue(&DRE).getAddress();
1552 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001553 OMPPrivateScope VarScope(*this);
1554 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001555 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001556 (void)VarScope.Privatize();
1557 EmitIgnoredExpr(F);
1558 }
1559 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001560 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001561 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001562 if (DoneBB)
1563 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001564}
1565
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001566static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1567 const OMPLoopDirective &S,
1568 CodeGenFunction::JumpDest LoopExit) {
1569 CGF.EmitOMPLoopBody(S, LoopExit);
1570 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001571}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001572
Alexey Bataevf8365372017-11-17 17:57:25 +00001573static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1574 PrePostActionTy &Action) {
1575 Action.Enter(CGF);
1576 assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1577 "Expected simd directive");
1578 OMPLoopScope PreInitScope(CGF, S);
1579 // if (PreCond) {
1580 // for (IV in 0..LastIteration) BODY;
1581 // <Final counter/linear vars updates>;
1582 // }
1583 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001584
Alexey Bataevf8365372017-11-17 17:57:25 +00001585 // Emit: if (PreCond) - begin.
1586 // If the condition constant folds and can be elided, avoid emitting the
1587 // whole loop.
1588 bool CondConstant;
1589 llvm::BasicBlock *ContBlock = nullptr;
1590 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1591 if (!CondConstant)
1592 return;
1593 } else {
1594 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1595 ContBlock = CGF.createBasicBlock("simd.if.end");
1596 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1597 CGF.getProfileCount(&S));
1598 CGF.EmitBlock(ThenBlock);
1599 CGF.incrementProfileCounter(&S);
1600 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001601
Alexey Bataevf8365372017-11-17 17:57:25 +00001602 // Emit the loop iteration variable.
1603 const Expr *IVExpr = S.getIterationVariable();
1604 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1605 CGF.EmitVarDecl(*IVDecl);
1606 CGF.EmitIgnoredExpr(S.getInit());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001607
Alexey Bataevf8365372017-11-17 17:57:25 +00001608 // Emit the iterations count variable.
1609 // If it is not a variable, Sema decided to calculate iterations count on
1610 // each iteration (e.g., it is foldable into a constant).
1611 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1612 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1613 // Emit calculation of the iterations count.
1614 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1615 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001616
Alexey Bataevf8365372017-11-17 17:57:25 +00001617 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001618
Alexey Bataevf8365372017-11-17 17:57:25 +00001619 emitAlignedClause(CGF, S);
1620 (void)CGF.EmitOMPLinearClauseInit(S);
1621 {
1622 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1623 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1624 CGF.EmitOMPLinearClause(S, LoopScope);
1625 CGF.EmitOMPPrivateClause(S, LoopScope);
1626 CGF.EmitOMPReductionClauseInit(S, LoopScope);
1627 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1628 (void)LoopScope.Privatize();
1629 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1630 S.getInc(),
1631 [&S](CodeGenFunction &CGF) {
1632 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1633 CGF.EmitStopPoint(&S);
1634 },
1635 [](CodeGenFunction &) {});
1636 CGF.EmitOMPSimdFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001637 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevf8365372017-11-17 17:57:25 +00001638 // Emit final copy of the lastprivate variables at the end of loops.
1639 if (HasLastprivateClause)
1640 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1641 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
1642 emitPostUpdateForReductionClause(
1643 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1644 }
1645 CGF.EmitOMPLinearClauseFinal(
1646 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1647 // Emit: if (PreCond) - end.
1648 if (ContBlock) {
1649 CGF.EmitBranch(ContBlock);
1650 CGF.EmitBlock(ContBlock, true);
1651 }
1652}
1653
1654void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1655 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1656 emitOMPSimdRegion(CGF, S, Action);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001657 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00001658 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001659 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001660}
1661
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001662void CodeGenFunction::EmitOMPOuterLoop(
1663 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1664 CodeGenFunction::OMPPrivateScope &LoopScope,
1665 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1666 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1667 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001668 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001669
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001670 const Expr *IVExpr = S.getIterationVariable();
1671 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1672 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1673
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001674 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1675
1676 // Start the loop with a block that tests the condition.
1677 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1678 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001679 const SourceRange &R = S.getSourceRange();
1680 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1681 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001682
1683 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001684 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001685 // UB = min(UB, GlobalUB) or
1686 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1687 // 'distribute parallel for')
1688 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001689 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001690 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001691 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001692 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001693 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001694 BoolCondVal =
1695 RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1696 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001697 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001698
1699 // If there are any cleanups between here and the loop-exit scope,
1700 // create a block to stage a loop exit along.
1701 auto ExitBlock = LoopExit.getBlock();
1702 if (LoopScope.requiresCleanups())
1703 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1704
1705 auto LoopBody = createBasicBlock("omp.dispatch.body");
1706 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1707 if (ExitBlock != LoopExit.getBlock()) {
1708 EmitBlock(ExitBlock);
1709 EmitBranchThroughCleanup(LoopExit);
1710 }
1711 EmitBlock(LoopBody);
1712
Alexander Musman92bdaab2015-03-12 13:37:50 +00001713 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1714 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001715 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001716 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001717
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001718 // Create a block for the increment.
1719 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1720 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1721
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001722 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1723 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001724 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1725 LoopStack.setParallel(!IsMonotonic);
1726 else
1727 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001728
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001729 SourceLocation Loc = S.getLocStart();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001730
1731 // when 'distribute' is not combined with a 'for':
1732 // while (idx <= UB) { BODY; ++idx; }
1733 // when 'distribute' is combined with a 'for'
1734 // (e.g. 'distribute parallel for')
1735 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1736 EmitOMPInnerLoop(
1737 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1738 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1739 CodeGenLoop(CGF, S, LoopExit);
1740 },
1741 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1742 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1743 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001744
1745 EmitBlock(Continue.getBlock());
1746 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001747 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001748 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001749 EmitIgnoredExpr(LoopArgs.NextLB);
1750 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001751 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001752
1753 EmitBranch(CondBlock);
1754 LoopStack.pop();
1755 // Emit the fall-through block.
1756 EmitBlock(LoopExit.getBlock());
1757
1758 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001759 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1760 if (!DynamicOrOrdered)
Alexey Bataevf43f7142017-09-06 16:17:35 +00001761 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
1762 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00001763 };
1764 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001765}
1766
1767void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001768 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001769 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001770 const OMPLoopArguments &LoopArgs,
1771 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001772 auto &RT = CGM.getOpenMPRuntime();
1773
1774 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001775 const bool DynamicOrOrdered =
1776 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001777
1778 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001779 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001780 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001781 "static non-chunked schedule does not need outer loop");
1782
1783 // Emit outer loop.
1784 //
1785 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1786 // When schedule(dynamic,chunk_size) is specified, the iterations are
1787 // distributed to threads in the team in chunks as the threads request them.
1788 // Each thread executes a chunk of iterations, then requests another chunk,
1789 // until no chunks remain to be distributed. Each chunk contains chunk_size
1790 // iterations, except for the last chunk to be distributed, which may have
1791 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1792 //
1793 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1794 // to threads in the team in chunks as the executing threads request them.
1795 // Each thread executes a chunk of iterations, then requests another chunk,
1796 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1797 // each chunk is proportional to the number of unassigned iterations divided
1798 // by the number of threads in the team, decreasing to 1. For a chunk_size
1799 // with value k (greater than 1), the size of each chunk is determined in the
1800 // same way, with the restriction that the chunks do not contain fewer than k
1801 // iterations (except for the last chunk to be assigned, which may have fewer
1802 // than k iterations).
1803 //
1804 // When schedule(auto) is specified, the decision regarding scheduling is
1805 // delegated to the compiler and/or runtime system. The programmer gives the
1806 // implementation the freedom to choose any possible mapping of iterations to
1807 // threads in the team.
1808 //
1809 // When schedule(runtime) is specified, the decision regarding scheduling is
1810 // deferred until run time, and the schedule and chunk size are taken from the
1811 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1812 // implementation defined
1813 //
1814 // while(__kmpc_dispatch_next(&LB, &UB)) {
1815 // idx = LB;
1816 // while (idx <= UB) { BODY; ++idx;
1817 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1818 // } // inner loop
1819 // }
1820 //
1821 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1822 // When schedule(static, chunk_size) is specified, iterations are divided into
1823 // chunks of size chunk_size, and the chunks are assigned to the threads in
1824 // the team in a round-robin fashion in the order of the thread number.
1825 //
1826 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1827 // while (idx <= UB) { BODY; ++idx; } // inner loop
1828 // LB = LB + ST;
1829 // UB = UB + ST;
1830 // }
1831 //
1832
1833 const Expr *IVExpr = S.getIterationVariable();
1834 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1835 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1836
1837 if (DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001838 auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1839 llvm::Value *LBVal = DispatchBounds.first;
1840 llvm::Value *UBVal = DispatchBounds.second;
1841 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1842 LoopArgs.Chunk};
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001843 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001844 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001845 } else {
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001846 CGOpenMPRuntime::StaticRTInput StaticInit(
1847 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1848 LoopArgs.ST, LoopArgs.Chunk);
1849 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
1850 ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001851 }
1852
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001853 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1854 const unsigned IVSize,
1855 const bool IVSigned) {
1856 if (Ordered) {
1857 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1858 IVSigned);
1859 }
1860 };
1861
1862 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1863 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1864 OuterLoopArgs.IncExpr = S.getInc();
1865 OuterLoopArgs.Init = S.getInit();
1866 OuterLoopArgs.Cond = S.getCond();
1867 OuterLoopArgs.NextLB = S.getNextLowerBound();
1868 OuterLoopArgs.NextUB = S.getNextUpperBound();
1869 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1870 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001871}
1872
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001873static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1874 const unsigned IVSize, const bool IVSigned) {}
1875
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001876void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001877 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1878 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1879 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001880
1881 auto &RT = CGM.getOpenMPRuntime();
1882
1883 // Emit outer loop.
1884 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1885 // dynamic
1886 //
1887
1888 const Expr *IVExpr = S.getIterationVariable();
1889 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1890 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1891
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00001892 CGOpenMPRuntime::StaticRTInput StaticInit(
1893 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
1894 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
1895 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001896
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001897 // for combined 'distribute' and 'for' the increment expression of distribute
1898 // is store in DistInc. For 'distribute' alone, it is in Inc.
1899 Expr *IncExpr;
1900 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1901 IncExpr = S.getDistInc();
1902 else
1903 IncExpr = S.getInc();
1904
1905 // this routine is shared by 'omp distribute parallel for' and
1906 // 'omp distribute': select the right EUB expression depending on the
1907 // directive
1908 OMPLoopArguments OuterLoopArgs;
1909 OuterLoopArgs.LB = LoopArgs.LB;
1910 OuterLoopArgs.UB = LoopArgs.UB;
1911 OuterLoopArgs.ST = LoopArgs.ST;
1912 OuterLoopArgs.IL = LoopArgs.IL;
1913 OuterLoopArgs.Chunk = LoopArgs.Chunk;
1914 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1915 ? S.getCombinedEnsureUpperBound()
1916 : S.getEnsureUpperBound();
1917 OuterLoopArgs.IncExpr = IncExpr;
1918 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1919 ? S.getCombinedInit()
1920 : S.getInit();
1921 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1922 ? S.getCombinedCond()
1923 : S.getCond();
1924 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1925 ? S.getCombinedNextLowerBound()
1926 : S.getNextLowerBound();
1927 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1928 ? S.getCombinedNextUpperBound()
1929 : S.getNextUpperBound();
1930
1931 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
1932 LoopScope, OuterLoopArgs, CodeGenLoopContent,
1933 emitEmptyOrdered);
1934}
1935
1936/// Emit a helper variable and return corresponding lvalue.
1937static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1938 const DeclRefExpr *Helper) {
1939 auto VDecl = cast<VarDecl>(Helper->getDecl());
1940 CGF.EmitVarDecl(*VDecl);
1941 return CGF.EmitLValue(Helper);
1942}
1943
1944static std::pair<LValue, LValue>
1945emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
1946 const OMPExecutableDirective &S) {
1947 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1948 LValue LB =
1949 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
1950 LValue UB =
1951 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
1952
1953 // When composing 'distribute' with 'for' (e.g. as in 'distribute
1954 // parallel for') we need to use the 'distribute'
1955 // chunk lower and upper bounds rather than the whole loop iteration
1956 // space. These are parameters to the outlined function for 'parallel'
1957 // and we copy the bounds of the previous schedule into the
1958 // the current ones.
1959 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
1960 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
1961 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(PrevLB, SourceLocation());
1962 PrevLBVal = CGF.EmitScalarConversion(
1963 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
1964 LS.getIterationVariable()->getType(), SourceLocation());
1965 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(PrevUB, SourceLocation());
1966 PrevUBVal = CGF.EmitScalarConversion(
1967 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
1968 LS.getIterationVariable()->getType(), SourceLocation());
1969
1970 CGF.EmitStoreOfScalar(PrevLBVal, LB);
1971 CGF.EmitStoreOfScalar(PrevUBVal, UB);
1972
1973 return {LB, UB};
1974}
1975
1976/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
1977/// we need to use the LB and UB expressions generated by the worksharing
1978/// code generation support, whereas in non combined situations we would
1979/// just emit 0 and the LastIteration expression
1980/// This function is necessary due to the difference of the LB and UB
1981/// types for the RT emission routines for 'for_static_init' and
1982/// 'for_dispatch_init'
1983static std::pair<llvm::Value *, llvm::Value *>
1984emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
1985 const OMPExecutableDirective &S,
1986 Address LB, Address UB) {
1987 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1988 const Expr *IVExpr = LS.getIterationVariable();
1989 // when implementing a dynamic schedule for a 'for' combined with a
1990 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
1991 // is not normalized as each team only executes its own assigned
1992 // distribute chunk
1993 QualType IteratorTy = IVExpr->getType();
1994 llvm::Value *LBVal = CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy,
1995 SourceLocation());
1996 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy,
1997 SourceLocation());
1998 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00001999}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002000
2001static void emitDistributeParallelForDistributeInnerBoundParams(
2002 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2003 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2004 const auto &Dir = cast<OMPLoopDirective>(S);
2005 LValue LB =
2006 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
2007 auto LBCast = CGF.Builder.CreateIntCast(
2008 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2009 CapturedVars.push_back(LBCast);
2010 LValue UB =
2011 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2012
2013 auto UBCast = CGF.Builder.CreateIntCast(
2014 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2015 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00002016}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002017
2018static void
2019emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2020 const OMPLoopDirective &S,
2021 CodeGenFunction::JumpDest LoopExit) {
2022 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
2023 PrePostActionTy &) {
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002024 bool HasCancel = false;
2025 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2026 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2027 HasCancel = D->hasCancel();
2028 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2029 HasCancel = D->hasCancel();
Alexey Bataev16e79882017-11-22 21:12:03 +00002030 else if (const auto *D =
2031 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2032 HasCancel = D->hasCancel();
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002033 }
2034 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2035 HasCancel);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002036 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2037 emitDistributeParallelForInnerBounds,
2038 emitDistributeParallelForDispatchBounds);
2039 };
2040
2041 emitCommonOMPParallelDirective(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002042 CGF, S,
2043 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2044 CGInlinedWorksharingLoop,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002045 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002046}
2047
Carlo Bertolli9925f152016-06-27 14:55:37 +00002048void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2049 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002050 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2051 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2052 S.getDistInc());
2053 };
Carlo Bertolli9925f152016-06-27 14:55:37 +00002054 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev10a54312017-11-27 16:54:08 +00002055 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002056}
2057
Kelvin Li4a39add2016-07-05 05:00:15 +00002058void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2059 const OMPDistributeParallelForSimdDirective &S) {
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002060 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2061 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2062 S.getDistInc());
2063 };
Kelvin Li4a39add2016-07-05 05:00:15 +00002064 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev0b49f9e2017-11-27 19:38:58 +00002065 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Kelvin Li4a39add2016-07-05 05:00:15 +00002066}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002067
2068void CodeGenFunction::EmitOMPDistributeSimdDirective(
2069 const OMPDistributeSimdDirective &S) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00002070 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2071 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2072 };
Kelvin Li787f3fc2016-07-06 04:45:38 +00002073 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev617db5f2017-12-04 15:38:33 +00002074 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002075}
2076
Alexey Bataevf8365372017-11-17 17:57:25 +00002077void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2078 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2079 // Emit SPMD target parallel for region as a standalone region.
2080 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2081 emitOMPSimdRegion(CGF, S, Action);
2082 };
2083 llvm::Function *Fn;
2084 llvm::Constant *Addr;
2085 // Emit target region as a standalone region.
2086 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2087 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2088 assert(Fn && Addr && "Target device function emission failed.");
2089}
2090
Kelvin Li986330c2016-07-20 22:57:10 +00002091void CodeGenFunction::EmitOMPTargetSimdDirective(
2092 const OMPTargetSimdDirective &S) {
Alexey Bataevf8365372017-11-17 17:57:25 +00002093 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2094 emitOMPSimdRegion(CGF, S, Action);
2095 };
2096 emitCommonOMPTargetDirective(*this, S, CodeGen);
Kelvin Li986330c2016-07-20 22:57:10 +00002097}
2098
Kelvin Li80e8f562016-12-29 22:16:30 +00002099void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
2100 const OMPTargetTeamsDistributeParallelForDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002101 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Li80e8f562016-12-29 22:16:30 +00002102 CGM.getOpenMPRuntime().emitInlinedDirective(
2103 *this, OMPD_target_teams_distribute_parallel_for,
2104 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2105 CGF.EmitStmt(
2106 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2107 });
2108}
2109
Kelvin Li1851df52017-01-03 05:23:48 +00002110void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2111 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
Alexey Bataev931e19b2017-10-02 16:32:39 +00002112 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Kelvin Li1851df52017-01-03 05:23:48 +00002113 CGM.getOpenMPRuntime().emitInlinedDirective(
2114 *this, OMPD_target_teams_distribute_parallel_for_simd,
2115 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2116 CGF.EmitStmt(
2117 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2118 });
2119}
2120
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002121namespace {
2122 struct ScheduleKindModifiersTy {
2123 OpenMPScheduleClauseKind Kind;
2124 OpenMPScheduleClauseModifier M1;
2125 OpenMPScheduleClauseModifier M2;
2126 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2127 OpenMPScheduleClauseModifier M1,
2128 OpenMPScheduleClauseModifier M2)
2129 : Kind(Kind), M1(M1), M2(M2) {}
2130 };
2131} // namespace
2132
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002133bool CodeGenFunction::EmitOMPWorksharingLoop(
2134 const OMPLoopDirective &S, Expr *EUB,
2135 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2136 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002137 // Emit the loop iteration variable.
2138 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2139 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2140 EmitVarDecl(*IVDecl);
2141
2142 // Emit the iterations count variable.
2143 // If it is not a variable, Sema decided to calculate iterations count on each
2144 // iteration (e.g., it is foldable into a constant).
2145 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2146 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2147 // Emit calculation of the iterations count.
2148 EmitIgnoredExpr(S.getCalcLastIteration());
2149 }
2150
2151 auto &RT = CGM.getOpenMPRuntime();
2152
Alexey Bataev38e89532015-04-16 04:54:05 +00002153 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002154 // Check pre-condition.
2155 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002156 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002157 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002158 // If the condition constant folds and can be elided, avoid emitting the
2159 // whole loop.
2160 bool CondConstant;
2161 llvm::BasicBlock *ContBlock = nullptr;
2162 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2163 if (!CondConstant)
2164 return false;
2165 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002166 auto *ThenBlock = createBasicBlock("omp.precond.then");
2167 ContBlock = createBasicBlock("omp.precond.end");
2168 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002169 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002170 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002171 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002172 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002173
Alexey Bataev8b427062016-05-25 12:36:08 +00002174 bool Ordered = false;
2175 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2176 if (OrderedClause->getNumForLoops())
2177 RT.emitDoacrossInit(*this, S);
2178 else
2179 Ordered = true;
2180 }
2181
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002182 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002183 emitAlignedClause(*this, S);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002184 bool HasLinears = EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002185 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002186
2187 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2188 LValue LB = Bounds.first;
2189 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002190 LValue ST =
2191 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2192 LValue IL =
2193 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2194
Alexander Musmanc6388682014-12-15 07:07:06 +00002195 // Emit 'then' code.
2196 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002197 OMPPrivateScope LoopScope(*this);
Alexey Bataev8c3edfe2017-08-16 15:58:46 +00002198 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00002199 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002200 // initialization of firstprivate variables and post-update of
2201 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002202 CGM.getOpenMPRuntime().emitBarrierCall(
2203 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2204 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002205 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002206 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002207 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002208 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002209 EmitOMPPrivateLoopCounters(S, LoopScope);
2210 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002211 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002212
2213 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002214 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002215 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002216 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002217 ScheduleKind.Schedule = C->getScheduleKind();
2218 ScheduleKind.M1 = C->getFirstScheduleModifier();
2219 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002220 if (const auto *Ch = C->getChunkSize()) {
2221 Chunk = EmitScalarExpr(Ch);
2222 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2223 S.getIterationVariable()->getType(),
2224 S.getLocStart());
2225 }
2226 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002227 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2228 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002229 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2230 // If the static schedule kind is specified or if the ordered clause is
2231 // specified, and if no monotonic modifier is specified, the effect will
2232 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002233 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002234 /* Chunked */ Chunk != nullptr) &&
2235 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002236 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2237 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002238 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2239 // When no chunk_size is specified, the iteration space is divided into
2240 // chunks that are approximately equal in size, and at most one chunk is
2241 // distributed to each thread. Note that the size of the chunks is
2242 // unspecified in this case.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002243 CGOpenMPRuntime::StaticRTInput StaticInit(
2244 IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
2245 UB.getAddress(), ST.getAddress());
2246 RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
2247 ScheduleKind, StaticInit);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002248 auto LoopExit =
2249 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002250 // UB = min(UB, GlobalUB);
2251 EmitIgnoredExpr(S.getEnsureUpperBound());
2252 // IV = LB;
2253 EmitIgnoredExpr(S.getInit());
2254 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002255 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2256 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002257 [&S, LoopExit](CodeGenFunction &CGF) {
2258 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002259 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002260 },
2261 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002262 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002263 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002264 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002265 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2266 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002267 };
2268 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002269 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002270 const bool IsMonotonic =
2271 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2272 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2273 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2274 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002275 // Emit the outer loop, which requests its work chunk [LB..UB] from
2276 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002277 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2278 ST.getAddress(), IL.getAddress(),
2279 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002280 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002281 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002282 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002283 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2284 EmitOMPSimdFinal(S,
2285 [&](CodeGenFunction &CGF) -> llvm::Value * {
2286 return CGF.Builder.CreateIsNotNull(
2287 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2288 });
2289 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002290 EmitOMPReductionClauseFinal(
2291 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2292 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2293 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002294 // Emit post-update of the reduction variables if IsLastIter != 0.
2295 emitPostUpdateForReductionClause(
2296 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2297 return CGF.Builder.CreateIsNotNull(
2298 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2299 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002300 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2301 if (HasLastprivateClause)
2302 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002303 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2304 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002305 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002306 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002307 return CGF.Builder.CreateIsNotNull(
2308 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2309 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002310 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002311 if (ContBlock) {
2312 EmitBranch(ContBlock);
2313 EmitBlock(ContBlock, true);
2314 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002315 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002316 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002317}
2318
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002319/// The following two functions generate expressions for the loop lower
2320/// and upper bounds in case of static and dynamic (dispatch) schedule
2321/// of the associated 'for' or 'distribute' loop.
2322static std::pair<LValue, LValue>
2323emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2324 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2325 LValue LB =
2326 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2327 LValue UB =
2328 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2329 return {LB, UB};
2330}
2331
2332/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2333/// consider the lower and upper bound expressions generated by the
2334/// worksharing loop support, but we use 0 and the iteration space size as
2335/// constants
2336static std::pair<llvm::Value *, llvm::Value *>
2337emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2338 Address LB, Address UB) {
2339 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2340 const Expr *IVExpr = LS.getIterationVariable();
2341 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2342 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2343 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2344 return {LBVal, UBVal};
2345}
2346
Alexander Musmanc6388682014-12-15 07:07:06 +00002347void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002348 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002349 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2350 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002351 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002352 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2353 emitForLoopBounds,
2354 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002355 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002356 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002357 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002358 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2359 S.hasCancel());
2360 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002361
2362 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002363 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002364 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2365 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002366}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002367
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002368void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002369 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002370 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2371 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002372 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2373 emitForLoopBounds,
2374 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002375 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002376 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002377 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002378 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2379 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002380
2381 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002382 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002383 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2384 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002385}
2386
Alexey Bataev2df54a02015-03-12 08:53:29 +00002387static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2388 const Twine &Name,
2389 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002390 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002391 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002392 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002393 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002394}
2395
Alexey Bataev3392d762016-02-16 11:18:12 +00002396void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00002397 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2398 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002399 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002400 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2401 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002402 auto &C = CGF.CGM.getContext();
2403 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2404 // Emit helper vars inits.
2405 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2406 CGF.Builder.getInt32(0));
2407 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2408 : CGF.Builder.getInt32(0);
2409 LValue UB =
2410 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2411 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2412 CGF.Builder.getInt32(1));
2413 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2414 CGF.Builder.getInt32(0));
2415 // Loop counter.
2416 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2417 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2418 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2419 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2420 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2421 // Generate condition for loop.
2422 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002423 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002424 // Increment for loop counter.
2425 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2426 S.getLocStart());
2427 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2428 // Iterate through all sections and emit a switch construct:
2429 // switch (IV) {
2430 // case 0:
2431 // <SectionStmt[0]>;
2432 // break;
2433 // ...
2434 // case <NumSection> - 1:
2435 // <SectionStmt[<NumSection> - 1]>;
2436 // break;
2437 // }
2438 // .omp.sections.exit:
2439 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2440 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2441 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2442 CS == nullptr ? 1 : CS->size());
2443 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002444 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002445 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002446 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2447 CGF.EmitBlock(CaseBB);
2448 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002449 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002450 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002451 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002452 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002453 } else {
2454 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2455 CGF.EmitBlock(CaseBB);
2456 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2457 CGF.EmitStmt(Stmt);
2458 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002459 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002460 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002461 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002462
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002463 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2464 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002465 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002466 // initialization of firstprivate variables and post-update of lastprivate
2467 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002468 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2469 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2470 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002471 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002472 CGF.EmitOMPPrivateClause(S, LoopScope);
2473 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2474 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2475 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002476
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002477 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002478 OpenMPScheduleTy ScheduleKind;
2479 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002480 CGOpenMPRuntime::StaticRTInput StaticInit(
2481 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2482 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002483 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002484 CGF, S.getLocStart(), S.getDirectiveKind(), ScheduleKind, StaticInit);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002485 // UB = min(UB, GlobalUB);
2486 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2487 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2488 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2489 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2490 // IV = LB;
2491 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2492 // while (idx <= UB) { BODY; ++idx; }
2493 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2494 [](CodeGenFunction &) {});
2495 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002496 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataevf43f7142017-09-06 16:17:35 +00002497 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2498 S.getDirectiveKind());
Alexey Bataev957d8562016-11-17 15:12:05 +00002499 };
2500 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002501 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002502 // Emit post-update of the reduction variables if IsLastIter != 0.
2503 emitPostUpdateForReductionClause(
2504 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2505 return CGF.Builder.CreateIsNotNull(
2506 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2507 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002508
2509 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2510 if (HasLastprivates)
2511 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002512 S, /*NoFinals=*/false,
2513 CGF.Builder.CreateIsNotNull(
2514 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002515 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002516
2517 bool HasCancel = false;
2518 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2519 HasCancel = OSD->hasCancel();
2520 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2521 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002522 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002523 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2524 HasCancel);
2525 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2526 // clause. Otherwise the barrier will be generated by the codegen for the
2527 // directive.
2528 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002529 // Emit implicit barrier to synchronize threads and avoid data races on
2530 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002531 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2532 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002533 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002534}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002535
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002536void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002537 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002538 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002539 EmitSections(S);
2540 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002541 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002542 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002543 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2544 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002545 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002546}
2547
2548void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002549 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002550 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002551 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002552 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002553 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2554 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002555}
2556
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002557void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002558 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002559 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002560 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002561 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002562 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002563 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002564 // Build a list of copyprivate variables along with helper expressions
2565 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002566 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002567 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002568 DestExprs.append(C->destination_exprs().begin(),
2569 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002570 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002571 AssignmentOps.append(C->assignment_ops().begin(),
2572 C->assignment_ops().end());
2573 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002574 // Emit code for 'single' region along with 'copyprivate' clauses
2575 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2576 Action.Enter(CGF);
2577 OMPPrivateScope SingleScope(CGF);
2578 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2579 CGF.EmitOMPPrivateClause(S, SingleScope);
2580 (void)SingleScope.Privatize();
2581 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2582 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002583 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002584 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002585 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2586 CopyprivateVars, DestExprs,
2587 SrcExprs, AssignmentOps);
2588 }
2589 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2590 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002591 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002592 CGM.getOpenMPRuntime().emitBarrierCall(
2593 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002594 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002595 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002596}
2597
Alexey Bataev8d690652014-12-04 07:23:53 +00002598void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002599 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2600 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002601 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002602 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002603 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002604 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002605}
2606
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002607void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002608 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2609 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002610 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002611 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002612 Expr *Hint = nullptr;
2613 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2614 Hint = HintClause->getHint();
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002615 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002616 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2617 S.getDirectiveName().getAsString(),
2618 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002619}
2620
Alexey Bataev671605e2015-04-13 05:28:11 +00002621void CodeGenFunction::EmitOMPParallelForDirective(
2622 const OMPParallelForDirective &S) {
2623 // Emit directive as a combined directive that consists of two implicit
2624 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002625 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002626 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002627 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2628 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002629 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002630 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2631 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002632}
2633
Alexander Musmane4e893b2014-09-23 09:33:00 +00002634void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002635 const OMPParallelForSimdDirective &S) {
2636 // Emit directive as a combined directive that consists of two implicit
2637 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002638 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002639 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2640 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002641 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002642 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2643 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002644}
2645
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002646void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002647 const OMPParallelSectionsDirective &S) {
2648 // Emit directive as a combined directive that consists of two implicit
2649 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002650 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2651 CGF.EmitSections(S);
2652 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002653 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2654 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002655}
2656
Alexey Bataev7292c292016-04-25 12:22:29 +00002657void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2658 const RegionCodeGenTy &BodyGen,
2659 const TaskGenTy &TaskGen,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002660 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002661 // Emit outlined function for task construct.
2662 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002663 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002664 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002665 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002666 // Check if the task is final
2667 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2668 // If the condition constant folds and can be elided, try to avoid emitting
2669 // the condition and the dead arm of the if/else.
2670 auto *Cond = Clause->getCondition();
2671 bool CondConstant;
2672 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2673 Data.Final.setInt(CondConstant);
2674 else
2675 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2676 } else {
2677 // By default the task is not final.
2678 Data.Final.setInt(/*IntVal=*/false);
2679 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002680 // Check if the task has 'priority' clause.
2681 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002682 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002683 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002684 Data.Priority.setPointer(EmitScalarConversion(
2685 EmitScalarExpr(Prio), Prio->getType(),
2686 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2687 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002688 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002689 // The first function argument for tasks is a thread id, the second one is a
2690 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002691 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2692 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002693 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002694 auto IRef = C->varlist_begin();
2695 for (auto *IInit : C->private_copies()) {
2696 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2697 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002698 Data.PrivateVars.push_back(*IRef);
2699 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002700 }
2701 ++IRef;
2702 }
2703 }
2704 EmittedAsPrivate.clear();
2705 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002706 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002707 auto IRef = C->varlist_begin();
2708 auto IElemInitRef = C->inits().begin();
2709 for (auto *IInit : C->private_copies()) {
2710 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2711 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002712 Data.FirstprivateVars.push_back(*IRef);
2713 Data.FirstprivateCopies.push_back(IInit);
2714 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002715 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002716 ++IRef;
2717 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002718 }
2719 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002720 // Get list of lastprivate variables (for taskloops).
2721 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2722 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2723 auto IRef = C->varlist_begin();
2724 auto ID = C->destination_exprs().begin();
2725 for (auto *IInit : C->private_copies()) {
2726 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2727 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2728 Data.LastprivateVars.push_back(*IRef);
2729 Data.LastprivateCopies.push_back(IInit);
2730 }
2731 LastprivateDstsOrigs.insert(
2732 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2733 cast<DeclRefExpr>(*IRef)});
2734 ++IRef;
2735 ++ID;
2736 }
2737 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002738 SmallVector<const Expr *, 4> LHSs;
2739 SmallVector<const Expr *, 4> RHSs;
2740 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2741 auto IPriv = C->privates().begin();
2742 auto IRed = C->reduction_ops().begin();
2743 auto ILHS = C->lhs_exprs().begin();
2744 auto IRHS = C->rhs_exprs().begin();
2745 for (const auto *Ref : C->varlists()) {
2746 Data.ReductionVars.emplace_back(Ref);
2747 Data.ReductionCopies.emplace_back(*IPriv);
2748 Data.ReductionOps.emplace_back(*IRed);
2749 LHSs.emplace_back(*ILHS);
2750 RHSs.emplace_back(*IRHS);
2751 std::advance(IPriv, 1);
2752 std::advance(IRed, 1);
2753 std::advance(ILHS, 1);
2754 std::advance(IRHS, 1);
2755 }
2756 }
2757 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2758 *this, S.getLocStart(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002759 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002760 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2761 for (auto *IRef : C->varlists())
2762 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002763 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs](
Alexey Bataevf93095a2016-05-05 08:46:22 +00002764 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002765 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002766 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002767 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2768 !Data.LastprivateVars.empty()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00002769 enum { PrivatesParam = 2, CopyFnParam = 3 };
Alexey Bataev48591dd2016-04-20 04:01:36 +00002770 auto *CopyFn = CGF.Builder.CreateLoad(
2771 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2772 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2773 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2774 // Map privates.
2775 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2776 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2777 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002778 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002779 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2780 Address PrivatePtr = CGF.CreateMemTemp(
2781 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2782 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2783 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002784 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002785 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002786 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2787 Address PrivatePtr =
2788 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2789 ".firstpriv.ptr.addr");
2790 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2791 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002792 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002793 for (auto *E : Data.LastprivateVars) {
2794 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2795 Address PrivatePtr =
2796 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2797 ".lastpriv.ptr.addr");
2798 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2799 CallArgs.push_back(PrivatePtr.getPointer());
2800 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00002801 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
2802 CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002803 for (auto &&Pair : LastprivateDstsOrigs) {
2804 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2805 DeclRefExpr DRE(
2806 const_cast<VarDecl *>(OrigVD),
2807 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2808 OrigVD) != nullptr,
2809 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2810 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2811 return CGF.EmitLValue(&DRE).getAddress();
2812 });
2813 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002814 for (auto &&Pair : PrivatePtrs) {
2815 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2816 CGF.getContext().getDeclAlign(Pair.first));
2817 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2818 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002819 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002820 if (Data.Reductions) {
2821 OMPLexicalScope LexScope(CGF, S, /*AsInlined=*/true);
2822 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2823 Data.ReductionOps);
2824 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2825 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2826 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2827 RedCG.emitSharedLValue(CGF, Cnt);
2828 RedCG.emitAggregateType(CGF, Cnt);
2829 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2830 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2831 Replacement =
2832 Address(CGF.EmitScalarConversion(
2833 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2834 CGF.getContext().getPointerType(
2835 Data.ReductionCopies[Cnt]->getType()),
2836 SourceLocation()),
2837 Replacement.getAlignment());
2838 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2839 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2840 [Replacement]() { return Replacement; });
2841 // FIXME: This must removed once the runtime library is fixed.
2842 // Emit required threadprivate variables for
2843 // initilizer/combiner/finalizer.
2844 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2845 RedCG, Cnt);
2846 }
2847 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002848 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002849 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002850 SmallVector<const Expr *, 4> InRedVars;
2851 SmallVector<const Expr *, 4> InRedPrivs;
2852 SmallVector<const Expr *, 4> InRedOps;
2853 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2854 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2855 auto IPriv = C->privates().begin();
2856 auto IRed = C->reduction_ops().begin();
2857 auto ITD = C->taskgroup_descriptors().begin();
2858 for (const auto *Ref : C->varlists()) {
2859 InRedVars.emplace_back(Ref);
2860 InRedPrivs.emplace_back(*IPriv);
2861 InRedOps.emplace_back(*IRed);
2862 TaskgroupDescriptors.emplace_back(*ITD);
2863 std::advance(IPriv, 1);
2864 std::advance(IRed, 1);
2865 std::advance(ITD, 1);
2866 }
2867 }
2868 // Privatize in_reduction items here, because taskgroup descriptors must be
2869 // privatized earlier.
2870 OMPPrivateScope InRedScope(CGF);
2871 if (!InRedVars.empty()) {
2872 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2873 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2874 RedCG.emitSharedLValue(CGF, Cnt);
2875 RedCG.emitAggregateType(CGF, Cnt);
2876 // The taskgroup descriptor variable is always implicit firstprivate and
2877 // privatized already during procoessing of the firstprivates.
2878 llvm::Value *ReductionsPtr = CGF.EmitLoadOfScalar(
2879 CGF.EmitLValue(TaskgroupDescriptors[Cnt]), SourceLocation());
2880 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2881 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2882 Replacement = Address(
2883 CGF.EmitScalarConversion(
2884 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2885 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
2886 SourceLocation()),
2887 Replacement.getAlignment());
2888 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2889 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2890 [Replacement]() { return Replacement; });
2891 // FIXME: This must removed once the runtime library is fixed.
2892 // Emit required threadprivate variables for
2893 // initilizer/combiner/finalizer.
2894 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2895 RedCG, Cnt);
2896 }
2897 }
2898 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00002899
2900 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002901 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002902 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002903 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2904 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2905 Data.NumberOfParts);
2906 OMPLexicalScope Scope(*this, S);
2907 TaskGen(*this, OutlinedFn, Data);
2908}
2909
Alexey Bataevd2202ca2017-12-27 17:58:32 +00002910static ImplicitParamDecl *
2911createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
2912 QualType Ty, CapturedDecl *CD) {
2913 auto *OrigVD = ImplicitParamDecl::Create(
2914 C, CD, SourceLocation(), /*Id=*/nullptr, Ty, ImplicitParamDecl::Other);
2915 auto *OrigRef =
2916 DeclRefExpr::Create(C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
2917 /*RefersToEnclosingVariableOrCapture=*/false,
2918 SourceLocation(), Ty, VK_LValue);
2919 auto *PrivateVD = ImplicitParamDecl::Create(
2920 C, CD, SourceLocation(), /*Id=*/nullptr, Ty, ImplicitParamDecl::Other);
2921 auto *PrivateRef = DeclRefExpr::Create(
2922 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
2923 /*RefersToEnclosingVariableOrCapture=*/false, SourceLocation(), Ty,
2924 VK_LValue);
2925 QualType ElemType = C.getBaseElementType(Ty);
2926 auto *InitVD =
2927 ImplicitParamDecl::Create(C, CD, SourceLocation(), /*Id=*/nullptr,
2928 ElemType, ImplicitParamDecl::Other);
2929 auto *InitRef =
2930 DeclRefExpr::Create(C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
2931 /*RefersToEnclosingVariableOrCapture=*/false,
2932 SourceLocation(), ElemType, VK_LValue);
2933 PrivateVD->setInitStyle(VarDecl::CInit);
2934 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
2935 InitRef, /*BasePath=*/nullptr,
2936 VK_RValue));
2937 Data.FirstprivateVars.emplace_back(OrigRef);
2938 Data.FirstprivateCopies.emplace_back(PrivateRef);
2939 Data.FirstprivateInits.emplace_back(InitRef);
2940 return OrigVD;
2941}
2942
2943void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
2944 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
2945 OMPTargetDataInfo &InputInfo) {
2946 // Emit outlined function for task construct.
2947 auto CS = S.getCapturedStmt(OMPD_task);
2948 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
2949 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
2950 auto *I = CS->getCapturedDecl()->param_begin();
2951 auto *PartId = std::next(I);
2952 auto *TaskT = std::next(I, 4);
2953 OMPTaskDataTy Data;
2954 // The task is not final.
2955 Data.Final.setInt(/*IntVal=*/false);
2956 // Get list of firstprivate variables.
2957 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
2958 auto IRef = C->varlist_begin();
2959 auto IElemInitRef = C->inits().begin();
2960 for (auto *IInit : C->private_copies()) {
2961 Data.FirstprivateVars.push_back(*IRef);
2962 Data.FirstprivateCopies.push_back(IInit);
2963 Data.FirstprivateInits.push_back(*IElemInitRef);
2964 ++IRef;
2965 ++IElemInitRef;
2966 }
2967 }
2968 OMPPrivateScope TargetScope(*this);
2969 VarDecl *BPVD = nullptr;
2970 VarDecl *PVD = nullptr;
2971 VarDecl *SVD = nullptr;
2972 if (InputInfo.NumberOfTargetItems > 0) {
2973 auto *CD = CapturedDecl::Create(
2974 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
2975 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
2976 QualType BaseAndPointersType = getContext().getConstantArrayType(
2977 getContext().VoidPtrTy, ArrSize, ArrayType::Normal,
2978 /*IndexTypeQuals=*/0);
2979 BPVD = createImplicitFirstprivateForType(getContext(), Data,
2980 BaseAndPointersType, CD);
2981 PVD = createImplicitFirstprivateForType(getContext(), Data,
2982 BaseAndPointersType, CD);
2983 QualType SizesType = getContext().getConstantArrayType(
2984 getContext().getSizeType(), ArrSize, ArrayType::Normal,
2985 /*IndexTypeQuals=*/0);
2986 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD);
2987 TargetScope.addPrivate(
2988 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
2989 TargetScope.addPrivate(PVD,
2990 [&InputInfo]() { return InputInfo.PointersArray; });
2991 TargetScope.addPrivate(SVD,
2992 [&InputInfo]() { return InputInfo.SizesArray; });
2993 }
2994 (void)TargetScope.Privatize();
2995 // Build list of dependences.
2996 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2997 for (auto *IRef : C->varlists())
2998 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
2999 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3000 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3001 // Set proper addresses for generated private copies.
3002 OMPPrivateScope Scope(CGF);
3003 if (!Data.FirstprivateVars.empty()) {
3004 enum { PrivatesParam = 2, CopyFnParam = 3 };
3005 auto *CopyFn = CGF.Builder.CreateLoad(
3006 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
3007 auto *PrivatesPtr = CGF.Builder.CreateLoad(
3008 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
3009 // Map privates.
3010 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3011 llvm::SmallVector<llvm::Value *, 16> CallArgs;
3012 CallArgs.push_back(PrivatesPtr);
3013 for (auto *E : Data.FirstprivateVars) {
3014 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3015 Address PrivatePtr =
3016 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3017 ".firstpriv.ptr.addr");
3018 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
3019 CallArgs.push_back(PrivatePtr.getPointer());
3020 }
3021 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3022 CopyFn, CallArgs);
3023 for (auto &&Pair : PrivatePtrs) {
3024 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3025 CGF.getContext().getDeclAlign(Pair.first));
3026 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3027 }
3028 }
3029 // Privatize all private variables except for in_reduction items.
3030 (void)Scope.Privatize();
3031 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
3032 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0, CGF.getPointerSize());
3033 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
3034 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0, CGF.getPointerSize());
3035 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
3036 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0, CGF.getSizeSize());
3037
3038 Action.Enter(CGF);
3039 OMPLexicalScope LexScope(CGF, S, /*AsInlined=*/true,
3040 /*EmitPreInitStmt=*/false);
3041 BodyGen(CGF);
3042 };
3043 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
3044 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3045 Data.NumberOfParts);
3046 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3047 IntegerLiteral IfCond(getContext(), TrueOrFalse,
3048 getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3049 SourceLocation());
3050
3051 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getLocStart(), S, OutlinedFn,
3052 SharedsTy, CapturedStruct, &IfCond, Data);
3053}
3054
Alexey Bataev7292c292016-04-25 12:22:29 +00003055void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3056 // Emit outlined function for task construct.
3057 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3058 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003059 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00003060 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00003061 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3062 if (C->getNameModifier() == OMPD_unknown ||
3063 C->getNameModifier() == OMPD_task) {
3064 IfCond = C->getCondition();
3065 break;
3066 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003067 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003068
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003069 OMPTaskDataTy Data;
3070 // Check if we should emit tied or untied task.
3071 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003072 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3073 CGF.EmitStmt(CS->getCapturedStmt());
3074 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003075 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00003076 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003077 const OMPTaskDataTy &Data) {
3078 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
3079 SharedsTy, CapturedStruct, IfCond,
3080 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003081 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003082 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003083}
3084
Alexey Bataev9f797f32015-02-05 05:57:51 +00003085void CodeGenFunction::EmitOMPTaskyieldDirective(
3086 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003087 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00003088}
3089
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003090void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00003091 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003092}
3093
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003094void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
3095 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00003096}
3097
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003098void CodeGenFunction::EmitOMPTaskgroupDirective(
3099 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003100 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3101 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00003102 if (const Expr *E = S.getReductionRef()) {
3103 SmallVector<const Expr *, 4> LHSs;
3104 SmallVector<const Expr *, 4> RHSs;
3105 OMPTaskDataTy Data;
3106 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3107 auto IPriv = C->privates().begin();
3108 auto IRed = C->reduction_ops().begin();
3109 auto ILHS = C->lhs_exprs().begin();
3110 auto IRHS = C->rhs_exprs().begin();
3111 for (const auto *Ref : C->varlists()) {
3112 Data.ReductionVars.emplace_back(Ref);
3113 Data.ReductionCopies.emplace_back(*IPriv);
3114 Data.ReductionOps.emplace_back(*IRed);
3115 LHSs.emplace_back(*ILHS);
3116 RHSs.emplace_back(*IRHS);
3117 std::advance(IPriv, 1);
3118 std::advance(IRed, 1);
3119 std::advance(ILHS, 1);
3120 std::advance(IRHS, 1);
3121 }
3122 }
3123 llvm::Value *ReductionDesc =
3124 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getLocStart(),
3125 LHSs, RHSs, Data);
3126 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3127 CGF.EmitVarDecl(*VD);
3128 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3129 /*Volatile=*/false, E->getType());
3130 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003131 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003132 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003133 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003134 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
3135}
3136
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003137void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003138 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003139 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003140 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3141 FlushClause->varlist_end());
3142 }
3143 return llvm::None;
3144 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00003145}
3146
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003147void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3148 const CodeGenLoopTy &CodeGenLoop,
3149 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003150 // Emit the loop iteration variable.
3151 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3152 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
3153 EmitVarDecl(*IVDecl);
3154
3155 // Emit the iterations count variable.
3156 // If it is not a variable, Sema decided to calculate iterations count on each
3157 // iteration (e.g., it is foldable into a constant).
3158 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3159 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3160 // Emit calculation of the iterations count.
3161 EmitIgnoredExpr(S.getCalcLastIteration());
3162 }
3163
3164 auto &RT = CGM.getOpenMPRuntime();
3165
Carlo Bertolli962bb802017-01-03 18:24:42 +00003166 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003167 // Check pre-condition.
3168 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003169 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003170 // Skip the entire loop if we don't meet the precondition.
3171 // If the condition constant folds and can be elided, avoid emitting the
3172 // whole loop.
3173 bool CondConstant;
3174 llvm::BasicBlock *ContBlock = nullptr;
3175 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3176 if (!CondConstant)
3177 return;
3178 } else {
3179 auto *ThenBlock = createBasicBlock("omp.precond.then");
3180 ContBlock = createBasicBlock("omp.precond.end");
3181 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3182 getProfileCount(&S));
3183 EmitBlock(ThenBlock);
3184 incrementProfileCounter(&S);
3185 }
3186
Alexey Bataev617db5f2017-12-04 15:38:33 +00003187 emitAlignedClause(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003188 // Emit 'then' code.
3189 {
3190 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003191
3192 LValue LB = EmitOMPHelperVar(
3193 *this, cast<DeclRefExpr>(
3194 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3195 ? S.getCombinedLowerBoundVariable()
3196 : S.getLowerBoundVariable())));
3197 LValue UB = EmitOMPHelperVar(
3198 *this, cast<DeclRefExpr>(
3199 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3200 ? S.getCombinedUpperBoundVariable()
3201 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003202 LValue ST =
3203 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3204 LValue IL =
3205 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3206
3207 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003208 if (EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003209 // Emit implicit barrier to synchronize threads and avoid data races
3210 // on initialization of firstprivate variables and post-update of
Carlo Bertolli962bb802017-01-03 18:24:42 +00003211 // lastprivate variables.
3212 CGM.getOpenMPRuntime().emitBarrierCall(
Alexey Bataev617db5f2017-12-04 15:38:33 +00003213 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3214 /*ForceSimpleCall=*/true);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003215 }
3216 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev617db5f2017-12-04 15:38:33 +00003217 if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
Alexey Bataev999277a2017-12-06 14:31:09 +00003218 !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3219 !isOpenMPTeamsDirective(S.getDirectiveKind()))
Alexey Bataev617db5f2017-12-04 15:38:33 +00003220 EmitOMPReductionClauseInit(S, LoopScope);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003221 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003222 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003223 (void)LoopScope.Privatize();
3224
3225 // Detect the distribute schedule kind and chunk.
3226 llvm::Value *Chunk = nullptr;
3227 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3228 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3229 ScheduleKind = C->getDistScheduleKind();
3230 if (const auto *Ch = C->getChunkSize()) {
3231 Chunk = EmitScalarExpr(Ch);
3232 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
Alexey Bataev617db5f2017-12-04 15:38:33 +00003233 S.getIterationVariable()->getType(),
3234 S.getLocStart());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003235 }
3236 }
3237 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3238 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3239
3240 // OpenMP [2.10.8, distribute Construct, Description]
3241 // If dist_schedule is specified, kind must be static. If specified,
3242 // iterations are divided into chunks of size chunk_size, chunks are
3243 // assigned to the teams of the league in a round-robin fashion in the
3244 // order of the team number. When no chunk_size is specified, the
3245 // iteration space is divided into chunks that are approximately equal
3246 // in size, and at most one chunk is distributed to each team of the
3247 // league. The size of the chunks is unspecified in this case.
3248 if (RT.isStaticNonchunked(ScheduleKind,
3249 /* Chunked */ Chunk != nullptr)) {
Alexey Bataev617db5f2017-12-04 15:38:33 +00003250 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3251 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003252 CGOpenMPRuntime::StaticRTInput StaticInit(
3253 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3254 LB.getAddress(), UB.getAddress(), ST.getAddress());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003255 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003256 StaticInit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003257 auto LoopExit =
3258 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3259 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003260 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3261 ? S.getCombinedEnsureUpperBound()
3262 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003263 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003264 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3265 ? S.getCombinedInit()
3266 : S.getInit());
3267
3268 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3269 ? S.getCombinedCond()
3270 : S.getCond();
3271
3272 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003273 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003274 // when combined with 'for' (e.g. as in 'distribute parallel for')
3275 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3276 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3277 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3278 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003279 },
3280 [](CodeGenFunction &) {});
3281 EmitBlock(LoopExit.getBlock());
3282 // Tell the runtime we are done.
Alexey Bataevf43f7142017-09-06 16:17:35 +00003283 RT.emitForStaticFinish(*this, S.getLocStart(), S.getDirectiveKind());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003284 } else {
3285 // Emit the outer loop, which requests its work chunk [LB..UB] from
3286 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003287 const OMPLoopArguments LoopArguments = {
3288 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3289 Chunk};
3290 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3291 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003292 }
Alexey Bataev617db5f2017-12-04 15:38:33 +00003293 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3294 EmitOMPSimdFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3295 return CGF.Builder.CreateIsNotNull(
3296 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3297 });
3298 }
3299 OpenMPDirectiveKind ReductionKind = OMPD_unknown;
3300 if (isOpenMPParallelDirective(S.getDirectiveKind()) &&
3301 isOpenMPSimdDirective(S.getDirectiveKind())) {
3302 ReductionKind = OMPD_parallel_for_simd;
3303 } else if (isOpenMPParallelDirective(S.getDirectiveKind())) {
3304 ReductionKind = OMPD_parallel_for;
3305 } else if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3306 ReductionKind = OMPD_simd;
3307 } else if (!isOpenMPTeamsDirective(S.getDirectiveKind()) &&
3308 S.hasClausesOfKind<OMPReductionClause>()) {
3309 llvm_unreachable(
3310 "No reduction clauses is allowed in distribute directive.");
3311 }
3312 EmitOMPReductionClauseFinal(S, ReductionKind);
3313 // Emit post-update of the reduction variables if IsLastIter != 0.
3314 emitPostUpdateForReductionClause(
3315 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3316 return CGF.Builder.CreateIsNotNull(
3317 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3318 });
Carlo Bertolli962bb802017-01-03 18:24:42 +00003319 // Emit final copy of the lastprivate variables if IsLastIter != 0.
Alexey Bataev617db5f2017-12-04 15:38:33 +00003320 if (HasLastprivateClause) {
Carlo Bertolli962bb802017-01-03 18:24:42 +00003321 EmitOMPLastprivateClauseFinal(
3322 S, /*NoFinals=*/false,
Alexey Bataev617db5f2017-12-04 15:38:33 +00003323 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
3324 }
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003325 }
3326
3327 // We're now done with the loop, so jump to the continuation block.
3328 if (ContBlock) {
3329 EmitBranch(ContBlock);
3330 EmitBlock(ContBlock, true);
3331 }
3332 }
3333}
3334
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003335void CodeGenFunction::EmitOMPDistributeDirective(
3336 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003337 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003338
3339 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003340 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003341 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev10a54312017-11-27 16:54:08 +00003342 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003343}
3344
Alexey Bataev5f600d62015-09-29 03:48:57 +00003345static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3346 const CapturedStmt *S) {
3347 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3348 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3349 CGF.CapturedStmtInfo = &CapStmtInfo;
3350 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3351 Fn->addFnAttr(llvm::Attribute::NoInline);
3352 return Fn;
3353}
3354
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003355void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8b427062016-05-25 12:36:08 +00003356 if (!S.getAssociatedStmt()) {
3357 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3358 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003359 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003360 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003361 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003362 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3363 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003364 if (C) {
3365 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3366 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3367 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3368 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Alexey Bataev3c595a62017-08-14 15:01:03 +00003369 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3370 OutlinedFn, CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003371 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003372 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003373 CGF.EmitStmt(
3374 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3375 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003376 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003377 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003378 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003379}
3380
Alexey Bataevb57056f2015-01-22 06:17:56 +00003381static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003382 QualType SrcType, QualType DestType,
3383 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003384 assert(CGF.hasScalarEvaluationKind(DestType) &&
3385 "DestType must have scalar evaluation kind.");
3386 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3387 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003388 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3389 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00003390 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003391 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003392}
3393
3394static CodeGenFunction::ComplexPairTy
3395convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003396 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003397 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3398 "DestType must have complex evaluation kind.");
3399 CodeGenFunction::ComplexPairTy ComplexVal;
3400 if (Val.isScalar()) {
3401 // Convert the input element to the element type of the complex.
3402 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003403 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3404 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003405 ComplexVal = CodeGenFunction::ComplexPairTy(
3406 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3407 } else {
3408 assert(Val.isComplex() && "Must be a scalar or complex.");
3409 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3410 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3411 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003412 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003413 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003414 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003415 }
3416 return ComplexVal;
3417}
3418
Alexey Bataev5e018f92015-04-23 06:35:10 +00003419static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3420 LValue LVal, RValue RVal) {
3421 if (LVal.isGlobalReg()) {
3422 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3423 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003424 CGF.EmitAtomicStore(RVal, LVal,
3425 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3426 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003427 LVal.isVolatile(), /*IsInit=*/false);
3428 }
3429}
3430
Alexey Bataev8524d152016-01-21 12:35:58 +00003431void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3432 QualType RValTy, SourceLocation Loc) {
3433 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003434 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003435 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3436 *this, RVal, RValTy, LVal.getType(), Loc)),
3437 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003438 break;
3439 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003440 EmitStoreOfComplex(
3441 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003442 /*isInit=*/false);
3443 break;
3444 case TEK_Aggregate:
3445 llvm_unreachable("Must be a scalar or complex.");
3446 }
3447}
3448
Alexey Bataevb57056f2015-01-22 06:17:56 +00003449static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3450 const Expr *X, const Expr *V,
3451 SourceLocation Loc) {
3452 // v = x;
3453 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3454 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3455 LValue XLValue = CGF.EmitLValue(X);
3456 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003457 RValue Res = XLValue.isGlobalReg()
3458 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003459 : CGF.EmitAtomicLoad(
3460 XLValue, Loc,
3461 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3462 : llvm::AtomicOrdering::Monotonic,
3463 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003464 // OpenMP, 2.12.6, atomic Construct
3465 // Any atomic construct with a seq_cst clause forces the atomically
3466 // performed operation to include an implicit flush operation without a
3467 // list.
3468 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003469 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003470 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003471}
3472
Alexey Bataevb8329262015-02-27 06:33:30 +00003473static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3474 const Expr *X, const Expr *E,
3475 SourceLocation Loc) {
3476 // x = expr;
3477 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003478 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003479 // OpenMP, 2.12.6, atomic Construct
3480 // Any atomic construct with a seq_cst clause forces the atomically
3481 // performed operation to include an implicit flush operation without a
3482 // list.
3483 if (IsSeqCst)
3484 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3485}
3486
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003487static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3488 RValue Update,
3489 BinaryOperatorKind BO,
3490 llvm::AtomicOrdering AO,
3491 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003492 auto &Context = CGF.CGM.getContext();
3493 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003494 // expression is simple and atomic is allowed for the given type for the
3495 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003496 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003497 !Update.getScalarVal()->getType()->isIntegerTy() ||
3498 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3499 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003500 X.getAddress().getElementType())) ||
3501 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003502 !Context.getTargetInfo().hasBuiltinAtomic(
3503 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003504 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003505
3506 llvm::AtomicRMWInst::BinOp RMWOp;
3507 switch (BO) {
3508 case BO_Add:
3509 RMWOp = llvm::AtomicRMWInst::Add;
3510 break;
3511 case BO_Sub:
3512 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003513 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003514 RMWOp = llvm::AtomicRMWInst::Sub;
3515 break;
3516 case BO_And:
3517 RMWOp = llvm::AtomicRMWInst::And;
3518 break;
3519 case BO_Or:
3520 RMWOp = llvm::AtomicRMWInst::Or;
3521 break;
3522 case BO_Xor:
3523 RMWOp = llvm::AtomicRMWInst::Xor;
3524 break;
3525 case BO_LT:
3526 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3527 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3528 : llvm::AtomicRMWInst::Max)
3529 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3530 : llvm::AtomicRMWInst::UMax);
3531 break;
3532 case BO_GT:
3533 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3534 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3535 : llvm::AtomicRMWInst::Min)
3536 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3537 : llvm::AtomicRMWInst::UMin);
3538 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003539 case BO_Assign:
3540 RMWOp = llvm::AtomicRMWInst::Xchg;
3541 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003542 case BO_Mul:
3543 case BO_Div:
3544 case BO_Rem:
3545 case BO_Shl:
3546 case BO_Shr:
3547 case BO_LAnd:
3548 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003549 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003550 case BO_PtrMemD:
3551 case BO_PtrMemI:
3552 case BO_LE:
3553 case BO_GE:
3554 case BO_EQ:
3555 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00003556 case BO_Cmp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003557 case BO_AddAssign:
3558 case BO_SubAssign:
3559 case BO_AndAssign:
3560 case BO_OrAssign:
3561 case BO_XorAssign:
3562 case BO_MulAssign:
3563 case BO_DivAssign:
3564 case BO_RemAssign:
3565 case BO_ShlAssign:
3566 case BO_ShrAssign:
3567 case BO_Comma:
3568 llvm_unreachable("Unsupported atomic update operation");
3569 }
3570 auto *UpdateVal = Update.getScalarVal();
3571 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3572 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003573 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003574 X.getType()->hasSignedIntegerRepresentation());
3575 }
John McCall7f416cc2015-09-08 08:05:57 +00003576 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003577 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003578}
3579
Alexey Bataev5e018f92015-04-23 06:35:10 +00003580std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003581 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3582 llvm::AtomicOrdering AO, SourceLocation Loc,
3583 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3584 // Update expressions are allowed to have the following forms:
3585 // x binop= expr; -> xrval + expr;
3586 // x++, ++x -> xrval + 1;
3587 // x--, --x -> xrval - 1;
3588 // x = x binop expr; -> xrval binop expr
3589 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003590 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3591 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003592 if (X.isGlobalReg()) {
3593 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3594 // 'xrval'.
3595 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3596 } else {
3597 // Perform compare-and-swap procedure.
3598 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003599 }
3600 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003601 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003602}
3603
3604static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3605 const Expr *X, const Expr *E,
3606 const Expr *UE, bool IsXLHSInRHSPart,
3607 SourceLocation Loc) {
3608 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3609 "Update expr in 'atomic update' must be a binary operator.");
3610 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3611 // Update expressions are allowed to have the following forms:
3612 // x binop= expr; -> xrval + expr;
3613 // x++, ++x -> xrval + 1;
3614 // x--, --x -> xrval - 1;
3615 // x = x binop expr; -> xrval binop expr
3616 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003617 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003618 LValue XLValue = CGF.EmitLValue(X);
3619 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003620 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3621 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003622 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3623 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3624 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3625 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3626 auto Gen =
3627 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3628 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3629 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3630 return CGF.EmitAnyExpr(UE);
3631 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003632 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3633 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3634 // OpenMP, 2.12.6, atomic Construct
3635 // Any atomic construct with a seq_cst clause forces the atomically
3636 // performed operation to include an implicit flush operation without a
3637 // list.
3638 if (IsSeqCst)
3639 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3640}
3641
3642static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003643 QualType SourceType, QualType ResType,
3644 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003645 switch (CGF.getEvaluationKind(ResType)) {
3646 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003647 return RValue::get(
3648 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003649 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003650 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003651 return RValue::getComplex(Res.first, Res.second);
3652 }
3653 case TEK_Aggregate:
3654 break;
3655 }
3656 llvm_unreachable("Must be a scalar or complex.");
3657}
3658
3659static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3660 bool IsPostfixUpdate, const Expr *V,
3661 const Expr *X, const Expr *E,
3662 const Expr *UE, bool IsXLHSInRHSPart,
3663 SourceLocation Loc) {
3664 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3665 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3666 RValue NewVVal;
3667 LValue VLValue = CGF.EmitLValue(V);
3668 LValue XLValue = CGF.EmitLValue(X);
3669 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003670 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3671 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003672 QualType NewVValType;
3673 if (UE) {
3674 // 'x' is updated with some additional value.
3675 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3676 "Update expr in 'atomic capture' must be a binary operator.");
3677 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3678 // Update expressions are allowed to have the following forms:
3679 // x binop= expr; -> xrval + expr;
3680 // x++, ++x -> xrval + 1;
3681 // x--, --x -> xrval - 1;
3682 // x = x binop expr; -> xrval binop expr
3683 // x = expr Op x; - > expr binop xrval;
3684 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3685 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3686 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3687 NewVValType = XRValExpr->getType();
3688 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3689 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003690 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003691 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3692 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3693 RValue Res = CGF.EmitAnyExpr(UE);
3694 NewVVal = IsPostfixUpdate ? XRValue : Res;
3695 return Res;
3696 };
3697 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3698 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3699 if (Res.first) {
3700 // 'atomicrmw' instruction was generated.
3701 if (IsPostfixUpdate) {
3702 // Use old value from 'atomicrmw'.
3703 NewVVal = Res.second;
3704 } else {
3705 // 'atomicrmw' does not provide new value, so evaluate it using old
3706 // value of 'x'.
3707 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3708 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3709 NewVVal = CGF.EmitAnyExpr(UE);
3710 }
3711 }
3712 } else {
3713 // 'x' is simply rewritten with some 'expr'.
3714 NewVValType = X->getType().getNonReferenceType();
3715 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003716 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003717 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003718 NewVVal = XRValue;
3719 return ExprRValue;
3720 };
3721 // Try to perform atomicrmw xchg, otherwise simple exchange.
3722 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3723 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3724 Loc, Gen);
3725 if (Res.first) {
3726 // 'atomicrmw' instruction was generated.
3727 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3728 }
3729 }
3730 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003731 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003732 // OpenMP, 2.12.6, atomic Construct
3733 // Any atomic construct with a seq_cst clause forces the atomically
3734 // performed operation to include an implicit flush operation without a
3735 // list.
3736 if (IsSeqCst)
3737 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3738}
3739
Alexey Bataevb57056f2015-01-22 06:17:56 +00003740static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003741 bool IsSeqCst, bool IsPostfixUpdate,
3742 const Expr *X, const Expr *V, const Expr *E,
3743 const Expr *UE, bool IsXLHSInRHSPart,
3744 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003745 switch (Kind) {
3746 case OMPC_read:
3747 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3748 break;
3749 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003750 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3751 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003752 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003753 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003754 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3755 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003756 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003757 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3758 IsXLHSInRHSPart, Loc);
3759 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003760 case OMPC_if:
3761 case OMPC_final:
3762 case OMPC_num_threads:
3763 case OMPC_private:
3764 case OMPC_firstprivate:
3765 case OMPC_lastprivate:
3766 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003767 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003768 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003769 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003770 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003771 case OMPC_collapse:
3772 case OMPC_default:
3773 case OMPC_seq_cst:
3774 case OMPC_shared:
3775 case OMPC_linear:
3776 case OMPC_aligned:
3777 case OMPC_copyin:
3778 case OMPC_copyprivate:
3779 case OMPC_flush:
3780 case OMPC_proc_bind:
3781 case OMPC_schedule:
3782 case OMPC_ordered:
3783 case OMPC_nowait:
3784 case OMPC_untied:
3785 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003786 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003787 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003788 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003789 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003790 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003791 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003792 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003793 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003794 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003795 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003796 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003797 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003798 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003799 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003800 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003801 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003802 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003803 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003804 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003805 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003806 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3807 }
3808}
3809
3810void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003811 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003812 OpenMPClauseKind Kind = OMPC_unknown;
3813 for (auto *C : S.clauses()) {
3814 // Find first clause (skip seq_cst clause, if it is first).
3815 if (C->getClauseKind() != OMPC_seq_cst) {
3816 Kind = C->getClauseKind();
3817 break;
3818 }
3819 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003820
3821 const auto *CS =
3822 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003823 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003824 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003825 }
3826 // Processing for statements under 'atomic capture'.
3827 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3828 for (const auto *C : Compound->body()) {
3829 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3830 enterFullExpression(EWC);
3831 }
3832 }
3833 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003834
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003835 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3836 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003837 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003838 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3839 S.getV(), S.getExpr(), S.getUpdateExpr(),
3840 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003841 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003842 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003843 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003844}
3845
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003846static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3847 const OMPExecutableDirective &S,
3848 const RegionCodeGenTy &CodeGen) {
3849 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3850 CodeGenModule &CGM = CGF.CGM;
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00003851 const CapturedStmt &CS = *S.getCapturedStmt(OMPD_target);
Samuel Antaobed3c462015-10-02 16:14:20 +00003852
Samuel Antaoee8fb302016-01-06 13:42:12 +00003853 llvm::Function *Fn = nullptr;
3854 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003855
Samuel Antaobed3c462015-10-02 16:14:20 +00003856 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003857 // Check for the at most one if clause associated with the target region.
3858 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3859 if (C->getNameModifier() == OMPD_unknown ||
3860 C->getNameModifier() == OMPD_target) {
3861 IfCond = C->getCondition();
3862 break;
3863 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003864 }
3865
3866 // Check if we have any device clause associated with the directive.
3867 const Expr *Device = nullptr;
3868 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3869 Device = C->getDevice();
3870 }
3871
Samuel Antaoee8fb302016-01-06 13:42:12 +00003872 // Check if we have an if clause whose conditional always evaluates to false
3873 // or if we do not have any targets specified. If so the target region is not
3874 // an offload entry point.
3875 bool IsOffloadEntry = true;
3876 if (IfCond) {
3877 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003878 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003879 IsOffloadEntry = false;
3880 }
3881 if (CGM.getLangOpts().OMPTargetTriples.empty())
3882 IsOffloadEntry = false;
3883
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003884 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003885 StringRef ParentName;
3886 // In case we have Ctors/Dtors we use the complete type variant to produce
3887 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003888 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003889 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003890 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003891 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3892 else
3893 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003894 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003895
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003896 // Emit target region as a standalone region.
3897 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3898 IsOffloadEntry, CodeGen);
3899 OMPLexicalScope Scope(CGF, S);
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003900 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3901 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003902 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003903 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003904}
3905
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003906static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3907 PrePostActionTy &Action) {
3908 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3909 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3910 CGF.EmitOMPPrivateClause(S, PrivateScope);
3911 (void)PrivateScope.Privatize();
3912
3913 Action.Enter(CGF);
3914 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3915}
3916
3917void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3918 StringRef ParentName,
3919 const OMPTargetDirective &S) {
3920 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3921 emitTargetRegion(CGF, S, Action);
3922 };
3923 llvm::Function *Fn;
3924 llvm::Constant *Addr;
3925 // Emit target region as a standalone region.
3926 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3927 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3928 assert(Fn && Addr && "Target device function emission failed.");
3929}
3930
3931void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3932 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3933 emitTargetRegion(CGF, S, Action);
3934 };
3935 emitCommonOMPTargetDirective(*this, S, CodeGen);
3936}
3937
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003938static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3939 const OMPExecutableDirective &S,
3940 OpenMPDirectiveKind InnermostKind,
3941 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003942 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
3943 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
3944 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003945
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003946 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
3947 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003948 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003949 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3950 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003951
Carlo Bertollic6872252016-04-04 15:55:02 +00003952 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3953 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003954 }
3955
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003956 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003957 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3958 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003959 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3960 CapturedVars);
3961}
3962
3963void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00003964 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003965 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003966 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003967 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3968 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003969 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003970 (void)PrivateScope.Privatize();
3971 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003972 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003973 };
Alexey Bataev2139ed62017-11-16 18:20:21 +00003974 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003975 emitPostUpdateForReductionClause(
3976 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00003977}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003978
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003979static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
3980 const OMPTargetTeamsDirective &S) {
3981 auto *CS = S.getCapturedStmt(OMPD_teams);
3982 Action.Enter(CGF);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00003983 // Emit teams region as a standalone region.
3984 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
3985 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3986 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3987 CGF.EmitOMPPrivateClause(S, PrivateScope);
3988 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3989 (void)PrivateScope.Privatize();
3990 Action.Enter(CGF);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003991 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00003992 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003993 };
3994 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00003995 emitPostUpdateForReductionClause(
3996 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003997}
3998
3999void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4000 CodeGenModule &CGM, StringRef ParentName,
4001 const OMPTargetTeamsDirective &S) {
4002 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4003 emitTargetTeamsRegion(CGF, Action, S);
4004 };
4005 llvm::Function *Fn;
4006 llvm::Constant *Addr;
4007 // Emit target region as a standalone region.
4008 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4009 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4010 assert(Fn && Addr && "Target device function emission failed.");
4011}
4012
4013void CodeGenFunction::EmitOMPTargetTeamsDirective(
4014 const OMPTargetTeamsDirective &S) {
4015 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4016 emitTargetTeamsRegion(CGF, Action, S);
4017 };
4018 emitCommonOMPTargetDirective(*this, S, CodeGen);
4019}
4020
Alexey Bataevdfa430f2017-12-08 15:03:50 +00004021static void
4022emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4023 const OMPTargetTeamsDistributeDirective &S) {
4024 Action.Enter(CGF);
4025 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4026 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4027 };
4028
4029 // Emit teams region as a standalone region.
4030 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4031 PrePostActionTy &) {
4032 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4033 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4034 (void)PrivateScope.Privatize();
4035 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4036 CodeGenDistribute);
4037 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4038 };
4039 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4040 emitPostUpdateForReductionClause(CGF, S,
4041 [](CodeGenFunction &) { return nullptr; });
4042}
4043
4044void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4045 CodeGenModule &CGM, StringRef ParentName,
4046 const OMPTargetTeamsDistributeDirective &S) {
4047 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4048 emitTargetTeamsDistributeRegion(CGF, Action, S);
4049 };
4050 llvm::Function *Fn;
4051 llvm::Constant *Addr;
4052 // Emit target region as a standalone region.
4053 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4054 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4055 assert(Fn && Addr && "Target device function emission failed.");
4056}
4057
4058void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4059 const OMPTargetTeamsDistributeDirective &S) {
4060 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4061 emitTargetTeamsDistributeRegion(CGF, Action, S);
4062 };
4063 emitCommonOMPTargetDirective(*this, S, CodeGen);
4064}
4065
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00004066static void emitTargetTeamsDistributeSimdRegion(
4067 CodeGenFunction &CGF, PrePostActionTy &Action,
4068 const OMPTargetTeamsDistributeSimdDirective &S) {
4069 Action.Enter(CGF);
4070 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4071 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4072 };
4073
4074 // Emit teams region as a standalone region.
4075 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4076 PrePostActionTy &) {
4077 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4078 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4079 (void)PrivateScope.Privatize();
4080 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4081 CodeGenDistribute);
4082 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4083 };
4084 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4085 emitPostUpdateForReductionClause(CGF, S,
4086 [](CodeGenFunction &) { return nullptr; });
4087}
4088
4089void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4090 CodeGenModule &CGM, StringRef ParentName,
4091 const OMPTargetTeamsDistributeSimdDirective &S) {
4092 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4093 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4094 };
4095 llvm::Function *Fn;
4096 llvm::Constant *Addr;
4097 // Emit target region as a standalone region.
4098 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4099 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4100 assert(Fn && Addr && "Target device function emission failed.");
4101}
4102
4103void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4104 const OMPTargetTeamsDistributeSimdDirective &S) {
4105 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4106 emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4107 };
4108 emitCommonOMPTargetDirective(*this, S, CodeGen);
4109}
4110
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004111void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4112 const OMPTeamsDistributeDirective &S) {
4113
4114 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4115 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4116 };
4117
4118 // Emit teams region as a standalone region.
4119 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4120 PrePostActionTy &) {
4121 OMPPrivateScope PrivateScope(CGF);
4122 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4123 (void)PrivateScope.Privatize();
4124 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4125 CodeGenDistribute);
4126 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4127 };
Alexey Bataev95c6dd42017-11-29 15:14:16 +00004128 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
Carlo Bertolliba1487b2017-10-04 14:12:09 +00004129 emitPostUpdateForReductionClause(*this, S,
4130 [](CodeGenFunction &) { return nullptr; });
4131}
4132
Alexey Bataev999277a2017-12-06 14:31:09 +00004133void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4134 const OMPTeamsDistributeSimdDirective &S) {
4135 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4136 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4137 };
4138
4139 // Emit teams region as a standalone region.
4140 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4141 PrePostActionTy &) {
4142 OMPPrivateScope PrivateScope(CGF);
4143 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4144 (void)PrivateScope.Privatize();
4145 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4146 CodeGenDistribute);
4147 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4148 };
4149 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4150 emitPostUpdateForReductionClause(*this, S,
4151 [](CodeGenFunction &) { return nullptr; });
4152}
4153
Carlo Bertolli62fae152017-11-20 20:46:39 +00004154void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4155 const OMPTeamsDistributeParallelForDirective &S) {
4156 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4157 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4158 S.getDistInc());
4159 };
4160
4161 // Emit teams region as a standalone region.
4162 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4163 PrePostActionTy &) {
4164 OMPPrivateScope PrivateScope(CGF);
4165 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4166 (void)PrivateScope.Privatize();
Alexey Bataev10a54312017-11-27 16:54:08 +00004167 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4168 CodeGenDistribute);
Carlo Bertolli62fae152017-11-20 20:46:39 +00004169 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4170 };
4171 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4172 emitPostUpdateForReductionClause(*this, S,
4173 [](CodeGenFunction &) { return nullptr; });
4174}
4175
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00004176void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4177 const OMPTeamsDistributeParallelForSimdDirective &S) {
4178 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4179 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4180 S.getDistInc());
4181 };
4182
4183 // Emit teams region as a standalone region.
4184 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4185 PrePostActionTy &) {
4186 OMPPrivateScope PrivateScope(CGF);
4187 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4188 (void)PrivateScope.Privatize();
4189 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4190 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4191 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4192 };
4193 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4194 emitPostUpdateForReductionClause(*this, S,
4195 [](CodeGenFunction &) { return nullptr; });
4196}
4197
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004198void CodeGenFunction::EmitOMPCancellationPointDirective(
4199 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00004200 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
4201 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004202}
4203
Alexey Bataev80909872015-07-02 11:25:17 +00004204void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004205 const Expr *IfCond = nullptr;
4206 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4207 if (C->getNameModifier() == OMPD_unknown ||
4208 C->getNameModifier() == OMPD_cancel) {
4209 IfCond = C->getCondition();
4210 break;
4211 }
4212 }
4213 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004214 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00004215}
4216
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004217CodeGenFunction::JumpDest
4218CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00004219 if (Kind == OMPD_parallel || Kind == OMPD_task ||
4220 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004221 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004222 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00004223 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
4224 Kind == OMPD_distribute_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004225 Kind == OMPD_target_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004226 Kind == OMPD_teams_distribute_parallel_for ||
4227 Kind == OMPD_target_teams_distribute_parallel_for);
Alexey Bataev957d8562016-11-17 15:12:05 +00004228 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004229}
Michael Wong65f367f2015-07-21 13:44:28 +00004230
Samuel Antaocc10b852016-07-28 14:23:26 +00004231void CodeGenFunction::EmitOMPUseDevicePtrClause(
4232 const OMPClause &NC, OMPPrivateScope &PrivateScope,
4233 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
4234 const auto &C = cast<OMPUseDevicePtrClause>(NC);
4235 auto OrigVarIt = C.varlist_begin();
4236 auto InitIt = C.inits().begin();
4237 for (auto PvtVarIt : C.private_copies()) {
4238 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
4239 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
4240 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
4241
4242 // In order to identify the right initializer we need to match the
4243 // declaration used by the mapping logic. In some cases we may get
4244 // OMPCapturedExprDecl that refers to the original declaration.
4245 const ValueDecl *MatchingVD = OrigVD;
4246 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
4247 // OMPCapturedExprDecl are used to privative fields of the current
4248 // structure.
4249 auto *ME = cast<MemberExpr>(OED->getInit());
4250 assert(isa<CXXThisExpr>(ME->getBase()) &&
4251 "Base should be the current struct!");
4252 MatchingVD = ME->getMemberDecl();
4253 }
4254
4255 // If we don't have information about the current list item, move on to
4256 // the next one.
4257 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
4258 if (InitAddrIt == CaptureDeviceAddrMap.end())
4259 continue;
4260
4261 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
4262 // Initialize the temporary initialization variable with the address we
4263 // get from the runtime library. We have to cast the source address
4264 // because it is always a void *. References are materialized in the
4265 // privatization scope, so the initialization here disregards the fact
4266 // the original variable is a reference.
4267 QualType AddrQTy =
4268 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
4269 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
4270 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
4271 setAddrOfLocalVar(InitVD, InitAddr);
4272
4273 // Emit private declaration, it will be initialized by the value we
4274 // declaration we just added to the local declarations map.
4275 EmitDecl(*PvtVD);
4276
4277 // The initialization variables reached its purpose in the emission
4278 // ofthe previous declaration, so we don't need it anymore.
4279 LocalDeclMap.erase(InitVD);
4280
4281 // Return the address of the private variable.
4282 return GetAddrOfLocalVar(PvtVD);
4283 });
4284 assert(IsRegistered && "firstprivate var already registered as private");
4285 // Silence the warning about unused variable.
4286 (void)IsRegistered;
4287
4288 ++OrigVarIt;
4289 ++InitIt;
4290 }
4291}
4292
Michael Wong65f367f2015-07-21 13:44:28 +00004293// Generate the instructions for '#pragma omp target data' directive.
4294void CodeGenFunction::EmitOMPTargetDataDirective(
4295 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004296 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4297
4298 // Create a pre/post action to signal the privatization of the device pointer.
4299 // This action can be replaced by the OpenMP runtime code generation to
4300 // deactivate privatization.
4301 bool PrivatizeDevicePointers = false;
4302 class DevicePointerPrivActionTy : public PrePostActionTy {
4303 bool &PrivatizeDevicePointers;
4304
4305 public:
4306 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4307 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4308 void Enter(CodeGenFunction &CGF) override {
4309 PrivatizeDevicePointers = true;
4310 }
Samuel Antaodf158d52016-04-27 22:58:19 +00004311 };
Samuel Antaocc10b852016-07-28 14:23:26 +00004312 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4313
4314 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
4315 CodeGenFunction &CGF, PrePostActionTy &Action) {
4316 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4317 CGF.EmitStmt(
4318 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
4319 };
4320
4321 // Codegen that selects wheather to generate the privatization code or not.
4322 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4323 &InnermostCodeGen](CodeGenFunction &CGF,
4324 PrePostActionTy &Action) {
4325 RegionCodeGenTy RCG(InnermostCodeGen);
4326 PrivatizeDevicePointers = false;
4327
4328 // Call the pre-action to change the status of PrivatizeDevicePointers if
4329 // needed.
4330 Action.Enter(CGF);
4331
4332 if (PrivatizeDevicePointers) {
4333 OMPPrivateScope PrivateScope(CGF);
4334 // Emit all instances of the use_device_ptr clause.
4335 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4336 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4337 Info.CaptureDeviceAddrMap);
4338 (void)PrivateScope.Privatize();
4339 RCG(CGF);
4340 } else
4341 RCG(CGF);
4342 };
4343
4344 // Forward the provided action to the privatization codegen.
4345 RegionCodeGenTy PrivRCG(PrivCodeGen);
4346 PrivRCG.setAction(Action);
4347
4348 // Notwithstanding the body of the region is emitted as inlined directive,
4349 // we don't use an inline scope as changes in the references inside the
4350 // region are expected to be visible outside, so we do not privative them.
4351 OMPLexicalScope Scope(CGF, S);
4352 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4353 PrivRCG);
4354 };
4355
4356 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004357
4358 // If we don't have target devices, don't bother emitting the data mapping
4359 // code.
4360 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004361 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004362 return;
4363 }
4364
4365 // Check if we have any if clause associated with the directive.
4366 const Expr *IfCond = nullptr;
4367 if (auto *C = S.getSingleClause<OMPIfClause>())
4368 IfCond = C->getCondition();
4369
4370 // Check if we have any device clause associated with the directive.
4371 const Expr *Device = nullptr;
4372 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4373 Device = C->getDevice();
4374
Samuel Antaocc10b852016-07-28 14:23:26 +00004375 // Set the action to signal privatization of device pointers.
4376 RCG.setAction(PrivAction);
4377
4378 // Emit region code.
4379 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4380 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004381}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004382
Samuel Antaodf67fc42016-01-19 19:15:56 +00004383void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4384 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004385 // If we don't have target devices, don't bother emitting the data mapping
4386 // code.
4387 if (CGM.getLangOpts().OMPTargetTriples.empty())
4388 return;
4389
4390 // Check if we have any if clause associated with the directive.
4391 const Expr *IfCond = nullptr;
4392 if (auto *C = S.getSingleClause<OMPIfClause>())
4393 IfCond = C->getCondition();
4394
4395 // Check if we have any device clause associated with the directive.
4396 const Expr *Device = nullptr;
4397 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4398 Device = C->getDevice();
4399
Alexey Bataev7828b252017-11-21 17:08:48 +00004400 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004401 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004402}
4403
Samuel Antao72590762016-01-19 20:04:50 +00004404void CodeGenFunction::EmitOMPTargetExitDataDirective(
4405 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004406 // If we don't have target devices, don't bother emitting the data mapping
4407 // code.
4408 if (CGM.getLangOpts().OMPTargetTriples.empty())
4409 return;
4410
4411 // Check if we have any if clause associated with the directive.
4412 const Expr *IfCond = nullptr;
4413 if (auto *C = S.getSingleClause<OMPIfClause>())
4414 IfCond = C->getCondition();
4415
4416 // Check if we have any device clause associated with the directive.
4417 const Expr *Device = nullptr;
4418 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4419 Device = C->getDevice();
4420
Alexey Bataev7828b252017-11-21 17:08:48 +00004421 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004422 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004423}
4424
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004425static void emitTargetParallelRegion(CodeGenFunction &CGF,
4426 const OMPTargetParallelDirective &S,
4427 PrePostActionTy &Action) {
4428 // Get the captured statement associated with the 'parallel' region.
4429 auto *CS = S.getCapturedStmt(OMPD_parallel);
4430 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004431 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
4432 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4433 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4434 CGF.EmitOMPPrivateClause(S, PrivateScope);
4435 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4436 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004437 // TODO: Add support for clauses.
4438 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004439 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004440 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004441 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4442 emitEmptyBoundParameters);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004443 emitPostUpdateForReductionClause(
4444 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004445}
4446
4447void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4448 CodeGenModule &CGM, StringRef ParentName,
4449 const OMPTargetParallelDirective &S) {
4450 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4451 emitTargetParallelRegion(CGF, S, Action);
4452 };
4453 llvm::Function *Fn;
4454 llvm::Constant *Addr;
4455 // Emit target region as a standalone region.
4456 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4457 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4458 assert(Fn && Addr && "Target device function emission failed.");
4459}
4460
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004461void CodeGenFunction::EmitOMPTargetParallelDirective(
4462 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004463 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4464 emitTargetParallelRegion(CGF, S, Action);
4465 };
4466 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004467}
4468
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004469static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4470 const OMPTargetParallelForDirective &S,
4471 PrePostActionTy &Action) {
4472 Action.Enter(CGF);
4473 // Emit directive as a combined directive that consists of two implicit
4474 // directives: 'parallel' with 'for' directive.
4475 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev2139ed62017-11-16 18:20:21 +00004476 CodeGenFunction::OMPCancelStackRAII CancelRegion(
4477 CGF, OMPD_target_parallel_for, S.hasCancel());
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004478 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4479 emitDispatchForLoopBounds);
4480 };
4481 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4482 emitEmptyBoundParameters);
4483}
4484
4485void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4486 CodeGenModule &CGM, StringRef ParentName,
4487 const OMPTargetParallelForDirective &S) {
4488 // Emit SPMD target parallel for region as a standalone region.
4489 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4490 emitTargetParallelForRegion(CGF, S, Action);
4491 };
4492 llvm::Function *Fn;
4493 llvm::Constant *Addr;
4494 // Emit target region as a standalone region.
4495 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4496 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4497 assert(Fn && Addr && "Target device function emission failed.");
4498}
4499
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004500void CodeGenFunction::EmitOMPTargetParallelForDirective(
4501 const OMPTargetParallelForDirective &S) {
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00004502 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4503 emitTargetParallelForRegion(CGF, S, Action);
4504 };
4505 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004506}
4507
Alexey Bataev5d7edca2017-11-09 17:32:15 +00004508static void
4509emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4510 const OMPTargetParallelForSimdDirective &S,
4511 PrePostActionTy &Action) {
4512 Action.Enter(CGF);
4513 // Emit directive as a combined directive that consists of two implicit
4514 // directives: 'parallel' with 'for' directive.
4515 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4516 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4517 emitDispatchForLoopBounds);
4518 };
4519 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4520 emitEmptyBoundParameters);
4521}
4522
4523void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4524 CodeGenModule &CGM, StringRef ParentName,
4525 const OMPTargetParallelForSimdDirective &S) {
4526 // Emit SPMD target parallel for region as a standalone region.
4527 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4528 emitTargetParallelForSimdRegion(CGF, S, Action);
4529 };
4530 llvm::Function *Fn;
4531 llvm::Constant *Addr;
4532 // Emit target region as a standalone region.
4533 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4534 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4535 assert(Fn && Addr && "Target device function emission failed.");
4536}
4537
4538void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4539 const OMPTargetParallelForSimdDirective &S) {
4540 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4541 emitTargetParallelForSimdRegion(CGF, S, Action);
4542 };
4543 emitCommonOMPTargetDirective(*this, S, CodeGen);
4544}
4545
Alexey Bataev7292c292016-04-25 12:22:29 +00004546/// Emit a helper variable and return corresponding lvalue.
4547static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4548 const ImplicitParamDecl *PVD,
4549 CodeGenFunction::OMPPrivateScope &Privates) {
4550 auto *VDecl = cast<VarDecl>(Helper->getDecl());
4551 Privates.addPrivate(
4552 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
4553}
4554
4555void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4556 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4557 // Emit outlined function for task construct.
4558 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
4559 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
4560 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4561 const Expr *IfCond = nullptr;
4562 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4563 if (C->getNameModifier() == OMPD_unknown ||
4564 C->getNameModifier() == OMPD_taskloop) {
4565 IfCond = C->getCondition();
4566 break;
4567 }
4568 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004569
4570 OMPTaskDataTy Data;
4571 // Check if taskloop must be emitted without taskgroup.
4572 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004573 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004574 Data.Tied = true;
4575 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004576 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4577 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004578 Data.Schedule.setInt(/*IntVal=*/false);
4579 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004580 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4581 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004582 Data.Schedule.setInt(/*IntVal=*/true);
4583 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004584 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004585
4586 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4587 // if (PreCond) {
4588 // for (IV in 0..LastIteration) BODY;
4589 // <Final counter/linear vars updates>;
4590 // }
4591 //
4592
4593 // Emit: if (PreCond) - begin.
4594 // If the condition constant folds and can be elided, avoid emitting the
4595 // whole loop.
4596 bool CondConstant;
4597 llvm::BasicBlock *ContBlock = nullptr;
4598 OMPLoopScope PreInitScope(CGF, S);
4599 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4600 if (!CondConstant)
4601 return;
4602 } else {
4603 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4604 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4605 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4606 CGF.getProfileCount(&S));
4607 CGF.EmitBlock(ThenBlock);
4608 CGF.incrementProfileCounter(&S);
4609 }
4610
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004611 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4612 CGF.EmitOMPSimdInit(S);
4613
Alexey Bataev7292c292016-04-25 12:22:29 +00004614 OMPPrivateScope LoopScope(CGF);
4615 // Emit helper vars inits.
4616 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4617 auto *I = CS->getCapturedDecl()->param_begin();
4618 auto *LBP = std::next(I, LowerBound);
4619 auto *UBP = std::next(I, UpperBound);
4620 auto *STP = std::next(I, Stride);
4621 auto *LIP = std::next(I, LastIter);
4622 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4623 LoopScope);
4624 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4625 LoopScope);
4626 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4627 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4628 LoopScope);
4629 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004630 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004631 (void)LoopScope.Privatize();
4632 // Emit the loop iteration variable.
4633 const Expr *IVExpr = S.getIterationVariable();
4634 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4635 CGF.EmitVarDecl(*IVDecl);
4636 CGF.EmitIgnoredExpr(S.getInit());
4637
4638 // Emit the iterations count variable.
4639 // If it is not a variable, Sema decided to calculate iterations count on
4640 // each iteration (e.g., it is foldable into a constant).
4641 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4642 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4643 // Emit calculation of the iterations count.
4644 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4645 }
4646
4647 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4648 S.getInc(),
4649 [&S](CodeGenFunction &CGF) {
4650 CGF.EmitOMPLoopBody(S, JumpDest());
4651 CGF.EmitStopPoint(&S);
4652 },
4653 [](CodeGenFunction &) {});
4654 // Emit: if (PreCond) - end.
4655 if (ContBlock) {
4656 CGF.EmitBranch(ContBlock);
4657 CGF.EmitBlock(ContBlock, true);
4658 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004659 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4660 if (HasLastprivateClause) {
4661 CGF.EmitOMPLastprivateClauseFinal(
4662 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4663 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4664 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4665 (*LIP)->getType(), S.getLocStart())));
4666 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004667 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004668 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4669 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4670 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004671 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4672 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004673 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4674 OutlinedFn, SharedsTy,
4675 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004676 };
4677 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4678 CodeGen);
4679 };
Alexey Bataev33446032017-07-12 18:09:32 +00004680 if (Data.Nogroup)
4681 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4682 else {
4683 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4684 *this,
4685 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4686 PrePostActionTy &Action) {
4687 Action.Enter(CGF);
4688 CGF.EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4689 },
4690 S.getLocStart());
4691 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004692}
4693
Alexey Bataev49f6e782015-12-01 04:18:41 +00004694void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004695 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004696}
4697
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004698void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4699 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004700 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004701}
Samuel Antao686c70c2016-05-26 17:30:50 +00004702
4703// Generate the instructions for '#pragma omp target update' directive.
4704void CodeGenFunction::EmitOMPTargetUpdateDirective(
4705 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00004706 // If we don't have target devices, don't bother emitting the data mapping
4707 // code.
4708 if (CGM.getLangOpts().OMPTargetTriples.empty())
4709 return;
4710
4711 // Check if we have any if clause associated with the directive.
4712 const Expr *IfCond = nullptr;
4713 if (auto *C = S.getSingleClause<OMPIfClause>())
4714 IfCond = C->getCondition();
4715
4716 // Check if we have any device clause associated with the directive.
4717 const Expr *Device = nullptr;
4718 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4719 Device = C->getDevice();
4720
Alexey Bataev7828b252017-11-21 17:08:48 +00004721 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004722 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00004723}