blob: 54d381798c63bd9fe7d93fbb69f80e0225f68ecb [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit OpenMP nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Alexey Bataev3392d762016-02-16 11:18:12 +000014#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "CGOpenMPRuntime.h"
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000018#include "TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Stmt.h"
20#include "clang/AST/StmtOpenMP.h"
Alexey Bataev2bbf7212016-03-03 03:52:24 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000022#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023using namespace clang;
24using namespace CodeGen;
25
Alexey Bataev3392d762016-02-16 11:18:12 +000026namespace {
27/// Lexical scope for OpenMP executable constructs, that handles correct codegen
28/// for captured expressions.
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000029class OMPLexicalScope : public CodeGenFunction::LexicalScope {
Alexey Bataev3392d762016-02-16 11:18:12 +000030 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
31 for (const auto *C : S.clauses()) {
32 if (auto *CPI = OMPClauseWithPreInit::get(C)) {
33 if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +000034 for (const auto *I : PreInit->decls()) {
35 if (!I->hasAttr<OMPCaptureNoInitAttr>())
36 CGF.EmitVarDecl(cast<VarDecl>(*I));
37 else {
38 CodeGenFunction::AutoVarEmission Emission =
39 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
40 CGF.EmitAutoVarCleanups(Emission);
41 }
42 }
Alexey Bataev3392d762016-02-16 11:18:12 +000043 }
44 }
45 }
46 }
Alexey Bataev4ba78a42016-04-27 07:56:03 +000047 CodeGenFunction::OMPPrivateScope InlinedShareds;
48
49 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
50 return CGF.LambdaCaptureFields.lookup(VD) ||
51 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
52 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
53 }
Alexey Bataev3392d762016-02-16 11:18:12 +000054
Alexey Bataev3392d762016-02-16 11:18:12 +000055public:
Alexey Bataev4ba78a42016-04-27 07:56:03 +000056 OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S,
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000057 bool AsInlined = false, bool EmitPreInitStmt = true)
Alexey Bataev4ba78a42016-04-27 07:56:03 +000058 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
59 InlinedShareds(CGF) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000060 if (EmitPreInitStmt)
61 emitPreInitStmt(CGF, S);
Alexey Bataev4ba78a42016-04-27 07:56:03 +000062 if (AsInlined) {
63 if (S.hasAssociatedStmt()) {
64 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
65 for (auto &C : CS->captures()) {
66 if (C.capturesVariable() || C.capturesVariableByCopy()) {
67 auto *VD = C.getCapturedVar();
68 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
69 isCapturedVar(CGF, VD) ||
70 (CGF.CapturedStmtInfo &&
71 InlinedShareds.isGlobalVarCaptured(VD)),
72 VD->getType().getNonReferenceType(), VK_LValue,
73 SourceLocation());
74 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
75 return CGF.EmitLValue(&DRE).getAddress();
76 });
77 }
78 }
79 (void)InlinedShareds.Privatize();
80 }
81 }
Alexey Bataev3392d762016-02-16 11:18:12 +000082 }
83};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000084
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000085/// Lexical scope for OpenMP parallel construct, that handles correct codegen
86/// for captured expressions.
87class OMPParallelScope final : public OMPLexicalScope {
88 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
89 OpenMPDirectiveKind Kind = S.getDirectiveKind();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +000090 return !(isOpenMPTargetExecutionDirective(Kind) ||
91 isOpenMPLoopBoundSharingDirective(Kind)) &&
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000092 isOpenMPParallelDirective(Kind);
93 }
94
95public:
96 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
97 : OMPLexicalScope(CGF, S,
98 /*AsInlined=*/false,
99 /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
100};
101
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000102/// Lexical scope for OpenMP teams construct, that handles correct codegen
103/// for captured expressions.
104class OMPTeamsScope final : public OMPLexicalScope {
105 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
106 OpenMPDirectiveKind Kind = S.getDirectiveKind();
107 return !isOpenMPTargetExecutionDirective(Kind) &&
108 isOpenMPTeamsDirective(Kind);
109 }
110
111public:
112 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
113 : OMPLexicalScope(CGF, S,
114 /*AsInlined=*/false,
115 /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
116};
117
Alexey Bataev5a3af132016-03-29 08:58:54 +0000118/// Private scope for OpenMP loop-based directives, that supports capturing
119/// of used expression from loop statement.
120class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
121 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
122 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
123 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
124 for (const auto *I : PreInits->decls())
125 CGF.EmitVarDecl(cast<VarDecl>(*I));
126 }
127 }
128 }
129
130public:
131 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
132 : CodeGenFunction::RunCleanupsScope(CGF) {
133 emitPreInitStmt(CGF, S);
134 }
135};
136
Alexey Bataev3392d762016-02-16 11:18:12 +0000137} // namespace
138
Alexey Bataev1189bd02016-01-26 12:20:39 +0000139llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
140 auto &C = getContext();
141 llvm::Value *Size = nullptr;
142 auto SizeInChars = C.getTypeSizeInChars(Ty);
143 if (SizeInChars.isZero()) {
144 // getTypeSizeInChars() returns 0 for a VLA.
145 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
146 llvm::Value *ArraySize;
147 std::tie(ArraySize, Ty) = getVLASize(VAT);
148 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
149 }
150 SizeInChars = C.getTypeSizeInChars(Ty);
151 if (SizeInChars.isZero())
152 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
153 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
154 } else
155 Size = CGM.getSize(SizeInChars);
156 return Size;
157}
158
Alexey Bataev2377fe92015-09-10 08:12:02 +0000159void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000160 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000161 const RecordDecl *RD = S.getCapturedRecordDecl();
162 auto CurField = RD->field_begin();
163 auto CurCap = S.captures().begin();
164 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
165 E = S.capture_init_end();
166 I != E; ++I, ++CurField, ++CurCap) {
167 if (CurField->hasCapturedVLAType()) {
168 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000169 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000170 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000171 } else if (CurCap->capturesThis())
172 CapturedVars.push_back(CXXThisValue);
Samuel Antao6d004262016-06-16 18:39:34 +0000173 else if (CurCap->capturesVariableByCopy()) {
174 llvm::Value *CV =
175 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal();
176
177 // If the field is not a pointer, we need to save the actual value
178 // and load it as a void pointer.
179 if (!CurField->getType()->isAnyPointerType()) {
180 auto &Ctx = getContext();
181 auto DstAddr = CreateMemTemp(
182 Ctx.getUIntPtrType(),
183 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
184 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
185
186 auto *SrcAddrVal = EmitScalarConversion(
187 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
188 Ctx.getPointerType(CurField->getType()), SourceLocation());
189 LValue SrcLV =
190 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
191
192 // Store the value using the source type pointer.
193 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
194
195 // Load the value using the destination type pointer.
196 CV = EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
197 }
198 CapturedVars.push_back(CV);
199 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000200 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000201 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000202 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000203 }
204}
205
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000206static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
207 StringRef Name, LValue AddrLV,
208 bool isReferenceType = false) {
209 ASTContext &Ctx = CGF.getContext();
210
211 auto *CastedPtr = CGF.EmitScalarConversion(
212 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
213 Ctx.getPointerType(DstType), SourceLocation());
214 auto TmpAddr =
215 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
216 .getAddress();
217
218 // If we are dealing with references we need to return the address of the
219 // reference instead of the reference of the value.
220 if (isReferenceType) {
221 QualType RefType = Ctx.getLValueReferenceType(DstType);
222 auto *RefVal = TmpAddr.getPointer();
223 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
224 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
Akira Hatanaka642f7992016-10-18 19:05:41 +0000225 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000226 }
227
228 return TmpAddr;
229}
230
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000231static QualType getCanonicalParamType(ASTContext &C, QualType T) {
232 if (T->isLValueReferenceType()) {
233 return C.getLValueReferenceType(
234 getCanonicalParamType(C, T.getNonReferenceType()),
235 /*SpelledAsLValue=*/false);
236 }
237 if (T->isPointerType())
238 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
239 return C.getCanonicalParamType(T);
240}
241
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000242namespace {
243 /// Contains required data for proper outlined function codegen.
244 struct FunctionOptions {
245 /// Captured statement for which the function is generated.
246 const CapturedStmt *S = nullptr;
247 /// true if cast to/from UIntPtr is required for variables captured by
248 /// value.
249 bool UIntPtrCastRequired = true;
250 /// true if only casted argumefnts must be registered as local args or VLA
251 /// sizes.
252 bool RegisterCastedArgsOnly = false;
253 /// Name of the generated function.
254 StringRef FunctionName;
Alexey Bataevbe83fad2017-08-04 19:46:10 +0000255 /// Function that maps given variable declaration to the specified address.
256 const CGOpenMPRuntime::MappingFnType MapFn;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000257 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
258 bool RegisterCastedArgsOnly,
Alexey Bataevbe83fad2017-08-04 19:46:10 +0000259 StringRef FunctionName,
260 const CGOpenMPRuntime::MappingFnType MapFn)
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000261 : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
262 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
Alexey Bataevbe83fad2017-08-04 19:46:10 +0000263 FunctionName(FunctionName), MapFn(MapFn) {}
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000264 };
265}
266
267static std::pair<llvm::Function *, bool> emitOutlinedFunctionPrologue(
268 CodeGenFunction &CGF, FunctionArgList &Args,
269 llvm::DenseMap<const Decl *, std::pair<const VarDecl *, Address>>
270 &LocalAddrs,
271 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
272 &VLASizes,
273 llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
274 const CapturedDecl *CD = FO.S->getCapturedDecl();
275 const RecordDecl *RD = FO.S->getCapturedRecordDecl();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000276 assert(CD->hasBody() && "missing CapturedDecl body");
277
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000278 CXXThisValue = nullptr;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000279 // Build the argument list.
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000280 CodeGenModule &CGM = CGF.CGM;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000281 ASTContext &Ctx = CGM.getContext();
Alexey Bataevbe83fad2017-08-04 19:46:10 +0000282 FunctionArgList TargetArgs;
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000283 bool HasUIntPtrArgs = false;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000284 Args.append(CD->param_begin(),
285 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataevbe83fad2017-08-04 19:46:10 +0000286 TargetArgs.append(
287 CD->param_begin(),
288 std::next(CD->param_begin(), CD->getContextParamPosition()));
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000289 auto I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000290 for (auto *FD : RD->fields()) {
291 QualType ArgType = FD->getType();
292 IdentifierInfo *II = nullptr;
293 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000294
295 // If this is a capture by copy and the type is not a pointer, the outlined
296 // function argument type should be uintptr and the value properly casted to
297 // uintptr. This is necessary given that the runtime library is only able to
298 // deal with pointers. We can pass in the same way the VLA type sizes to the
299 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000300 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000301 I->capturesVariableArrayType()) {
302 HasUIntPtrArgs = true;
303 if (FO.UIntPtrCastRequired)
304 ArgType = Ctx.getUIntPtrType();
305 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000306
307 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000308 CapVar = I->getCapturedVar();
309 II = CapVar->getIdentifier();
310 } else if (I->capturesThis())
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000311 II = &Ctx.Idents.get("this");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000312 else {
313 assert(I->capturesVariableArrayType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000314 II = &Ctx.Idents.get("vla");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000315 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000316 if (ArgType->isVariablyModifiedType())
317 ArgType = getCanonicalParamType(Ctx, ArgType.getNonReferenceType());
Alexey Bataevbe83fad2017-08-04 19:46:10 +0000318 auto *Arg =
319 ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(), II,
320 ArgType, ImplicitParamDecl::Other);
321 Args.emplace_back(Arg);
322 // Do not cast arguments if we emit function with non-original types.
Alexey Bataeve09a7742017-08-04 20:29:52 +0000323 TargetArgs.emplace_back(CGM.getOpenMPRuntime().translateParameter(FD, Arg));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000324 ++I;
325 }
326 Args.append(
327 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
328 CD->param_end());
Alexey Bataevbe83fad2017-08-04 19:46:10 +0000329 TargetArgs.append(
330 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
331 CD->param_end());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000332
333 // Create the function declaration.
334 FunctionType::ExtInfo ExtInfo;
335 const CGFunctionInfo &FuncInfo =
Alexey Bataevbe83fad2017-08-04 19:46:10 +0000336 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000337 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
338
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000339 llvm::Function *F =
340 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
341 FO.FunctionName, &CGM.getModule());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000342 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
343 if (CD->isNothrow())
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000344 F->setDoesNotThrow();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000345
346 // Generate the function.
Alexey Bataevbe83fad2017-08-04 19:46:10 +0000347 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs, CD->getLocation(),
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000348 CD->getBody()->getLocStart());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000349 unsigned Cnt = CD->getContextParamPosition();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000350 I = FO.S->captures().begin();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000351 for (auto *FD : RD->fields()) {
Alexey Bataevbe83fad2017-08-04 19:46:10 +0000352 // Do not map arguments if we emit function with non-original types.
353 CGM.getOpenMPRuntime().mapParameterAddress(CGF, FD, Args[Cnt],
354 TargetArgs[Cnt], FO.MapFn);
355 Address LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000356 // If we are capturing a pointer by copy we don't need to do anything, just
357 // use the value that we get from the arguments.
358 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000359 const VarDecl *CurVD = I->getCapturedVar();
Samuel Antao403ffd42016-07-27 22:49:49 +0000360 // If the variable is a reference we need to materialize it here.
361 if (CurVD->getType()->isReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000362 Address RefAddr = CGF.CreateMemTemp(
363 CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
364 CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
365 /*Volatile=*/false, CurVD->getType());
Samuel Antao403ffd42016-07-27 22:49:49 +0000366 LocalAddr = RefAddr;
367 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000368 if (!FO.RegisterCastedArgsOnly)
369 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
Richard Trieucc3949d2016-02-18 22:34:54 +0000370 ++Cnt;
371 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000372 continue;
373 }
374
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000375 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
Alexey Bataevbe83fad2017-08-04 19:46:10 +0000376 LValue ArgLVal =
377 CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(), BaseInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000378 if (FD->hasCapturedVLAType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000379 if (FO.UIntPtrCastRequired) {
380 ArgLVal = CGF.MakeAddrLValue(castValueFromUintptr(CGF, FD->getType(),
381 Args[Cnt]->getName(),
382 ArgLVal),
383 FD->getType(), BaseInfo);
384 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000385 auto *ExprArg =
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000386 CGF.EmitLoadOfLValue(ArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000387 auto VAT = FD->getCapturedVLAType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000388 VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000389 } else if (I->capturesVariable()) {
390 auto *Var = I->getCapturedVar();
391 QualType VarTy = Var->getType();
392 Address ArgAddr = ArgLVal.getAddress();
393 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000394 if (ArgLVal.getType()->isLValueReferenceType()) {
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000395 ArgAddr = CGF.EmitLoadOfReference(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000396 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000397 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000398 assert(ArgLVal.getType()->isPointerType());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000399 ArgAddr = CGF.EmitLoadOfPointer(
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000400 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
401 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000402 }
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000403 if (!FO.RegisterCastedArgsOnly) {
404 LocalAddrs.insert(
405 {Args[Cnt],
406 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
407 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000408 } else if (I->capturesVariableByCopy()) {
409 assert(!FD->getType()->isAnyPointerType() &&
410 "Not expecting a captured pointer.");
411 auto *Var = I->getCapturedVar();
412 QualType VarTy = Var->getType();
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000413 LocalAddrs.insert(
414 {Args[Cnt],
415 {Var,
416 FO.UIntPtrCastRequired
417 ? castValueFromUintptr(CGF, FD->getType(), Args[Cnt]->getName(),
418 ArgLVal, VarTy->isReferenceType())
419 : ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000420 } else {
421 // If 'this' is captured, load it into CXXThisValue.
422 assert(I->capturesThis());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000423 CXXThisValue = CGF.EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation())
424 .getScalarVal();
425 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
Alexey Bataev2377fe92015-09-10 08:12:02 +0000426 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000427 ++Cnt;
428 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000429 }
430
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000431 return {F, HasUIntPtrArgs};
432}
433
434llvm::Function *
435CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
436 assert(
437 CapturedStmtInfo &&
438 "CapturedStmtInfo should be set when generating the captured function");
439 const CapturedDecl *CD = S.getCapturedDecl();
440 // Build the argument list.
441 bool NeedWrapperFunction =
442 getDebugInfo() &&
443 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
444 FunctionArgList Args;
445 llvm::DenseMap<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
446 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
Alexey Bataeve09a7742017-08-04 20:29:52 +0000447 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
448 CapturedStmtInfo->getHelperName(),
449 [](CodeGenFunction &CGF, const VarDecl *VD, Address Addr) {
450 CGF.setAddrOfLocalVar(VD, Addr);
451 });
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000452 llvm::Function *F;
453 bool HasUIntPtrArgs;
454 std::tie(F, HasUIntPtrArgs) = emitOutlinedFunctionPrologue(
455 *this, Args, LocalAddrs, VLASizes, CXXThisValue, FO);
456 for (const auto &LocalAddrPair : LocalAddrs) {
457 if (LocalAddrPair.second.first) {
458 setAddrOfLocalVar(LocalAddrPair.second.first,
459 LocalAddrPair.second.second);
460 }
461 }
462 for (const auto &VLASizePair : VLASizes)
463 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
Serge Pavlov3a561452015-12-06 14:32:39 +0000464 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000465 CapturedStmtInfo->EmitBody(*this, CD->getBody());
466 FinishFunction(CD->getBodyRBrace());
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000467 if (!NeedWrapperFunction || !HasUIntPtrArgs)
468 return F;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000469
Alexey Bataev3e660702017-07-31 16:43:06 +0000470 SmallString<256> Buffer;
471 llvm::raw_svector_ostream Out(Buffer);
472 Out << "__nondebug_wrapper_" << CapturedStmtInfo->getHelperName();
Alexey Bataeve09a7742017-08-04 20:29:52 +0000473 FunctionOptions WrapperFO(
474 &S, /*UIntPtrCastRequired=*/true,
475 /*RegisterCastedArgsOnly=*/true, Out.str(),
476 [](CodeGenFunction &CGF, const VarDecl *VD, Address Addr) {
477 CGF.setAddrOfLocalVar(VD, Addr);
478 });
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000479 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
480 WrapperCGF.disableDebugInfo();
481 Args.clear();
482 LocalAddrs.clear();
483 VLASizes.clear();
484 llvm::Function *WrapperF =
485 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
486 WrapperCGF.CXXThisValue, WrapperFO).first;
487 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
488 llvm::SmallVector<llvm::Value *, 4> CallArgs;
489 for (const auto *Arg : Args) {
490 llvm::Value *CallArg;
491 auto I = LocalAddrs.find(Arg);
492 if (I != LocalAddrs.end()) {
493 LValue LV =
494 WrapperCGF.MakeAddrLValue(I->second.second, Arg->getType(), BaseInfo);
495 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
496 } else {
497 auto EI = VLASizes.find(Arg);
498 if (EI != VLASizes.end())
499 CallArg = EI->second.second;
500 else {
501 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
502 Arg->getType(), BaseInfo);
503 CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
504 }
505 }
506 CallArgs.emplace_back(CallArg);
507 }
Alexey Bataev2c7eee52017-08-04 19:10:54 +0000508 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, F, CallArgs);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +0000509 WrapperCGF.FinishFunction();
510 return WrapperF;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000511}
512
Alexey Bataev9959db52014-05-06 10:08:46 +0000513//===----------------------------------------------------------------------===//
514// OpenMP Directive Emission
515//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000516void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000517 Address DestAddr, Address SrcAddr, QualType OriginalType,
518 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000519 // Perform element-by-element initialization.
520 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000521
522 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000523 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000524 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
525 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
526
527 auto SrcBegin = SrcAddr.getPointer();
528 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000529 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000530 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
531 // The basic structure here is a while-do loop.
532 auto BodyBB = createBasicBlock("omp.arraycpy.body");
533 auto DoneBB = createBasicBlock("omp.arraycpy.done");
534 auto IsEmpty =
535 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
536 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000537
Alexey Bataev420d45b2015-04-14 05:11:24 +0000538 // Enter the loop body, making that address the current address.
539 auto EntryBB = Builder.GetInsertBlock();
540 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000541
542 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
543
544 llvm::PHINode *SrcElementPHI =
545 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
546 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
547 Address SrcElementCurrent =
548 Address(SrcElementPHI,
549 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
550
551 llvm::PHINode *DestElementPHI =
552 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
553 DestElementPHI->addIncoming(DestBegin, EntryBB);
554 Address DestElementCurrent =
555 Address(DestElementPHI,
556 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000557
Alexey Bataev420d45b2015-04-14 05:11:24 +0000558 // Emit copy.
559 CopyGen(DestElementCurrent, SrcElementCurrent);
560
561 // Shift the address forward by one element.
562 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000563 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000564 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000565 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000566 // Check whether we've reached the end.
567 auto Done =
568 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
569 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000570 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
571 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000572
573 // Done.
574 EmitBlock(DoneBB, /*IsFinished=*/true);
575}
576
John McCall7f416cc2015-09-08 08:05:57 +0000577void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
578 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000579 const VarDecl *SrcVD, const Expr *Copy) {
580 if (OriginalType->isArrayType()) {
581 auto *BO = dyn_cast<BinaryOperator>(Copy);
582 if (BO && BO->getOpcode() == BO_Assign) {
583 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000584 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000585 } else {
586 // For arrays with complex element types perform element by element
587 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000588 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000589 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000590 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000591 // Working with the single array element, so have to remap
592 // destination and source variables to corresponding array
593 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000594 CodeGenFunction::OMPPrivateScope Remap(*this);
595 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000596 return DestElement;
597 });
598 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000599 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000600 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000601 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000602 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000603 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000604 } else {
605 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000606 CodeGenFunction::OMPPrivateScope Remap(*this);
607 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
608 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000609 (void)Remap.Privatize();
610 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000611 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000612 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000613}
614
Alexey Bataev69c62a92015-04-15 04:52:20 +0000615bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
616 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000617 if (!HaveInsertPoint())
618 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000619 bool FirstprivateIsLastprivate = false;
620 llvm::DenseSet<const VarDecl *> Lastprivates;
621 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
622 for (const auto *D : C->varlists())
623 Lastprivates.insert(
624 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
625 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000626 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000627 CGCapturedStmtInfo CapturesInfo(cast<CapturedStmt>(*D.getAssociatedStmt()));
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000628 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000629 auto IRef = C->varlist_begin();
630 auto InitsRef = C->inits().begin();
631 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000632 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000633 bool ThisFirstprivateIsLastprivate =
634 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000635 auto *CapFD = CapturesInfo.lookup(OrigVD);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000636 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9afe5752016-05-24 07:40:12 +0000637 if (!ThisFirstprivateIsLastprivate && FD && (FD == CapFD) &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000638 !FD->getType()->isReferenceType()) {
639 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
640 ++IRef;
641 ++InitsRef;
642 continue;
643 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000644 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000645 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000646 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000647 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
648 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
649 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000650 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
651 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
652 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000653 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000654 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000655 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000656 // Emit VarDecl with copy init for arrays.
657 // Get the address of the original variable captured in current
658 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000659 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000660 auto Emission = EmitAutoVarAlloca(*VD);
661 auto *Init = VD->getInit();
662 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
663 // Perform simple memcpy.
664 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000665 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000666 } else {
667 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000668 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000669 [this, VDInit, Init](Address DestElement,
670 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000671 // Clean up any temporaries needed by the initialization.
672 RunCleanupsScope InitScope(*this);
673 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000674 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000675 EmitAnyExprToMem(Init, DestElement,
676 Init->getType().getQualifiers(),
677 /*IsInitializer*/ false);
678 LocalDeclMap.erase(VDInit);
679 });
680 }
681 EmitAutoVarCleanups(Emission);
682 return Emission.getAllocatedAddress();
683 });
684 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000685 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000686 // Emit private VarDecl with copy init.
687 // Remap temp VDInit variable to the address of the original
688 // variable
689 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000690 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000691 EmitDecl(*VD);
692 LocalDeclMap.erase(VDInit);
693 return GetAddrOfLocalVar(VD);
694 });
695 }
696 assert(IsRegistered &&
697 "firstprivate var already registered as private");
698 // Silence the warning about unused variable.
699 (void)IsRegistered;
700 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000701 ++IRef;
702 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000703 }
704 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000705 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000706}
707
Alexey Bataev03b340a2014-10-21 03:16:40 +0000708void CodeGenFunction::EmitOMPPrivateClause(
709 const OMPExecutableDirective &D,
710 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000711 if (!HaveInsertPoint())
712 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000713 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000714 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000715 auto IRef = C->varlist_begin();
716 for (auto IInit : C->private_copies()) {
717 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000718 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
719 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
720 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000721 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000722 // Emit private VarDecl with copy init.
723 EmitDecl(*VD);
724 return GetAddrOfLocalVar(VD);
725 });
726 assert(IsRegistered && "private var already registered as private");
727 // Silence the warning about unused variable.
728 (void)IsRegistered;
729 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000730 ++IRef;
731 }
732 }
733}
734
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000735bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000736 if (!HaveInsertPoint())
737 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000738 // threadprivate_var1 = master_threadprivate_var1;
739 // operator=(threadprivate_var2, master_threadprivate_var2);
740 // ...
741 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000742 llvm::DenseSet<const VarDecl *> CopiedVars;
743 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000744 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000745 auto IRef = C->varlist_begin();
746 auto ISrcRef = C->source_exprs().begin();
747 auto IDestRef = C->destination_exprs().begin();
748 for (auto *AssignOp : C->assignment_ops()) {
749 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000750 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000751 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000752 // Get the address of the master variable. If we are emitting code with
753 // TLS support, the address is passed from the master as field in the
754 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000755 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000756 if (getLangOpts().OpenMPUseTLS &&
757 getContext().getTargetInfo().isTLSSupported()) {
758 assert(CapturedStmtInfo->lookup(VD) &&
759 "Copyin threadprivates should have been captured!");
760 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
761 VK_LValue, (*IRef)->getExprLoc());
762 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000763 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000764 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000765 MasterAddr =
766 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
767 : CGM.GetAddrOfGlobal(VD),
768 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000769 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000770 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000771 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000772 if (CopiedVars.size() == 1) {
773 // At first check if current thread is a master thread. If it is, no
774 // need to copy data.
775 CopyBegin = createBasicBlock("copyin.not.master");
776 CopyEnd = createBasicBlock("copyin.not.master.end");
777 Builder.CreateCondBr(
778 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000779 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
780 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000781 CopyBegin, CopyEnd);
782 EmitBlock(CopyBegin);
783 }
784 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
785 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000786 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000787 }
788 ++IRef;
789 ++ISrcRef;
790 ++IDestRef;
791 }
792 }
793 if (CopyEnd) {
794 // Exit out of copying procedure for non-master thread.
795 EmitBlock(CopyEnd, /*IsFinished=*/true);
796 return true;
797 }
798 return false;
799}
800
Alexey Bataev38e89532015-04-16 04:54:05 +0000801bool CodeGenFunction::EmitOMPLastprivateClauseInit(
802 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000803 if (!HaveInsertPoint())
804 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000805 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000806 llvm::DenseSet<const VarDecl *> SIMDLCVs;
807 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
808 auto *LoopDirective = cast<OMPLoopDirective>(&D);
809 for (auto *C : LoopDirective->counters()) {
810 SIMDLCVs.insert(
811 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
812 }
813 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000814 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000815 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000816 HasAtLeastOneLastprivate = true;
Alexey Bataevf93095a2016-05-05 08:46:22 +0000817 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()))
818 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000819 auto IRef = C->varlist_begin();
820 auto IDestRef = C->destination_exprs().begin();
821 for (auto *IInit : C->private_copies()) {
822 // Keep the address of the original variable for future update at the end
823 // of the loop.
824 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000825 // Taskloops do not require additional initialization, it is done in
826 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000827 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
828 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000829 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000830 DeclRefExpr DRE(
831 const_cast<VarDecl *>(OrigVD),
832 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
833 OrigVD) != nullptr,
834 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
835 return EmitLValue(&DRE).getAddress();
836 });
837 // Check if the variable is also a firstprivate: in this case IInit is
838 // not generated. Initialization of this variable will happen in codegen
839 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000840 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000841 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000842 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
843 // Emit private VarDecl with copy init.
844 EmitDecl(*VD);
845 return GetAddrOfLocalVar(VD);
846 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000847 assert(IsRegistered &&
848 "lastprivate var already registered as private");
849 (void)IsRegistered;
850 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000851 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000852 ++IRef;
853 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000854 }
855 }
856 return HasAtLeastOneLastprivate;
857}
858
859void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000860 const OMPExecutableDirective &D, bool NoFinals,
861 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000862 if (!HaveInsertPoint())
863 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000864 // Emit following code:
865 // if (<IsLastIterCond>) {
866 // orig_var1 = private_orig_var1;
867 // ...
868 // orig_varn = private_orig_varn;
869 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000870 llvm::BasicBlock *ThenBB = nullptr;
871 llvm::BasicBlock *DoneBB = nullptr;
872 if (IsLastIterCond) {
873 ThenBB = createBasicBlock(".omp.lastprivate.then");
874 DoneBB = createBasicBlock(".omp.lastprivate.done");
875 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
876 EmitBlock(ThenBB);
877 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000878 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
879 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000880 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000881 auto IC = LoopDirective->counters().begin();
882 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000883 auto *D =
884 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
885 if (NoFinals)
886 AlreadyEmittedVars.insert(D);
887 else
888 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000889 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000890 }
891 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000892 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
893 auto IRef = C->varlist_begin();
894 auto ISrcRef = C->source_exprs().begin();
895 auto IDestRef = C->destination_exprs().begin();
896 for (auto *AssignOp : C->assignment_ops()) {
897 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
898 QualType Type = PrivateVD->getType();
899 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
900 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
901 // If lastprivate variable is a loop control variable for loop-based
902 // directive, update its value before copyin back to original
903 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000904 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
905 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000906 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
907 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
908 // Get the address of the original variable.
909 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
910 // Get the address of the private variable.
911 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
912 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
913 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000914 Address(Builder.CreateLoad(PrivateAddr),
915 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000916 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000917 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000918 ++IRef;
919 ++ISrcRef;
920 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000921 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000922 if (auto *PostUpdate = C->getPostUpdateExpr())
923 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000924 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000925 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000926 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000927}
928
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000929void CodeGenFunction::EmitOMPReductionClauseInit(
930 const OMPExecutableDirective &D,
931 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000932 if (!HaveInsertPoint())
933 return;
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000934 SmallVector<const Expr *, 4> Shareds;
935 SmallVector<const Expr *, 4> Privates;
936 SmallVector<const Expr *, 4> ReductionOps;
937 SmallVector<const Expr *, 4> LHSs;
938 SmallVector<const Expr *, 4> RHSs;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000939 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000940 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000941 auto IRed = C->reduction_ops().begin();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000942 auto ILHS = C->lhs_exprs().begin();
943 auto IRHS = C->rhs_exprs().begin();
944 for (const auto *Ref : C->varlists()) {
945 Shareds.emplace_back(Ref);
946 Privates.emplace_back(*IPriv);
947 ReductionOps.emplace_back(*IRed);
948 LHSs.emplace_back(*ILHS);
949 RHSs.emplace_back(*IRHS);
950 std::advance(IPriv, 1);
951 std::advance(IRed, 1);
952 std::advance(ILHS, 1);
953 std::advance(IRHS, 1);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000954 }
955 }
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000956 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
957 unsigned Count = 0;
958 auto ILHS = LHSs.begin();
959 auto IRHS = RHSs.begin();
960 auto IPriv = Privates.begin();
961 for (const auto *IRef : Shareds) {
962 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
963 // Emit private VarDecl with reduction init.
964 RedCG.emitSharedLValue(*this, Count);
965 RedCG.emitAggregateType(*this, Count);
966 auto Emission = EmitAutoVarAlloca(*PrivateVD);
967 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
968 RedCG.getSharedLValue(Count),
969 [&Emission](CodeGenFunction &CGF) {
970 CGF.EmitAutoVarInit(Emission);
971 return true;
972 });
973 EmitAutoVarCleanups(Emission);
974 Address BaseAddr = RedCG.adjustPrivateAddress(
975 *this, Count, Emission.getAllocatedAddress());
976 bool IsRegistered = PrivateScope.addPrivate(
977 RedCG.getBaseDecl(Count), [BaseAddr]() -> Address { return BaseAddr; });
978 assert(IsRegistered && "private var already registered as private");
979 // Silence the warning about unused variable.
980 (void)IsRegistered;
981
982 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
983 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Eric Christopher7aba9782017-07-14 01:42:57 +0000984 if (isa<OMPArraySectionExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000985 // Store the address of the original variable associated with the LHS
986 // implicit variable.
987 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
988 return RedCG.getSharedLValue(Count).getAddress();
989 });
990 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
991 return GetAddrOfLocalVar(PrivateVD);
992 });
Eric Christopher7aba9782017-07-14 01:42:57 +0000993 } else if (isa<ArraySubscriptExpr>(IRef)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000994 // Store the address of the original variable associated with the LHS
995 // implicit variable.
996 PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
997 return RedCG.getSharedLValue(Count).getAddress();
998 });
999 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1000 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1001 ConvertTypeForMem(RHSVD->getType()),
1002 "rhs.begin");
1003 });
1004 } else {
1005 QualType Type = PrivateVD->getType();
1006 bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1007 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1008 // Store the address of the original variable associated with the LHS
1009 // implicit variable.
1010 if (IsArray) {
1011 OriginalAddr = Builder.CreateElementBitCast(
1012 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1013 }
1014 PrivateScope.addPrivate(
1015 LHSVD, [OriginalAddr]() -> Address { return OriginalAddr; });
1016 PrivateScope.addPrivate(
1017 RHSVD, [this, PrivateVD, RHSVD, IsArray]() -> Address {
1018 return IsArray
1019 ? Builder.CreateElementBitCast(
1020 GetAddrOfLocalVar(PrivateVD),
1021 ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1022 : GetAddrOfLocalVar(PrivateVD);
1023 });
1024 }
1025 ++ILHS;
1026 ++IRHS;
1027 ++IPriv;
1028 ++Count;
1029 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001030}
1031
1032void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001033 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001034 if (!HaveInsertPoint())
1035 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001036 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001037 llvm::SmallVector<const Expr *, 8> LHSExprs;
1038 llvm::SmallVector<const Expr *, 8> RHSExprs;
1039 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001040 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001041 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001042 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001043 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001044 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1045 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1046 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1047 }
1048 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001049 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1050 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1051 D.getDirectiveKind() == OMPD_simd;
1052 bool SimpleReduction = D.getDirectiveKind() == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001053 // Emit nowait reduction if nowait clause is present or directive is a
1054 // parallel directive (it always has implicit barrier).
1055 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001056 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001057 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001058 }
1059}
1060
Alexey Bataev61205072016-03-02 04:57:40 +00001061static void emitPostUpdateForReductionClause(
1062 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1063 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1064 if (!CGF.HaveInsertPoint())
1065 return;
1066 llvm::BasicBlock *DoneBB = nullptr;
1067 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1068 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1069 if (!DoneBB) {
1070 if (auto *Cond = CondGen(CGF)) {
1071 // If the first post-update expression is found, emit conditional
1072 // block if it was requested.
1073 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1074 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1075 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1076 CGF.EmitBlock(ThenBB);
1077 }
1078 }
1079 CGF.EmitIgnoredExpr(PostUpdate);
1080 }
1081 }
1082 if (DoneBB)
1083 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1084}
1085
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001086namespace {
1087/// Codegen lambda for appending distribute lower and upper bounds to outlined
1088/// parallel function. This is necessary for combined constructs such as
1089/// 'distribute parallel for'
1090typedef llvm::function_ref<void(CodeGenFunction &,
1091 const OMPExecutableDirective &,
1092 llvm::SmallVectorImpl<llvm::Value *> &)>
1093 CodeGenBoundParametersTy;
1094} // anonymous namespace
1095
1096static void emitCommonOMPParallelDirective(
1097 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1098 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1099 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001100 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1101 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1102 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001103 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001104 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001105 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1106 /*IgnoreResultAssign*/ true);
1107 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1108 CGF, NumThreads, NumThreadsClause->getLocStart());
1109 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001110 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001111 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001112 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1113 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1114 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001115 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001116 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1117 if (C->getNameModifier() == OMPD_unknown ||
1118 C->getNameModifier() == OMPD_parallel) {
1119 IfCond = C->getCondition();
1120 break;
1121 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001122 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001123
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001124 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001125 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001126 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1127 // lower and upper bounds with the pragma 'for' chunking mechanism.
1128 // The following lambda takes care of appending the lower and upper bound
1129 // parameters when necessary
1130 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001131 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001132 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001133 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001134}
1135
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001136static void emitEmptyBoundParameters(CodeGenFunction &,
1137 const OMPExecutableDirective &,
1138 llvm::SmallVectorImpl<llvm::Value *> &) {}
1139
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001140void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001141 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001142 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001143 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001144 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001145 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1146 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001147 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001148 // propagation master's thread values of threadprivate variables to local
1149 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001150 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1151 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1152 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001153 }
1154 CGF.EmitOMPPrivateClause(S, PrivateScope);
1155 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1156 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001157 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001158 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001159 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001160 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1161 emitEmptyBoundParameters);
Alexey Bataev61205072016-03-02 04:57:40 +00001162 emitPostUpdateForReductionClause(
1163 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001164}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001165
Alexey Bataev0f34da12015-07-02 04:17:07 +00001166void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1167 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001168 RunCleanupsScope BodyScope(*this);
1169 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001170 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001171 EmitIgnoredExpr(I);
1172 }
Alexander Musman3276a272015-03-21 10:12:56 +00001173 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001174 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001175 for (auto *U : C->updates())
Alexander Musman3276a272015-03-21 10:12:56 +00001176 EmitIgnoredExpr(U);
Alexander Musman3276a272015-03-21 10:12:56 +00001177 }
1178
Alexander Musmana5f070a2014-10-01 06:03:56 +00001179 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001180 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001181 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001182 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001183 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001184 // The end (updates/cleanups).
1185 EmitBlock(Continue.getBlock());
1186 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001187}
1188
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001189void CodeGenFunction::EmitOMPInnerLoop(
1190 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1191 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001192 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1193 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001194 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001195
1196 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001197 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001198 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001199 const SourceRange &R = S.getSourceRange();
1200 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1201 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001202
1203 // If there are any cleanups between here and the loop-exit scope,
1204 // create a block to stage a loop exit along.
1205 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001206 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001207 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001208
Alexander Musmand196ef22014-10-07 08:57:09 +00001209 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001210
Alexey Bataev2df54a02015-03-12 08:53:29 +00001211 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001212 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001213 if (ExitBlock != LoopExit.getBlock()) {
1214 EmitBlock(ExitBlock);
1215 EmitBranchThroughCleanup(LoopExit);
1216 }
1217
1218 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001219 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001220
1221 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001222 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001223 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1224
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001225 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001226
1227 // Emit "IV = IV + 1" and a back-edge to the condition block.
1228 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001229 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001230 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001231 BreakContinueStack.pop_back();
1232 EmitBranch(CondBlock);
1233 LoopStack.pop();
1234 // Emit the fall-through block.
1235 EmitBlock(LoopExit.getBlock());
1236}
1237
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001238void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001239 if (!HaveInsertPoint())
1240 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001241 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001242 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001243 for (auto *Init : C->inits()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001244 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001245 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1246 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1247 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1248 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1249 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1250 VD->getInit()->getType(), VK_LValue,
1251 VD->getInit()->getExprLoc());
1252 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1253 VD->getType()),
1254 /*capturedByInit=*/false);
1255 EmitAutoVarCleanups(Emission);
1256 } else
1257 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001258 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001259 // Emit the linear steps for the linear clauses.
1260 // If a step is not constant, it is pre-calculated before the loop.
1261 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1262 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001263 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001264 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001265 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001266 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001267 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001268}
1269
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001270void CodeGenFunction::EmitOMPLinearClauseFinal(
1271 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001272 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001273 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001274 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001275 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001276 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001277 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001278 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001279 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001280 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001281 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001282 // If the first post-update expression is found, emit conditional
1283 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001284 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1285 DoneBB = createBasicBlock(".omp.linear.pu.done");
1286 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1287 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001288 }
1289 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001290 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1291 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001292 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001293 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001294 Address OrigAddr = EmitLValue(&DRE).getAddress();
1295 CodeGenFunction::OMPPrivateScope VarScope(*this);
1296 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001297 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001298 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001299 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001300 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001301 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001302 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001303 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001304 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001305 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001306}
1307
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001308static void emitAlignedClause(CodeGenFunction &CGF,
1309 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001310 if (!CGF.HaveInsertPoint())
1311 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001312 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001313 unsigned ClauseAlignment = 0;
1314 if (auto AlignmentExpr = Clause->getAlignment()) {
1315 auto AlignmentCI =
1316 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1317 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001318 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001319 for (auto E : Clause->varlists()) {
1320 unsigned Alignment = ClauseAlignment;
1321 if (Alignment == 0) {
1322 // OpenMP [2.8.1, Description]
1323 // If no optional parameter is specified, implementation-defined default
1324 // alignments for SIMD instructions on the target platforms are assumed.
1325 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001326 CGF.getContext()
1327 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1328 E->getType()->getPointeeType()))
1329 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001330 }
1331 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1332 "alignment is not power of 2");
1333 if (Alignment != 0) {
1334 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1335 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1336 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001337 }
1338 }
1339}
1340
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001341void CodeGenFunction::EmitOMPPrivateLoopCounters(
1342 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1343 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001344 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001345 auto I = S.private_counters().begin();
1346 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001347 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1348 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001349 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001350 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001351 if (!LocalDeclMap.count(PrivateVD)) {
1352 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1353 EmitAutoVarCleanups(VarEmission);
1354 }
1355 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1356 /*RefersToEnclosingVariableOrCapture=*/false,
1357 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1358 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001359 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001360 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1361 VD->hasGlobalStorage()) {
1362 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1363 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1364 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1365 E->getType(), VK_LValue, E->getExprLoc());
1366 return EmitLValue(&DRE).getAddress();
1367 });
1368 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001369 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001370 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001371}
1372
Alexey Bataev62dbb972015-04-22 11:59:37 +00001373static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1374 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1375 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001376 if (!CGF.HaveInsertPoint())
1377 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001378 {
1379 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001380 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001381 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001382 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001383 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001384 CGF.EmitIgnoredExpr(I);
1385 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001386 }
1387 // Check that loop is executed at least one time.
1388 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1389}
1390
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001391void CodeGenFunction::EmitOMPLinearClause(
1392 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1393 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001394 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001395 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1396 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1397 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1398 for (auto *C : LoopDirective->counters()) {
1399 SIMDLCVs.insert(
1400 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1401 }
1402 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001403 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001404 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001405 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001406 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1407 auto *PrivateVD =
1408 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001409 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1410 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1411 // Emit private VarDecl with copy init.
1412 EmitVarDecl(*PrivateVD);
1413 return GetAddrOfLocalVar(PrivateVD);
1414 });
1415 assert(IsRegistered && "linear var already registered as private");
1416 // Silence the warning about unused variable.
1417 (void)IsRegistered;
1418 } else
1419 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001420 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001421 }
1422 }
1423}
1424
Alexey Bataev45bfad52015-08-21 12:19:04 +00001425static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001426 const OMPExecutableDirective &D,
1427 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001428 if (!CGF.HaveInsertPoint())
1429 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001430 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001431 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1432 /*ignoreResult=*/true);
1433 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1434 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1435 // In presence of finite 'safelen', it may be unsafe to mark all
1436 // the memory instructions parallel, because loop-carried
1437 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001438 if (!IsMonotonic)
1439 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001440 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001441 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1442 /*ignoreResult=*/true);
1443 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001444 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001445 // In presence of finite 'safelen', it may be unsafe to mark all
1446 // the memory instructions parallel, because loop-carried
1447 // dependences of 'safelen' iterations are possible.
1448 CGF.LoopStack.setParallel(false);
1449 }
1450}
1451
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001452void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1453 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001454 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001455 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001456 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001457 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001458}
1459
Alexey Bataevef549a82016-03-09 09:49:09 +00001460void CodeGenFunction::EmitOMPSimdFinal(
1461 const OMPLoopDirective &D,
1462 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001463 if (!HaveInsertPoint())
1464 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001465 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001466 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001467 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001468 for (auto F : D.finals()) {
1469 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001470 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1471 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1472 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1473 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001474 if (!DoneBB) {
1475 if (auto *Cond = CondGen(*this)) {
1476 // If the first post-update expression is found, emit conditional
1477 // block if it was requested.
1478 auto *ThenBB = createBasicBlock(".omp.final.then");
1479 DoneBB = createBasicBlock(".omp.final.done");
1480 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1481 EmitBlock(ThenBB);
1482 }
1483 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001484 Address OrigAddr = Address::invalid();
1485 if (CED)
1486 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1487 else {
1488 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1489 /*RefersToEnclosingVariableOrCapture=*/false,
1490 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1491 OrigAddr = EmitLValue(&DRE).getAddress();
1492 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001493 OMPPrivateScope VarScope(*this);
1494 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001495 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001496 (void)VarScope.Privatize();
1497 EmitIgnoredExpr(F);
1498 }
1499 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001500 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001501 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001502 if (DoneBB)
1503 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001504}
1505
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001506static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1507 const OMPLoopDirective &S,
1508 CodeGenFunction::JumpDest LoopExit) {
1509 CGF.EmitOMPLoopBody(S, LoopExit);
1510 CGF.EmitStopPoint(&S);
Hans Wennborged129ae2017-04-27 17:02:25 +00001511}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001512
Alexander Musman515ad8c2014-05-22 08:54:05 +00001513void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001514 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00001515 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001516 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001517 // for (IV in 0..LastIteration) BODY;
1518 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001519 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001520 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001521
Alexey Bataev62dbb972015-04-22 11:59:37 +00001522 // Emit: if (PreCond) - begin.
1523 // If the condition constant folds and can be elided, avoid emitting the
1524 // whole loop.
1525 bool CondConstant;
1526 llvm::BasicBlock *ContBlock = nullptr;
1527 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1528 if (!CondConstant)
1529 return;
1530 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001531 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1532 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001533 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1534 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001535 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001536 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001537 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001538
1539 // Emit the loop iteration variable.
1540 const Expr *IVExpr = S.getIterationVariable();
1541 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1542 CGF.EmitVarDecl(*IVDecl);
1543 CGF.EmitIgnoredExpr(S.getInit());
1544
1545 // Emit the iterations count variable.
1546 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001547 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001548 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1549 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1550 // Emit calculation of the iterations count.
1551 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001552 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001553
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001554 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001555
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001556 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001557 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001558 {
1559 OMPPrivateScope LoopScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001560 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1561 CGF.EmitOMPLinearClause(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001562 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001563 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001564 bool HasLastprivateClause =
1565 CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001566 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001567 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1568 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001569 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001570 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001571 CGF.EmitStopPoint(&S);
1572 },
1573 [](CodeGenFunction &) {});
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001574 CGF.EmitOMPSimdFinal(
1575 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001576 // Emit final copy of the lastprivate variables at the end of loops.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001577 if (HasLastprivateClause)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001578 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001579 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
Alexey Bataev61205072016-03-02 04:57:40 +00001580 emitPostUpdateForReductionClause(
1581 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001582 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001583 CGF.EmitOMPLinearClauseFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001584 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001585 // Emit: if (PreCond) - end.
1586 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001587 CGF.EmitBranch(ContBlock);
1588 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001589 }
1590 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00001591 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001592 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001593}
1594
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001595void CodeGenFunction::EmitOMPOuterLoop(
1596 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1597 CodeGenFunction::OMPPrivateScope &LoopScope,
1598 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1599 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1600 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001601 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001602
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001603 const Expr *IVExpr = S.getIterationVariable();
1604 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1605 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1606
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001607 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1608
1609 // Start the loop with a block that tests the condition.
1610 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1611 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001612 const SourceRange &R = S.getSourceRange();
1613 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1614 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001615
1616 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001617 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001618 // UB = min(UB, GlobalUB) or
1619 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1620 // 'distribute parallel for')
1621 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001622 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001623 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001624 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001625 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001626 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001627 BoolCondVal =
1628 RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1629 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001630 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001631
1632 // If there are any cleanups between here and the loop-exit scope,
1633 // create a block to stage a loop exit along.
1634 auto ExitBlock = LoopExit.getBlock();
1635 if (LoopScope.requiresCleanups())
1636 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1637
1638 auto LoopBody = createBasicBlock("omp.dispatch.body");
1639 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1640 if (ExitBlock != LoopExit.getBlock()) {
1641 EmitBlock(ExitBlock);
1642 EmitBranchThroughCleanup(LoopExit);
1643 }
1644 EmitBlock(LoopBody);
1645
Alexander Musman92bdaab2015-03-12 13:37:50 +00001646 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1647 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001648 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001649 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001650
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001651 // Create a block for the increment.
1652 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1653 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1654
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001655 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1656 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001657 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1658 LoopStack.setParallel(!IsMonotonic);
1659 else
1660 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001661
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001662 SourceLocation Loc = S.getLocStart();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001663
1664 // when 'distribute' is not combined with a 'for':
1665 // while (idx <= UB) { BODY; ++idx; }
1666 // when 'distribute' is combined with a 'for'
1667 // (e.g. 'distribute parallel for')
1668 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1669 EmitOMPInnerLoop(
1670 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1671 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1672 CodeGenLoop(CGF, S, LoopExit);
1673 },
1674 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1675 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1676 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001677
1678 EmitBlock(Continue.getBlock());
1679 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001680 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001681 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001682 EmitIgnoredExpr(LoopArgs.NextLB);
1683 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001684 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001685
1686 EmitBranch(CondBlock);
1687 LoopStack.pop();
1688 // Emit the fall-through block.
1689 EmitBlock(LoopExit.getBlock());
1690
1691 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001692 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1693 if (!DynamicOrOrdered)
1694 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
1695 };
1696 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001697}
1698
1699void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001700 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001701 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001702 const OMPLoopArguments &LoopArgs,
1703 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001704 auto &RT = CGM.getOpenMPRuntime();
1705
1706 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001707 const bool DynamicOrOrdered =
1708 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001709
1710 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001711 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001712 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001713 "static non-chunked schedule does not need outer loop");
1714
1715 // Emit outer loop.
1716 //
1717 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1718 // When schedule(dynamic,chunk_size) is specified, the iterations are
1719 // distributed to threads in the team in chunks as the threads request them.
1720 // Each thread executes a chunk of iterations, then requests another chunk,
1721 // until no chunks remain to be distributed. Each chunk contains chunk_size
1722 // iterations, except for the last chunk to be distributed, which may have
1723 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1724 //
1725 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1726 // to threads in the team in chunks as the executing threads request them.
1727 // Each thread executes a chunk of iterations, then requests another chunk,
1728 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1729 // each chunk is proportional to the number of unassigned iterations divided
1730 // by the number of threads in the team, decreasing to 1. For a chunk_size
1731 // with value k (greater than 1), the size of each chunk is determined in the
1732 // same way, with the restriction that the chunks do not contain fewer than k
1733 // iterations (except for the last chunk to be assigned, which may have fewer
1734 // than k iterations).
1735 //
1736 // When schedule(auto) is specified, the decision regarding scheduling is
1737 // delegated to the compiler and/or runtime system. The programmer gives the
1738 // implementation the freedom to choose any possible mapping of iterations to
1739 // threads in the team.
1740 //
1741 // When schedule(runtime) is specified, the decision regarding scheduling is
1742 // deferred until run time, and the schedule and chunk size are taken from the
1743 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1744 // implementation defined
1745 //
1746 // while(__kmpc_dispatch_next(&LB, &UB)) {
1747 // idx = LB;
1748 // while (idx <= UB) { BODY; ++idx;
1749 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1750 // } // inner loop
1751 // }
1752 //
1753 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1754 // When schedule(static, chunk_size) is specified, iterations are divided into
1755 // chunks of size chunk_size, and the chunks are assigned to the threads in
1756 // the team in a round-robin fashion in the order of the thread number.
1757 //
1758 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1759 // while (idx <= UB) { BODY; ++idx; } // inner loop
1760 // LB = LB + ST;
1761 // UB = UB + ST;
1762 // }
1763 //
1764
1765 const Expr *IVExpr = S.getIterationVariable();
1766 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1767 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1768
1769 if (DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001770 auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1771 llvm::Value *LBVal = DispatchBounds.first;
1772 llvm::Value *UBVal = DispatchBounds.second;
1773 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1774 LoopArgs.Chunk};
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001775 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001776 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001777 } else {
1778 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001779 Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1780 LoopArgs.ST, LoopArgs.Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001781 }
1782
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001783 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1784 const unsigned IVSize,
1785 const bool IVSigned) {
1786 if (Ordered) {
1787 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1788 IVSigned);
1789 }
1790 };
1791
1792 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1793 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1794 OuterLoopArgs.IncExpr = S.getInc();
1795 OuterLoopArgs.Init = S.getInit();
1796 OuterLoopArgs.Cond = S.getCond();
1797 OuterLoopArgs.NextLB = S.getNextLowerBound();
1798 OuterLoopArgs.NextUB = S.getNextUpperBound();
1799 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1800 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001801}
1802
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001803static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1804 const unsigned IVSize, const bool IVSigned) {}
1805
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001806void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001807 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1808 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1809 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001810
1811 auto &RT = CGM.getOpenMPRuntime();
1812
1813 // Emit outer loop.
1814 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1815 // dynamic
1816 //
1817
1818 const Expr *IVExpr = S.getIterationVariable();
1819 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1820 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1821
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001822 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize,
1823 IVSigned, /* Ordered = */ false, LoopArgs.IL,
1824 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1825 LoopArgs.Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001826
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001827 // for combined 'distribute' and 'for' the increment expression of distribute
1828 // is store in DistInc. For 'distribute' alone, it is in Inc.
1829 Expr *IncExpr;
1830 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1831 IncExpr = S.getDistInc();
1832 else
1833 IncExpr = S.getInc();
1834
1835 // this routine is shared by 'omp distribute parallel for' and
1836 // 'omp distribute': select the right EUB expression depending on the
1837 // directive
1838 OMPLoopArguments OuterLoopArgs;
1839 OuterLoopArgs.LB = LoopArgs.LB;
1840 OuterLoopArgs.UB = LoopArgs.UB;
1841 OuterLoopArgs.ST = LoopArgs.ST;
1842 OuterLoopArgs.IL = LoopArgs.IL;
1843 OuterLoopArgs.Chunk = LoopArgs.Chunk;
1844 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1845 ? S.getCombinedEnsureUpperBound()
1846 : S.getEnsureUpperBound();
1847 OuterLoopArgs.IncExpr = IncExpr;
1848 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1849 ? S.getCombinedInit()
1850 : S.getInit();
1851 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1852 ? S.getCombinedCond()
1853 : S.getCond();
1854 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1855 ? S.getCombinedNextLowerBound()
1856 : S.getNextLowerBound();
1857 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1858 ? S.getCombinedNextUpperBound()
1859 : S.getNextUpperBound();
1860
1861 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
1862 LoopScope, OuterLoopArgs, CodeGenLoopContent,
1863 emitEmptyOrdered);
1864}
1865
1866/// Emit a helper variable and return corresponding lvalue.
1867static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1868 const DeclRefExpr *Helper) {
1869 auto VDecl = cast<VarDecl>(Helper->getDecl());
1870 CGF.EmitVarDecl(*VDecl);
1871 return CGF.EmitLValue(Helper);
1872}
1873
1874static std::pair<LValue, LValue>
1875emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
1876 const OMPExecutableDirective &S) {
1877 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1878 LValue LB =
1879 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
1880 LValue UB =
1881 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
1882
1883 // When composing 'distribute' with 'for' (e.g. as in 'distribute
1884 // parallel for') we need to use the 'distribute'
1885 // chunk lower and upper bounds rather than the whole loop iteration
1886 // space. These are parameters to the outlined function for 'parallel'
1887 // and we copy the bounds of the previous schedule into the
1888 // the current ones.
1889 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
1890 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
1891 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(PrevLB, SourceLocation());
1892 PrevLBVal = CGF.EmitScalarConversion(
1893 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
1894 LS.getIterationVariable()->getType(), SourceLocation());
1895 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(PrevUB, SourceLocation());
1896 PrevUBVal = CGF.EmitScalarConversion(
1897 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
1898 LS.getIterationVariable()->getType(), SourceLocation());
1899
1900 CGF.EmitStoreOfScalar(PrevLBVal, LB);
1901 CGF.EmitStoreOfScalar(PrevUBVal, UB);
1902
1903 return {LB, UB};
1904}
1905
1906/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
1907/// we need to use the LB and UB expressions generated by the worksharing
1908/// code generation support, whereas in non combined situations we would
1909/// just emit 0 and the LastIteration expression
1910/// This function is necessary due to the difference of the LB and UB
1911/// types for the RT emission routines for 'for_static_init' and
1912/// 'for_dispatch_init'
1913static std::pair<llvm::Value *, llvm::Value *>
1914emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
1915 const OMPExecutableDirective &S,
1916 Address LB, Address UB) {
1917 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1918 const Expr *IVExpr = LS.getIterationVariable();
1919 // when implementing a dynamic schedule for a 'for' combined with a
1920 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
1921 // is not normalized as each team only executes its own assigned
1922 // distribute chunk
1923 QualType IteratorTy = IVExpr->getType();
1924 llvm::Value *LBVal = CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy,
1925 SourceLocation());
1926 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy,
1927 SourceLocation());
1928 return {LBVal, UBVal};
Hans Wennborged129ae2017-04-27 17:02:25 +00001929}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001930
1931static void emitDistributeParallelForDistributeInnerBoundParams(
1932 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1933 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
1934 const auto &Dir = cast<OMPLoopDirective>(S);
1935 LValue LB =
1936 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
1937 auto LBCast = CGF.Builder.CreateIntCast(
1938 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
1939 CapturedVars.push_back(LBCast);
1940 LValue UB =
1941 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
1942
1943 auto UBCast = CGF.Builder.CreateIntCast(
1944 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
1945 CapturedVars.push_back(UBCast);
Hans Wennborged129ae2017-04-27 17:02:25 +00001946}
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001947
1948static void
1949emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
1950 const OMPLoopDirective &S,
1951 CodeGenFunction::JumpDest LoopExit) {
1952 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
1953 PrePostActionTy &) {
1954 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
1955 emitDistributeParallelForInnerBounds,
1956 emitDistributeParallelForDispatchBounds);
1957 };
1958
1959 emitCommonOMPParallelDirective(
1960 CGF, S, OMPD_for, CGInlinedWorksharingLoop,
1961 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001962}
1963
Carlo Bertolli9925f152016-06-27 14:55:37 +00001964void CodeGenFunction::EmitOMPDistributeParallelForDirective(
1965 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001966 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1967 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
1968 S.getDistInc());
1969 };
Carlo Bertolli9925f152016-06-27 14:55:37 +00001970 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001971 OMPCancelStackRAII CancelRegion(*this, OMPD_distribute_parallel_for,
1972 /*HasCancel=*/false);
1973 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
1974 /*HasCancel=*/false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00001975}
1976
Kelvin Li4a39add2016-07-05 05:00:15 +00001977void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
1978 const OMPDistributeParallelForSimdDirective &S) {
1979 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1980 CGM.getOpenMPRuntime().emitInlinedDirective(
1981 *this, OMPD_distribute_parallel_for_simd,
1982 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1983 OMPLoopScope PreInitScope(CGF, S);
1984 CGF.EmitStmt(
1985 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1986 });
1987}
Kelvin Li787f3fc2016-07-06 04:45:38 +00001988
1989void CodeGenFunction::EmitOMPDistributeSimdDirective(
1990 const OMPDistributeSimdDirective &S) {
1991 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1992 CGM.getOpenMPRuntime().emitInlinedDirective(
1993 *this, OMPD_distribute_simd,
1994 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1995 OMPLoopScope PreInitScope(CGF, S);
1996 CGF.EmitStmt(
1997 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1998 });
1999}
2000
Kelvin Lia579b912016-07-14 02:54:56 +00002001void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
2002 const OMPTargetParallelForSimdDirective &S) {
2003 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2004 CGM.getOpenMPRuntime().emitInlinedDirective(
2005 *this, OMPD_target_parallel_for_simd,
2006 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2007 OMPLoopScope PreInitScope(CGF, S);
2008 CGF.EmitStmt(
2009 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2010 });
2011}
2012
Kelvin Li986330c2016-07-20 22:57:10 +00002013void CodeGenFunction::EmitOMPTargetSimdDirective(
2014 const OMPTargetSimdDirective &S) {
2015 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2016 CGM.getOpenMPRuntime().emitInlinedDirective(
2017 *this, OMPD_target_simd, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2018 OMPLoopScope PreInitScope(CGF, S);
2019 CGF.EmitStmt(
2020 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2021 });
2022}
2023
Kelvin Li02532872016-08-05 14:37:37 +00002024void CodeGenFunction::EmitOMPTeamsDistributeDirective(
2025 const OMPTeamsDistributeDirective &S) {
2026 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2027 CGM.getOpenMPRuntime().emitInlinedDirective(
2028 *this, OMPD_teams_distribute,
2029 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2030 OMPLoopScope PreInitScope(CGF, S);
2031 CGF.EmitStmt(
2032 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2033 });
2034}
2035
Kelvin Li4e325f72016-10-25 12:50:55 +00002036void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
2037 const OMPTeamsDistributeSimdDirective &S) {
2038 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2039 CGM.getOpenMPRuntime().emitInlinedDirective(
2040 *this, OMPD_teams_distribute_simd,
2041 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2042 OMPLoopScope PreInitScope(CGF, S);
2043 CGF.EmitStmt(
2044 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2045 });
2046}
2047
Kelvin Li579e41c2016-11-30 23:51:03 +00002048void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
2049 const OMPTeamsDistributeParallelForSimdDirective &S) {
2050 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2051 CGM.getOpenMPRuntime().emitInlinedDirective(
2052 *this, OMPD_teams_distribute_parallel_for_simd,
2053 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2054 OMPLoopScope PreInitScope(CGF, S);
2055 CGF.EmitStmt(
2056 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2057 });
2058}
Kelvin Li4e325f72016-10-25 12:50:55 +00002059
Kelvin Li7ade93f2016-12-09 03:24:30 +00002060void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
2061 const OMPTeamsDistributeParallelForDirective &S) {
2062 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2063 CGM.getOpenMPRuntime().emitInlinedDirective(
2064 *this, OMPD_teams_distribute_parallel_for,
2065 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2066 OMPLoopScope PreInitScope(CGF, S);
2067 CGF.EmitStmt(
2068 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2069 });
2070}
2071
Kelvin Li83c451e2016-12-25 04:52:54 +00002072void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
2073 const OMPTargetTeamsDistributeDirective &S) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002074 CGM.getOpenMPRuntime().emitInlinedDirective(
2075 *this, OMPD_target_teams_distribute,
Kelvin Li83c451e2016-12-25 04:52:54 +00002076 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002077 CGF.EmitStmt(
2078 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Kelvin Li83c451e2016-12-25 04:52:54 +00002079 });
2080}
2081
Kelvin Li80e8f562016-12-29 22:16:30 +00002082void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
2083 const OMPTargetTeamsDistributeParallelForDirective &S) {
2084 CGM.getOpenMPRuntime().emitInlinedDirective(
2085 *this, OMPD_target_teams_distribute_parallel_for,
2086 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2087 CGF.EmitStmt(
2088 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2089 });
2090}
2091
Kelvin Li1851df52017-01-03 05:23:48 +00002092void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2093 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
2094 CGM.getOpenMPRuntime().emitInlinedDirective(
2095 *this, OMPD_target_teams_distribute_parallel_for_simd,
2096 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2097 CGF.EmitStmt(
2098 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2099 });
2100}
2101
Kelvin Lida681182017-01-10 18:08:18 +00002102void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
2103 const OMPTargetTeamsDistributeSimdDirective &S) {
2104 CGM.getOpenMPRuntime().emitInlinedDirective(
2105 *this, OMPD_target_teams_distribute_simd,
2106 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2107 CGF.EmitStmt(
2108 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2109 });
2110}
2111
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002112namespace {
2113 struct ScheduleKindModifiersTy {
2114 OpenMPScheduleClauseKind Kind;
2115 OpenMPScheduleClauseModifier M1;
2116 OpenMPScheduleClauseModifier M2;
2117 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2118 OpenMPScheduleClauseModifier M1,
2119 OpenMPScheduleClauseModifier M2)
2120 : Kind(Kind), M1(M1), M2(M2) {}
2121 };
2122} // namespace
2123
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002124bool CodeGenFunction::EmitOMPWorksharingLoop(
2125 const OMPLoopDirective &S, Expr *EUB,
2126 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2127 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002128 // Emit the loop iteration variable.
2129 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2130 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2131 EmitVarDecl(*IVDecl);
2132
2133 // Emit the iterations count variable.
2134 // If it is not a variable, Sema decided to calculate iterations count on each
2135 // iteration (e.g., it is foldable into a constant).
2136 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2137 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2138 // Emit calculation of the iterations count.
2139 EmitIgnoredExpr(S.getCalcLastIteration());
2140 }
2141
2142 auto &RT = CGM.getOpenMPRuntime();
2143
Alexey Bataev38e89532015-04-16 04:54:05 +00002144 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002145 // Check pre-condition.
2146 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002147 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002148 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002149 // If the condition constant folds and can be elided, avoid emitting the
2150 // whole loop.
2151 bool CondConstant;
2152 llvm::BasicBlock *ContBlock = nullptr;
2153 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2154 if (!CondConstant)
2155 return false;
2156 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002157 auto *ThenBlock = createBasicBlock("omp.precond.then");
2158 ContBlock = createBasicBlock("omp.precond.end");
2159 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002160 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002161 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002162 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002163 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002164
Alexey Bataev8b427062016-05-25 12:36:08 +00002165 bool Ordered = false;
2166 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2167 if (OrderedClause->getNumForLoops())
2168 RT.emitDoacrossInit(*this, S);
2169 else
2170 Ordered = true;
2171 }
2172
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002173 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002174 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002175 EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002176 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002177
2178 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2179 LValue LB = Bounds.first;
2180 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002181 LValue ST =
2182 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2183 LValue IL =
2184 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2185
Alexander Musmanc6388682014-12-15 07:07:06 +00002186 // Emit 'then' code.
2187 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002188 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002189 if (EmitOMPFirstprivateClause(S, LoopScope)) {
2190 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002191 // initialization of firstprivate variables and post-update of
2192 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002193 CGM.getOpenMPRuntime().emitBarrierCall(
2194 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2195 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002196 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002197 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002198 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002199 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002200 EmitOMPPrivateLoopCounters(S, LoopScope);
2201 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002202 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002203
2204 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002205 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002206 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002207 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002208 ScheduleKind.Schedule = C->getScheduleKind();
2209 ScheduleKind.M1 = C->getFirstScheduleModifier();
2210 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002211 if (const auto *Ch = C->getChunkSize()) {
2212 Chunk = EmitScalarExpr(Ch);
2213 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2214 S.getIterationVariable()->getType(),
2215 S.getLocStart());
2216 }
2217 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002218 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2219 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002220 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2221 // If the static schedule kind is specified or if the ordered clause is
2222 // specified, and if no monotonic modifier is specified, the effect will
2223 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002224 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002225 /* Chunked */ Chunk != nullptr) &&
2226 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002227 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2228 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002229 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2230 // When no chunk_size is specified, the iteration space is divided into
2231 // chunks that are approximately equal in size, and at most one chunk is
2232 // distributed to each thread. Note that the size of the chunks is
2233 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00002234 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
2235 IVSize, IVSigned, Ordered,
2236 IL.getAddress(), LB.getAddress(),
2237 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002238 auto LoopExit =
2239 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002240 // UB = min(UB, GlobalUB);
2241 EmitIgnoredExpr(S.getEnsureUpperBound());
2242 // IV = LB;
2243 EmitIgnoredExpr(S.getInit());
2244 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002245 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2246 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002247 [&S, LoopExit](CodeGenFunction &CGF) {
2248 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002249 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002250 },
2251 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002252 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002253 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002254 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2255 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
2256 };
2257 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002258 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002259 const bool IsMonotonic =
2260 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2261 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2262 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2263 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002264 // Emit the outer loop, which requests its work chunk [LB..UB] from
2265 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002266 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2267 ST.getAddress(), IL.getAddress(),
2268 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002269 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002270 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002271 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002272 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2273 EmitOMPSimdFinal(S,
2274 [&](CodeGenFunction &CGF) -> llvm::Value * {
2275 return CGF.Builder.CreateIsNotNull(
2276 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2277 });
2278 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002279 EmitOMPReductionClauseFinal(
2280 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2281 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2282 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002283 // Emit post-update of the reduction variables if IsLastIter != 0.
2284 emitPostUpdateForReductionClause(
2285 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2286 return CGF.Builder.CreateIsNotNull(
2287 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2288 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002289 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2290 if (HasLastprivateClause)
2291 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002292 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2293 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002294 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002295 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002296 return CGF.Builder.CreateIsNotNull(
2297 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2298 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002299 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002300 if (ContBlock) {
2301 EmitBranch(ContBlock);
2302 EmitBlock(ContBlock, true);
2303 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002304 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002305 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002306}
2307
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002308/// The following two functions generate expressions for the loop lower
2309/// and upper bounds in case of static and dynamic (dispatch) schedule
2310/// of the associated 'for' or 'distribute' loop.
2311static std::pair<LValue, LValue>
2312emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2313 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2314 LValue LB =
2315 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2316 LValue UB =
2317 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2318 return {LB, UB};
2319}
2320
2321/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2322/// consider the lower and upper bound expressions generated by the
2323/// worksharing loop support, but we use 0 and the iteration space size as
2324/// constants
2325static std::pair<llvm::Value *, llvm::Value *>
2326emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2327 Address LB, Address UB) {
2328 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2329 const Expr *IVExpr = LS.getIterationVariable();
2330 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2331 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2332 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2333 return {LBVal, UBVal};
2334}
2335
Alexander Musmanc6388682014-12-15 07:07:06 +00002336void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002337 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002338 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2339 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002340 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002341 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2342 emitForLoopBounds,
2343 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002344 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002345 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002346 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002347 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2348 S.hasCancel());
2349 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002350
2351 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002352 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002353 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2354 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002355}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002356
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002357void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002358 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002359 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2360 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002361 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2362 emitForLoopBounds,
2363 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002364 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002365 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002366 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002367 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2368 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002369
2370 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002371 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002372 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2373 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002374}
2375
Alexey Bataev2df54a02015-03-12 08:53:29 +00002376static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2377 const Twine &Name,
2378 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002379 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002380 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002381 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002382 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002383}
2384
Alexey Bataev3392d762016-02-16 11:18:12 +00002385void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00002386 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2387 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002388 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002389 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2390 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002391 auto &C = CGF.CGM.getContext();
2392 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2393 // Emit helper vars inits.
2394 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2395 CGF.Builder.getInt32(0));
2396 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2397 : CGF.Builder.getInt32(0);
2398 LValue UB =
2399 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2400 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2401 CGF.Builder.getInt32(1));
2402 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2403 CGF.Builder.getInt32(0));
2404 // Loop counter.
2405 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2406 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2407 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2408 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2409 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2410 // Generate condition for loop.
2411 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002412 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002413 // Increment for loop counter.
2414 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2415 S.getLocStart());
2416 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2417 // Iterate through all sections and emit a switch construct:
2418 // switch (IV) {
2419 // case 0:
2420 // <SectionStmt[0]>;
2421 // break;
2422 // ...
2423 // case <NumSection> - 1:
2424 // <SectionStmt[<NumSection> - 1]>;
2425 // break;
2426 // }
2427 // .omp.sections.exit:
2428 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2429 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2430 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2431 CS == nullptr ? 1 : CS->size());
2432 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002433 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002434 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002435 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2436 CGF.EmitBlock(CaseBB);
2437 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002438 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002439 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002440 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002441 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002442 } else {
2443 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2444 CGF.EmitBlock(CaseBB);
2445 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2446 CGF.EmitStmt(Stmt);
2447 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002448 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002449 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002450 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002451
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002452 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2453 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002454 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002455 // initialization of firstprivate variables and post-update of lastprivate
2456 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002457 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2458 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2459 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002460 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002461 CGF.EmitOMPPrivateClause(S, LoopScope);
2462 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2463 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2464 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002465
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002466 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002467 OpenMPScheduleTy ScheduleKind;
2468 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002469 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002470 CGF, S.getLocStart(), ScheduleKind, /*IVSize=*/32,
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002471 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
2472 UB.getAddress(), ST.getAddress());
2473 // UB = min(UB, GlobalUB);
2474 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2475 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2476 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2477 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2478 // IV = LB;
2479 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2480 // while (idx <= UB) { BODY; ++idx; }
2481 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2482 [](CodeGenFunction &) {});
2483 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002484 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2485 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
2486 };
2487 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002488 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002489 // Emit post-update of the reduction variables if IsLastIter != 0.
2490 emitPostUpdateForReductionClause(
2491 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2492 return CGF.Builder.CreateIsNotNull(
2493 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2494 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002495
2496 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2497 if (HasLastprivates)
2498 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002499 S, /*NoFinals=*/false,
2500 CGF.Builder.CreateIsNotNull(
2501 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002502 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002503
2504 bool HasCancel = false;
2505 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2506 HasCancel = OSD->hasCancel();
2507 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2508 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002509 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002510 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2511 HasCancel);
2512 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2513 // clause. Otherwise the barrier will be generated by the codegen for the
2514 // directive.
2515 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002516 // Emit implicit barrier to synchronize threads and avoid data races on
2517 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002518 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2519 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002520 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002521}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002522
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002523void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002524 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002525 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002526 EmitSections(S);
2527 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002528 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002529 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002530 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2531 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002532 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002533}
2534
2535void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002536 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002537 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002538 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002539 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002540 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2541 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002542}
2543
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002544void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002545 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002546 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002547 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002548 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002549 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002550 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002551 // Build a list of copyprivate variables along with helper expressions
2552 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002553 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002554 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002555 DestExprs.append(C->destination_exprs().begin(),
2556 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002557 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002558 AssignmentOps.append(C->assignment_ops().begin(),
2559 C->assignment_ops().end());
2560 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002561 // Emit code for 'single' region along with 'copyprivate' clauses
2562 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2563 Action.Enter(CGF);
2564 OMPPrivateScope SingleScope(CGF);
2565 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2566 CGF.EmitOMPPrivateClause(S, SingleScope);
2567 (void)SingleScope.Privatize();
2568 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2569 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002570 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002571 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002572 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2573 CopyprivateVars, DestExprs,
2574 SrcExprs, AssignmentOps);
2575 }
2576 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2577 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002578 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002579 CGM.getOpenMPRuntime().emitBarrierCall(
2580 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002581 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002582 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002583}
2584
Alexey Bataev8d690652014-12-04 07:23:53 +00002585void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002586 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2587 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002588 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002589 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002590 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002591 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002592}
2593
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002594void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002595 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2596 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002597 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002598 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002599 Expr *Hint = nullptr;
2600 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2601 Hint = HintClause->getHint();
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002602 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002603 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2604 S.getDirectiveName().getAsString(),
2605 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002606}
2607
Alexey Bataev671605e2015-04-13 05:28:11 +00002608void CodeGenFunction::EmitOMPParallelForDirective(
2609 const OMPParallelForDirective &S) {
2610 // Emit directive as a combined directive that consists of two implicit
2611 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002612 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002613 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002614 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2615 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002616 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002617 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2618 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002619}
2620
Alexander Musmane4e893b2014-09-23 09:33:00 +00002621void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002622 const OMPParallelForSimdDirective &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 &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002626 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2627 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002628 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002629 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2630 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002631}
2632
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002633void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002634 const OMPParallelSectionsDirective &S) {
2635 // Emit directive as a combined directive that consists of two implicit
2636 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002637 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2638 CGF.EmitSections(S);
2639 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002640 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2641 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002642}
2643
Alexey Bataev7292c292016-04-25 12:22:29 +00002644void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2645 const RegionCodeGenTy &BodyGen,
2646 const TaskGenTy &TaskGen,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002647 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002648 // Emit outlined function for task construct.
2649 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002650 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002651 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002652 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002653 // Check if the task is final
2654 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2655 // If the condition constant folds and can be elided, try to avoid emitting
2656 // the condition and the dead arm of the if/else.
2657 auto *Cond = Clause->getCondition();
2658 bool CondConstant;
2659 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2660 Data.Final.setInt(CondConstant);
2661 else
2662 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2663 } else {
2664 // By default the task is not final.
2665 Data.Final.setInt(/*IntVal=*/false);
2666 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002667 // Check if the task has 'priority' clause.
2668 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002669 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002670 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002671 Data.Priority.setPointer(EmitScalarConversion(
2672 EmitScalarExpr(Prio), Prio->getType(),
2673 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2674 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002675 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002676 // The first function argument for tasks is a thread id, the second one is a
2677 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002678 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2679 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002680 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002681 auto IRef = C->varlist_begin();
2682 for (auto *IInit : C->private_copies()) {
2683 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2684 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002685 Data.PrivateVars.push_back(*IRef);
2686 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002687 }
2688 ++IRef;
2689 }
2690 }
2691 EmittedAsPrivate.clear();
2692 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002693 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002694 auto IRef = C->varlist_begin();
2695 auto IElemInitRef = C->inits().begin();
2696 for (auto *IInit : C->private_copies()) {
2697 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2698 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002699 Data.FirstprivateVars.push_back(*IRef);
2700 Data.FirstprivateCopies.push_back(IInit);
2701 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002702 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002703 ++IRef;
2704 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002705 }
2706 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002707 // Get list of lastprivate variables (for taskloops).
2708 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2709 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2710 auto IRef = C->varlist_begin();
2711 auto ID = C->destination_exprs().begin();
2712 for (auto *IInit : C->private_copies()) {
2713 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2714 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2715 Data.LastprivateVars.push_back(*IRef);
2716 Data.LastprivateCopies.push_back(IInit);
2717 }
2718 LastprivateDstsOrigs.insert(
2719 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2720 cast<DeclRefExpr>(*IRef)});
2721 ++IRef;
2722 ++ID;
2723 }
2724 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002725 SmallVector<const Expr *, 4> LHSs;
2726 SmallVector<const Expr *, 4> RHSs;
2727 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2728 auto IPriv = C->privates().begin();
2729 auto IRed = C->reduction_ops().begin();
2730 auto ILHS = C->lhs_exprs().begin();
2731 auto IRHS = C->rhs_exprs().begin();
2732 for (const auto *Ref : C->varlists()) {
2733 Data.ReductionVars.emplace_back(Ref);
2734 Data.ReductionCopies.emplace_back(*IPriv);
2735 Data.ReductionOps.emplace_back(*IRed);
2736 LHSs.emplace_back(*ILHS);
2737 RHSs.emplace_back(*IRHS);
2738 std::advance(IPriv, 1);
2739 std::advance(IRed, 1);
2740 std::advance(ILHS, 1);
2741 std::advance(IRHS, 1);
2742 }
2743 }
2744 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2745 *this, S.getLocStart(), LHSs, RHSs, Data);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002746 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002747 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2748 for (auto *IRef : C->varlists())
2749 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002750 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs](
Alexey Bataevf93095a2016-05-05 08:46:22 +00002751 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002752 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002753 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002754 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2755 !Data.LastprivateVars.empty()) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002756 auto *CopyFn = CGF.Builder.CreateLoad(
2757 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2758 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2759 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2760 // Map privates.
2761 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2762 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2763 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002764 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002765 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2766 Address PrivatePtr = CGF.CreateMemTemp(
2767 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2768 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2769 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002770 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002771 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002772 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2773 Address PrivatePtr =
2774 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2775 ".firstpriv.ptr.addr");
2776 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2777 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002778 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002779 for (auto *E : Data.LastprivateVars) {
2780 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2781 Address PrivatePtr =
2782 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2783 ".lastpriv.ptr.addr");
2784 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2785 CallArgs.push_back(PrivatePtr.getPointer());
2786 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002787 CGF.EmitRuntimeCall(CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002788 for (auto &&Pair : LastprivateDstsOrigs) {
2789 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2790 DeclRefExpr DRE(
2791 const_cast<VarDecl *>(OrigVD),
2792 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2793 OrigVD) != nullptr,
2794 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2795 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2796 return CGF.EmitLValue(&DRE).getAddress();
2797 });
2798 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002799 for (auto &&Pair : PrivatePtrs) {
2800 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2801 CGF.getContext().getDeclAlign(Pair.first));
2802 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2803 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002804 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002805 if (Data.Reductions) {
2806 OMPLexicalScope LexScope(CGF, S, /*AsInlined=*/true);
2807 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2808 Data.ReductionOps);
2809 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2810 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2811 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2812 RedCG.emitSharedLValue(CGF, Cnt);
2813 RedCG.emitAggregateType(CGF, Cnt);
2814 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2815 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2816 Replacement =
2817 Address(CGF.EmitScalarConversion(
2818 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2819 CGF.getContext().getPointerType(
2820 Data.ReductionCopies[Cnt]->getType()),
2821 SourceLocation()),
2822 Replacement.getAlignment());
2823 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2824 Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2825 [Replacement]() { return Replacement; });
2826 // FIXME: This must removed once the runtime library is fixed.
2827 // Emit required threadprivate variables for
2828 // initilizer/combiner/finalizer.
2829 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2830 RedCG, Cnt);
2831 }
2832 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002833 // Privatize all private variables except for in_reduction items.
Alexey Bataev48591dd2016-04-20 04:01:36 +00002834 (void)Scope.Privatize();
Alexey Bataev88202be2017-07-27 13:20:36 +00002835 SmallVector<const Expr *, 4> InRedVars;
2836 SmallVector<const Expr *, 4> InRedPrivs;
2837 SmallVector<const Expr *, 4> InRedOps;
2838 SmallVector<const Expr *, 4> TaskgroupDescriptors;
2839 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2840 auto IPriv = C->privates().begin();
2841 auto IRed = C->reduction_ops().begin();
2842 auto ITD = C->taskgroup_descriptors().begin();
2843 for (const auto *Ref : C->varlists()) {
2844 InRedVars.emplace_back(Ref);
2845 InRedPrivs.emplace_back(*IPriv);
2846 InRedOps.emplace_back(*IRed);
2847 TaskgroupDescriptors.emplace_back(*ITD);
2848 std::advance(IPriv, 1);
2849 std::advance(IRed, 1);
2850 std::advance(ITD, 1);
2851 }
2852 }
2853 // Privatize in_reduction items here, because taskgroup descriptors must be
2854 // privatized earlier.
2855 OMPPrivateScope InRedScope(CGF);
2856 if (!InRedVars.empty()) {
2857 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2858 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2859 RedCG.emitSharedLValue(CGF, Cnt);
2860 RedCG.emitAggregateType(CGF, Cnt);
2861 // The taskgroup descriptor variable is always implicit firstprivate and
2862 // privatized already during procoessing of the firstprivates.
2863 llvm::Value *ReductionsPtr = CGF.EmitLoadOfScalar(
2864 CGF.EmitLValue(TaskgroupDescriptors[Cnt]), SourceLocation());
2865 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2866 CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2867 Replacement = Address(
2868 CGF.EmitScalarConversion(
2869 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2870 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
2871 SourceLocation()),
2872 Replacement.getAlignment());
2873 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2874 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2875 [Replacement]() { return Replacement; });
2876 // FIXME: This must removed once the runtime library is fixed.
2877 // Emit required threadprivate variables for
2878 // initilizer/combiner/finalizer.
2879 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2880 RedCG, Cnt);
2881 }
2882 }
2883 (void)InRedScope.Privatize();
Alexey Bataev48591dd2016-04-20 04:01:36 +00002884
2885 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002886 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002887 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002888 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2889 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2890 Data.NumberOfParts);
2891 OMPLexicalScope Scope(*this, S);
2892 TaskGen(*this, OutlinedFn, Data);
2893}
2894
2895void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2896 // Emit outlined function for task construct.
2897 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2898 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002899 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002900 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002901 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2902 if (C->getNameModifier() == OMPD_unknown ||
2903 C->getNameModifier() == OMPD_task) {
2904 IfCond = C->getCondition();
2905 break;
2906 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002907 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002908
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002909 OMPTaskDataTy Data;
2910 // Check if we should emit tied or untied task.
2911 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00002912 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
2913 CGF.EmitStmt(CS->getCapturedStmt());
2914 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002915 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00002916 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002917 const OMPTaskDataTy &Data) {
2918 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
2919 SharedsTy, CapturedStruct, IfCond,
2920 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00002921 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002922 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002923}
2924
Alexey Bataev9f797f32015-02-05 05:57:51 +00002925void CodeGenFunction::EmitOMPTaskyieldDirective(
2926 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002927 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002928}
2929
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002930void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002931 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002932}
2933
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002934void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2935 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002936}
2937
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002938void CodeGenFunction::EmitOMPTaskgroupDirective(
2939 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002940 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2941 Action.Enter(CGF);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002942 if (const Expr *E = S.getReductionRef()) {
2943 SmallVector<const Expr *, 4> LHSs;
2944 SmallVector<const Expr *, 4> RHSs;
2945 OMPTaskDataTy Data;
2946 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
2947 auto IPriv = C->privates().begin();
2948 auto IRed = C->reduction_ops().begin();
2949 auto ILHS = C->lhs_exprs().begin();
2950 auto IRHS = C->rhs_exprs().begin();
2951 for (const auto *Ref : C->varlists()) {
2952 Data.ReductionVars.emplace_back(Ref);
2953 Data.ReductionCopies.emplace_back(*IPriv);
2954 Data.ReductionOps.emplace_back(*IRed);
2955 LHSs.emplace_back(*ILHS);
2956 RHSs.emplace_back(*IRHS);
2957 std::advance(IPriv, 1);
2958 std::advance(IRed, 1);
2959 std::advance(ILHS, 1);
2960 std::advance(IRHS, 1);
2961 }
2962 }
2963 llvm::Value *ReductionDesc =
2964 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getLocStart(),
2965 LHSs, RHSs, Data);
2966 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2967 CGF.EmitVarDecl(*VD);
2968 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
2969 /*Volatile=*/false, E->getType());
2970 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002971 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002972 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002973 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002974 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2975}
2976
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002977void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002978 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002979 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002980 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2981 FlushClause->varlist_end());
2982 }
2983 return llvm::None;
2984 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002985}
2986
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002987void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
2988 const CodeGenLoopTy &CodeGenLoop,
2989 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002990 // Emit the loop iteration variable.
2991 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2992 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2993 EmitVarDecl(*IVDecl);
2994
2995 // Emit the iterations count variable.
2996 // If it is not a variable, Sema decided to calculate iterations count on each
2997 // iteration (e.g., it is foldable into a constant).
2998 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2999 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3000 // Emit calculation of the iterations count.
3001 EmitIgnoredExpr(S.getCalcLastIteration());
3002 }
3003
3004 auto &RT = CGM.getOpenMPRuntime();
3005
Carlo Bertolli962bb802017-01-03 18:24:42 +00003006 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003007 // Check pre-condition.
3008 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003009 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003010 // Skip the entire loop if we don't meet the precondition.
3011 // If the condition constant folds and can be elided, avoid emitting the
3012 // whole loop.
3013 bool CondConstant;
3014 llvm::BasicBlock *ContBlock = nullptr;
3015 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3016 if (!CondConstant)
3017 return;
3018 } else {
3019 auto *ThenBlock = createBasicBlock("omp.precond.then");
3020 ContBlock = createBasicBlock("omp.precond.end");
3021 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3022 getProfileCount(&S));
3023 EmitBlock(ThenBlock);
3024 incrementProfileCounter(&S);
3025 }
3026
3027 // Emit 'then' code.
3028 {
3029 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003030
3031 LValue LB = EmitOMPHelperVar(
3032 *this, cast<DeclRefExpr>(
3033 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3034 ? S.getCombinedLowerBoundVariable()
3035 : S.getLowerBoundVariable())));
3036 LValue UB = EmitOMPHelperVar(
3037 *this, cast<DeclRefExpr>(
3038 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3039 ? S.getCombinedUpperBoundVariable()
3040 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003041 LValue ST =
3042 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3043 LValue IL =
3044 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3045
3046 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003047 if (EmitOMPFirstprivateClause(S, LoopScope)) {
3048 // Emit implicit barrier to synchronize threads and avoid data races on
3049 // initialization of firstprivate variables and post-update of
3050 // lastprivate variables.
3051 CGM.getOpenMPRuntime().emitBarrierCall(
3052 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3053 /*ForceSimpleCall=*/true);
3054 }
3055 EmitOMPPrivateClause(S, LoopScope);
3056 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003057 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003058 (void)LoopScope.Privatize();
3059
3060 // Detect the distribute schedule kind and chunk.
3061 llvm::Value *Chunk = nullptr;
3062 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3063 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3064 ScheduleKind = C->getDistScheduleKind();
3065 if (const auto *Ch = C->getChunkSize()) {
3066 Chunk = EmitScalarExpr(Ch);
3067 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
3068 S.getIterationVariable()->getType(),
3069 S.getLocStart());
3070 }
3071 }
3072 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3073 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3074
3075 // OpenMP [2.10.8, distribute Construct, Description]
3076 // If dist_schedule is specified, kind must be static. If specified,
3077 // iterations are divided into chunks of size chunk_size, chunks are
3078 // assigned to the teams of the league in a round-robin fashion in the
3079 // order of the team number. When no chunk_size is specified, the
3080 // iteration space is divided into chunks that are approximately equal
3081 // in size, and at most one chunk is distributed to each team of the
3082 // league. The size of the chunks is unspecified in this case.
3083 if (RT.isStaticNonchunked(ScheduleKind,
3084 /* Chunked */ Chunk != nullptr)) {
3085 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
3086 IVSize, IVSigned, /* Ordered = */ false,
3087 IL.getAddress(), LB.getAddress(),
3088 UB.getAddress(), ST.getAddress());
3089 auto LoopExit =
3090 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3091 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003092 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3093 ? S.getCombinedEnsureUpperBound()
3094 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003095 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003096 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3097 ? S.getCombinedInit()
3098 : S.getInit());
3099
3100 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3101 ? S.getCombinedCond()
3102 : S.getCond();
3103
3104 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003105 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003106 // when combined with 'for' (e.g. as in 'distribute parallel for')
3107 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3108 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3109 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3110 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003111 },
3112 [](CodeGenFunction &) {});
3113 EmitBlock(LoopExit.getBlock());
3114 // Tell the runtime we are done.
3115 RT.emitForStaticFinish(*this, S.getLocStart());
3116 } else {
3117 // Emit the outer loop, which requests its work chunk [LB..UB] from
3118 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003119 const OMPLoopArguments LoopArguments = {
3120 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3121 Chunk};
3122 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3123 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003124 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00003125
3126 // Emit final copy of the lastprivate variables if IsLastIter != 0.
3127 if (HasLastprivateClause)
3128 EmitOMPLastprivateClauseFinal(
3129 S, /*NoFinals=*/false,
3130 Builder.CreateIsNotNull(
3131 EmitLoadOfScalar(IL, S.getLocStart())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003132 }
3133
3134 // We're now done with the loop, so jump to the continuation block.
3135 if (ContBlock) {
3136 EmitBranch(ContBlock);
3137 EmitBlock(ContBlock, true);
3138 }
3139 }
3140}
3141
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003142void CodeGenFunction::EmitOMPDistributeDirective(
3143 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003144 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003145
3146 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003147 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003148 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003149 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
3150 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003151}
3152
Alexey Bataev5f600d62015-09-29 03:48:57 +00003153static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3154 const CapturedStmt *S) {
3155 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3156 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3157 CGF.CapturedStmtInfo = &CapStmtInfo;
3158 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3159 Fn->addFnAttr(llvm::Attribute::NoInline);
3160 return Fn;
3161}
3162
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003163void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8b427062016-05-25 12:36:08 +00003164 if (!S.getAssociatedStmt()) {
3165 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3166 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003167 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003168 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003169 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003170 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3171 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003172 if (C) {
3173 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3174 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3175 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3176 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00003177 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, OutlinedFn,
3178 CapturedVars);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003179 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003180 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003181 CGF.EmitStmt(
3182 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3183 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003184 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003185 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003186 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003187}
3188
Alexey Bataevb57056f2015-01-22 06:17:56 +00003189static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003190 QualType SrcType, QualType DestType,
3191 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003192 assert(CGF.hasScalarEvaluationKind(DestType) &&
3193 "DestType must have scalar evaluation kind.");
3194 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3195 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003196 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3197 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00003198 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003199 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003200}
3201
3202static CodeGenFunction::ComplexPairTy
3203convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003204 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003205 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3206 "DestType must have complex evaluation kind.");
3207 CodeGenFunction::ComplexPairTy ComplexVal;
3208 if (Val.isScalar()) {
3209 // Convert the input element to the element type of the complex.
3210 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003211 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3212 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003213 ComplexVal = CodeGenFunction::ComplexPairTy(
3214 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3215 } else {
3216 assert(Val.isComplex() && "Must be a scalar or complex.");
3217 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3218 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3219 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003220 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003221 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003222 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003223 }
3224 return ComplexVal;
3225}
3226
Alexey Bataev5e018f92015-04-23 06:35:10 +00003227static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3228 LValue LVal, RValue RVal) {
3229 if (LVal.isGlobalReg()) {
3230 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3231 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003232 CGF.EmitAtomicStore(RVal, LVal,
3233 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3234 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003235 LVal.isVolatile(), /*IsInit=*/false);
3236 }
3237}
3238
Alexey Bataev8524d152016-01-21 12:35:58 +00003239void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3240 QualType RValTy, SourceLocation Loc) {
3241 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003242 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003243 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3244 *this, RVal, RValTy, LVal.getType(), Loc)),
3245 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003246 break;
3247 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003248 EmitStoreOfComplex(
3249 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003250 /*isInit=*/false);
3251 break;
3252 case TEK_Aggregate:
3253 llvm_unreachable("Must be a scalar or complex.");
3254 }
3255}
3256
Alexey Bataevb57056f2015-01-22 06:17:56 +00003257static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3258 const Expr *X, const Expr *V,
3259 SourceLocation Loc) {
3260 // v = x;
3261 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3262 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3263 LValue XLValue = CGF.EmitLValue(X);
3264 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003265 RValue Res = XLValue.isGlobalReg()
3266 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003267 : CGF.EmitAtomicLoad(
3268 XLValue, Loc,
3269 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3270 : llvm::AtomicOrdering::Monotonic,
3271 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003272 // OpenMP, 2.12.6, atomic Construct
3273 // Any atomic construct with a seq_cst clause forces the atomically
3274 // performed operation to include an implicit flush operation without a
3275 // list.
3276 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003277 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003278 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003279}
3280
Alexey Bataevb8329262015-02-27 06:33:30 +00003281static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3282 const Expr *X, const Expr *E,
3283 SourceLocation Loc) {
3284 // x = expr;
3285 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003286 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003287 // OpenMP, 2.12.6, atomic Construct
3288 // Any atomic construct with a seq_cst clause forces the atomically
3289 // performed operation to include an implicit flush operation without a
3290 // list.
3291 if (IsSeqCst)
3292 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3293}
3294
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003295static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3296 RValue Update,
3297 BinaryOperatorKind BO,
3298 llvm::AtomicOrdering AO,
3299 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003300 auto &Context = CGF.CGM.getContext();
3301 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003302 // expression is simple and atomic is allowed for the given type for the
3303 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003304 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003305 !Update.getScalarVal()->getType()->isIntegerTy() ||
3306 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3307 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003308 X.getAddress().getElementType())) ||
3309 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003310 !Context.getTargetInfo().hasBuiltinAtomic(
3311 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003312 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003313
3314 llvm::AtomicRMWInst::BinOp RMWOp;
3315 switch (BO) {
3316 case BO_Add:
3317 RMWOp = llvm::AtomicRMWInst::Add;
3318 break;
3319 case BO_Sub:
3320 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003321 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003322 RMWOp = llvm::AtomicRMWInst::Sub;
3323 break;
3324 case BO_And:
3325 RMWOp = llvm::AtomicRMWInst::And;
3326 break;
3327 case BO_Or:
3328 RMWOp = llvm::AtomicRMWInst::Or;
3329 break;
3330 case BO_Xor:
3331 RMWOp = llvm::AtomicRMWInst::Xor;
3332 break;
3333 case BO_LT:
3334 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3335 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3336 : llvm::AtomicRMWInst::Max)
3337 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3338 : llvm::AtomicRMWInst::UMax);
3339 break;
3340 case BO_GT:
3341 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3342 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3343 : llvm::AtomicRMWInst::Min)
3344 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3345 : llvm::AtomicRMWInst::UMin);
3346 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003347 case BO_Assign:
3348 RMWOp = llvm::AtomicRMWInst::Xchg;
3349 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003350 case BO_Mul:
3351 case BO_Div:
3352 case BO_Rem:
3353 case BO_Shl:
3354 case BO_Shr:
3355 case BO_LAnd:
3356 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003357 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003358 case BO_PtrMemD:
3359 case BO_PtrMemI:
3360 case BO_LE:
3361 case BO_GE:
3362 case BO_EQ:
3363 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003364 case BO_AddAssign:
3365 case BO_SubAssign:
3366 case BO_AndAssign:
3367 case BO_OrAssign:
3368 case BO_XorAssign:
3369 case BO_MulAssign:
3370 case BO_DivAssign:
3371 case BO_RemAssign:
3372 case BO_ShlAssign:
3373 case BO_ShrAssign:
3374 case BO_Comma:
3375 llvm_unreachable("Unsupported atomic update operation");
3376 }
3377 auto *UpdateVal = Update.getScalarVal();
3378 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3379 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003380 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003381 X.getType()->hasSignedIntegerRepresentation());
3382 }
John McCall7f416cc2015-09-08 08:05:57 +00003383 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003384 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003385}
3386
Alexey Bataev5e018f92015-04-23 06:35:10 +00003387std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003388 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3389 llvm::AtomicOrdering AO, SourceLocation Loc,
3390 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3391 // Update expressions are allowed to have the following forms:
3392 // x binop= expr; -> xrval + expr;
3393 // x++, ++x -> xrval + 1;
3394 // x--, --x -> xrval - 1;
3395 // x = x binop expr; -> xrval binop expr
3396 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003397 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3398 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003399 if (X.isGlobalReg()) {
3400 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3401 // 'xrval'.
3402 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3403 } else {
3404 // Perform compare-and-swap procedure.
3405 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003406 }
3407 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003408 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003409}
3410
3411static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3412 const Expr *X, const Expr *E,
3413 const Expr *UE, bool IsXLHSInRHSPart,
3414 SourceLocation Loc) {
3415 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3416 "Update expr in 'atomic update' must be a binary operator.");
3417 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3418 // Update expressions are allowed to have the following forms:
3419 // x binop= expr; -> xrval + expr;
3420 // x++, ++x -> xrval + 1;
3421 // x--, --x -> xrval - 1;
3422 // x = x binop expr; -> xrval binop expr
3423 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003424 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003425 LValue XLValue = CGF.EmitLValue(X);
3426 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003427 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3428 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003429 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3430 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3431 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3432 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3433 auto Gen =
3434 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3435 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3436 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3437 return CGF.EmitAnyExpr(UE);
3438 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003439 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3440 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3441 // OpenMP, 2.12.6, atomic Construct
3442 // Any atomic construct with a seq_cst clause forces the atomically
3443 // performed operation to include an implicit flush operation without a
3444 // list.
3445 if (IsSeqCst)
3446 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3447}
3448
3449static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003450 QualType SourceType, QualType ResType,
3451 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003452 switch (CGF.getEvaluationKind(ResType)) {
3453 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003454 return RValue::get(
3455 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003456 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003457 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003458 return RValue::getComplex(Res.first, Res.second);
3459 }
3460 case TEK_Aggregate:
3461 break;
3462 }
3463 llvm_unreachable("Must be a scalar or complex.");
3464}
3465
3466static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3467 bool IsPostfixUpdate, const Expr *V,
3468 const Expr *X, const Expr *E,
3469 const Expr *UE, bool IsXLHSInRHSPart,
3470 SourceLocation Loc) {
3471 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3472 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3473 RValue NewVVal;
3474 LValue VLValue = CGF.EmitLValue(V);
3475 LValue XLValue = CGF.EmitLValue(X);
3476 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003477 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3478 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003479 QualType NewVValType;
3480 if (UE) {
3481 // 'x' is updated with some additional value.
3482 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3483 "Update expr in 'atomic capture' must be a binary operator.");
3484 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3485 // Update expressions are allowed to have the following forms:
3486 // x binop= expr; -> xrval + expr;
3487 // x++, ++x -> xrval + 1;
3488 // x--, --x -> xrval - 1;
3489 // x = x binop expr; -> xrval binop expr
3490 // x = expr Op x; - > expr binop xrval;
3491 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3492 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3493 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3494 NewVValType = XRValExpr->getType();
3495 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3496 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003497 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003498 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3499 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3500 RValue Res = CGF.EmitAnyExpr(UE);
3501 NewVVal = IsPostfixUpdate ? XRValue : Res;
3502 return Res;
3503 };
3504 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3505 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3506 if (Res.first) {
3507 // 'atomicrmw' instruction was generated.
3508 if (IsPostfixUpdate) {
3509 // Use old value from 'atomicrmw'.
3510 NewVVal = Res.second;
3511 } else {
3512 // 'atomicrmw' does not provide new value, so evaluate it using old
3513 // value of 'x'.
3514 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3515 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3516 NewVVal = CGF.EmitAnyExpr(UE);
3517 }
3518 }
3519 } else {
3520 // 'x' is simply rewritten with some 'expr'.
3521 NewVValType = X->getType().getNonReferenceType();
3522 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003523 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003524 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003525 NewVVal = XRValue;
3526 return ExprRValue;
3527 };
3528 // Try to perform atomicrmw xchg, otherwise simple exchange.
3529 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3530 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3531 Loc, Gen);
3532 if (Res.first) {
3533 // 'atomicrmw' instruction was generated.
3534 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3535 }
3536 }
3537 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003538 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003539 // OpenMP, 2.12.6, atomic Construct
3540 // Any atomic construct with a seq_cst clause forces the atomically
3541 // performed operation to include an implicit flush operation without a
3542 // list.
3543 if (IsSeqCst)
3544 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3545}
3546
Alexey Bataevb57056f2015-01-22 06:17:56 +00003547static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003548 bool IsSeqCst, bool IsPostfixUpdate,
3549 const Expr *X, const Expr *V, const Expr *E,
3550 const Expr *UE, bool IsXLHSInRHSPart,
3551 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003552 switch (Kind) {
3553 case OMPC_read:
3554 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3555 break;
3556 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003557 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3558 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003559 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003560 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003561 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3562 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003563 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003564 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3565 IsXLHSInRHSPart, Loc);
3566 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003567 case OMPC_if:
3568 case OMPC_final:
3569 case OMPC_num_threads:
3570 case OMPC_private:
3571 case OMPC_firstprivate:
3572 case OMPC_lastprivate:
3573 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003574 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00003575 case OMPC_in_reduction:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003576 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003577 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003578 case OMPC_collapse:
3579 case OMPC_default:
3580 case OMPC_seq_cst:
3581 case OMPC_shared:
3582 case OMPC_linear:
3583 case OMPC_aligned:
3584 case OMPC_copyin:
3585 case OMPC_copyprivate:
3586 case OMPC_flush:
3587 case OMPC_proc_bind:
3588 case OMPC_schedule:
3589 case OMPC_ordered:
3590 case OMPC_nowait:
3591 case OMPC_untied:
3592 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003593 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003594 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003595 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003596 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003597 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003598 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003599 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003600 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003601 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003602 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003603 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003604 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003605 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003606 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003607 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003608 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003609 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003610 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003611 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003612 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003613 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3614 }
3615}
3616
3617void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003618 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003619 OpenMPClauseKind Kind = OMPC_unknown;
3620 for (auto *C : S.clauses()) {
3621 // Find first clause (skip seq_cst clause, if it is first).
3622 if (C->getClauseKind() != OMPC_seq_cst) {
3623 Kind = C->getClauseKind();
3624 break;
3625 }
3626 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003627
3628 const auto *CS =
3629 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003630 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003631 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003632 }
3633 // Processing for statements under 'atomic capture'.
3634 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3635 for (const auto *C : Compound->body()) {
3636 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3637 enterFullExpression(EWC);
3638 }
3639 }
3640 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003641
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003642 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3643 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003644 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003645 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3646 S.getV(), S.getExpr(), S.getUpdateExpr(),
3647 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003648 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003649 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003650 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003651}
3652
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003653static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3654 const OMPExecutableDirective &S,
3655 const RegionCodeGenTy &CodeGen) {
3656 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3657 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00003658 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
3659
Samuel Antaoee8fb302016-01-06 13:42:12 +00003660 llvm::Function *Fn = nullptr;
3661 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003662
Samuel Antaobed3c462015-10-02 16:14:20 +00003663 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003664 // Check for the at most one if clause associated with the target region.
3665 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3666 if (C->getNameModifier() == OMPD_unknown ||
3667 C->getNameModifier() == OMPD_target) {
3668 IfCond = C->getCondition();
3669 break;
3670 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003671 }
3672
3673 // Check if we have any device clause associated with the directive.
3674 const Expr *Device = nullptr;
3675 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3676 Device = C->getDevice();
3677 }
3678
Samuel Antaoee8fb302016-01-06 13:42:12 +00003679 // Check if we have an if clause whose conditional always evaluates to false
3680 // or if we do not have any targets specified. If so the target region is not
3681 // an offload entry point.
3682 bool IsOffloadEntry = true;
3683 if (IfCond) {
3684 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003685 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003686 IsOffloadEntry = false;
3687 }
3688 if (CGM.getLangOpts().OMPTargetTriples.empty())
3689 IsOffloadEntry = false;
3690
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003691 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003692 StringRef ParentName;
3693 // In case we have Ctors/Dtors we use the complete type variant to produce
3694 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003695 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003696 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003697 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003698 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3699 else
3700 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003701 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003702
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003703 // Emit target region as a standalone region.
3704 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3705 IsOffloadEntry, CodeGen);
3706 OMPLexicalScope Scope(CGF, S);
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003707 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3708 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003709 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003710 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003711}
3712
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003713static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3714 PrePostActionTy &Action) {
3715 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3716 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3717 CGF.EmitOMPPrivateClause(S, PrivateScope);
3718 (void)PrivateScope.Privatize();
3719
3720 Action.Enter(CGF);
3721 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3722}
3723
3724void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3725 StringRef ParentName,
3726 const OMPTargetDirective &S) {
3727 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3728 emitTargetRegion(CGF, S, Action);
3729 };
3730 llvm::Function *Fn;
3731 llvm::Constant *Addr;
3732 // Emit target region as a standalone region.
3733 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3734 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3735 assert(Fn && Addr && "Target device function emission failed.");
3736}
3737
3738void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3739 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3740 emitTargetRegion(CGF, S, Action);
3741 };
3742 emitCommonOMPTargetDirective(*this, S, CodeGen);
3743}
3744
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003745static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3746 const OMPExecutableDirective &S,
3747 OpenMPDirectiveKind InnermostKind,
3748 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003749 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
3750 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
3751 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003752
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003753 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
3754 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003755 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003756 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3757 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003758
Carlo Bertollic6872252016-04-04 15:55:02 +00003759 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3760 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003761 }
3762
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003763 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003764 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3765 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003766 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3767 CapturedVars);
3768}
3769
3770void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00003771 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003772 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003773 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003774 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3775 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003776 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003777 (void)PrivateScope.Privatize();
3778 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003779 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003780 };
3781 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003782 emitPostUpdateForReductionClause(
3783 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00003784}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003785
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003786static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
3787 const OMPTargetTeamsDirective &S) {
3788 auto *CS = S.getCapturedStmt(OMPD_teams);
3789 Action.Enter(CGF);
3790 auto &&CodeGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3791 // TODO: Add support for clauses.
3792 CGF.EmitStmt(CS->getCapturedStmt());
3793 };
3794 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
3795}
3796
3797void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
3798 CodeGenModule &CGM, StringRef ParentName,
3799 const OMPTargetTeamsDirective &S) {
3800 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3801 emitTargetTeamsRegion(CGF, Action, S);
3802 };
3803 llvm::Function *Fn;
3804 llvm::Constant *Addr;
3805 // Emit target region as a standalone region.
3806 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3807 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3808 assert(Fn && Addr && "Target device function emission failed.");
3809}
3810
3811void CodeGenFunction::EmitOMPTargetTeamsDirective(
3812 const OMPTargetTeamsDirective &S) {
3813 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3814 emitTargetTeamsRegion(CGF, Action, S);
3815 };
3816 emitCommonOMPTargetDirective(*this, S, CodeGen);
3817}
3818
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003819void CodeGenFunction::EmitOMPCancellationPointDirective(
3820 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00003821 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
3822 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003823}
3824
Alexey Bataev80909872015-07-02 11:25:17 +00003825void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003826 const Expr *IfCond = nullptr;
3827 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3828 if (C->getNameModifier() == OMPD_unknown ||
3829 C->getNameModifier() == OMPD_cancel) {
3830 IfCond = C->getCondition();
3831 break;
3832 }
3833 }
3834 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003835 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00003836}
3837
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003838CodeGenFunction::JumpDest
3839CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00003840 if (Kind == OMPD_parallel || Kind == OMPD_task ||
3841 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003842 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003843 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00003844 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
3845 Kind == OMPD_distribute_parallel_for ||
3846 Kind == OMPD_target_parallel_for);
3847 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003848}
Michael Wong65f367f2015-07-21 13:44:28 +00003849
Samuel Antaocc10b852016-07-28 14:23:26 +00003850void CodeGenFunction::EmitOMPUseDevicePtrClause(
3851 const OMPClause &NC, OMPPrivateScope &PrivateScope,
3852 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
3853 const auto &C = cast<OMPUseDevicePtrClause>(NC);
3854 auto OrigVarIt = C.varlist_begin();
3855 auto InitIt = C.inits().begin();
3856 for (auto PvtVarIt : C.private_copies()) {
3857 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
3858 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
3859 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
3860
3861 // In order to identify the right initializer we need to match the
3862 // declaration used by the mapping logic. In some cases we may get
3863 // OMPCapturedExprDecl that refers to the original declaration.
3864 const ValueDecl *MatchingVD = OrigVD;
3865 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
3866 // OMPCapturedExprDecl are used to privative fields of the current
3867 // structure.
3868 auto *ME = cast<MemberExpr>(OED->getInit());
3869 assert(isa<CXXThisExpr>(ME->getBase()) &&
3870 "Base should be the current struct!");
3871 MatchingVD = ME->getMemberDecl();
3872 }
3873
3874 // If we don't have information about the current list item, move on to
3875 // the next one.
3876 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
3877 if (InitAddrIt == CaptureDeviceAddrMap.end())
3878 continue;
3879
3880 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
3881 // Initialize the temporary initialization variable with the address we
3882 // get from the runtime library. We have to cast the source address
3883 // because it is always a void *. References are materialized in the
3884 // privatization scope, so the initialization here disregards the fact
3885 // the original variable is a reference.
3886 QualType AddrQTy =
3887 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
3888 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
3889 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
3890 setAddrOfLocalVar(InitVD, InitAddr);
3891
3892 // Emit private declaration, it will be initialized by the value we
3893 // declaration we just added to the local declarations map.
3894 EmitDecl(*PvtVD);
3895
3896 // The initialization variables reached its purpose in the emission
3897 // ofthe previous declaration, so we don't need it anymore.
3898 LocalDeclMap.erase(InitVD);
3899
3900 // Return the address of the private variable.
3901 return GetAddrOfLocalVar(PvtVD);
3902 });
3903 assert(IsRegistered && "firstprivate var already registered as private");
3904 // Silence the warning about unused variable.
3905 (void)IsRegistered;
3906
3907 ++OrigVarIt;
3908 ++InitIt;
3909 }
3910}
3911
Michael Wong65f367f2015-07-21 13:44:28 +00003912// Generate the instructions for '#pragma omp target data' directive.
3913void CodeGenFunction::EmitOMPTargetDataDirective(
3914 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00003915 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
3916
3917 // Create a pre/post action to signal the privatization of the device pointer.
3918 // This action can be replaced by the OpenMP runtime code generation to
3919 // deactivate privatization.
3920 bool PrivatizeDevicePointers = false;
3921 class DevicePointerPrivActionTy : public PrePostActionTy {
3922 bool &PrivatizeDevicePointers;
3923
3924 public:
3925 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
3926 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
3927 void Enter(CodeGenFunction &CGF) override {
3928 PrivatizeDevicePointers = true;
3929 }
Samuel Antaodf158d52016-04-27 22:58:19 +00003930 };
Samuel Antaocc10b852016-07-28 14:23:26 +00003931 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
3932
3933 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
3934 CodeGenFunction &CGF, PrePostActionTy &Action) {
3935 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3936 CGF.EmitStmt(
3937 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3938 };
3939
3940 // Codegen that selects wheather to generate the privatization code or not.
3941 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
3942 &InnermostCodeGen](CodeGenFunction &CGF,
3943 PrePostActionTy &Action) {
3944 RegionCodeGenTy RCG(InnermostCodeGen);
3945 PrivatizeDevicePointers = false;
3946
3947 // Call the pre-action to change the status of PrivatizeDevicePointers if
3948 // needed.
3949 Action.Enter(CGF);
3950
3951 if (PrivatizeDevicePointers) {
3952 OMPPrivateScope PrivateScope(CGF);
3953 // Emit all instances of the use_device_ptr clause.
3954 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
3955 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
3956 Info.CaptureDeviceAddrMap);
3957 (void)PrivateScope.Privatize();
3958 RCG(CGF);
3959 } else
3960 RCG(CGF);
3961 };
3962
3963 // Forward the provided action to the privatization codegen.
3964 RegionCodeGenTy PrivRCG(PrivCodeGen);
3965 PrivRCG.setAction(Action);
3966
3967 // Notwithstanding the body of the region is emitted as inlined directive,
3968 // we don't use an inline scope as changes in the references inside the
3969 // region are expected to be visible outside, so we do not privative them.
3970 OMPLexicalScope Scope(CGF, S);
3971 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
3972 PrivRCG);
3973 };
3974
3975 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00003976
3977 // If we don't have target devices, don't bother emitting the data mapping
3978 // code.
3979 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00003980 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00003981 return;
3982 }
3983
3984 // Check if we have any if clause associated with the directive.
3985 const Expr *IfCond = nullptr;
3986 if (auto *C = S.getSingleClause<OMPIfClause>())
3987 IfCond = C->getCondition();
3988
3989 // Check if we have any device clause associated with the directive.
3990 const Expr *Device = nullptr;
3991 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3992 Device = C->getDevice();
3993
Samuel Antaocc10b852016-07-28 14:23:26 +00003994 // Set the action to signal privatization of device pointers.
3995 RCG.setAction(PrivAction);
3996
3997 // Emit region code.
3998 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
3999 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004000}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004001
Samuel Antaodf67fc42016-01-19 19:15:56 +00004002void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4003 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004004 // If we don't have target devices, don't bother emitting the data mapping
4005 // code.
4006 if (CGM.getLangOpts().OMPTargetTriples.empty())
4007 return;
4008
4009 // Check if we have any if clause associated with the directive.
4010 const Expr *IfCond = nullptr;
4011 if (auto *C = S.getSingleClause<OMPIfClause>())
4012 IfCond = C->getCondition();
4013
4014 // Check if we have any device clause associated with the directive.
4015 const Expr *Device = nullptr;
4016 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4017 Device = C->getDevice();
4018
Samuel Antao8d2d7302016-05-26 18:30:22 +00004019 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004020}
4021
Samuel Antao72590762016-01-19 20:04:50 +00004022void CodeGenFunction::EmitOMPTargetExitDataDirective(
4023 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004024 // If we don't have target devices, don't bother emitting the data mapping
4025 // code.
4026 if (CGM.getLangOpts().OMPTargetTriples.empty())
4027 return;
4028
4029 // Check if we have any if clause associated with the directive.
4030 const Expr *IfCond = nullptr;
4031 if (auto *C = S.getSingleClause<OMPIfClause>())
4032 IfCond = C->getCondition();
4033
4034 // Check if we have any device clause associated with the directive.
4035 const Expr *Device = nullptr;
4036 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4037 Device = C->getDevice();
4038
Samuel Antao8d2d7302016-05-26 18:30:22 +00004039 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004040}
4041
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004042static void emitTargetParallelRegion(CodeGenFunction &CGF,
4043 const OMPTargetParallelDirective &S,
4044 PrePostActionTy &Action) {
4045 // Get the captured statement associated with the 'parallel' region.
4046 auto *CS = S.getCapturedStmt(OMPD_parallel);
4047 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004048 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
4049 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4050 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4051 CGF.EmitOMPPrivateClause(S, PrivateScope);
4052 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4053 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004054 // TODO: Add support for clauses.
4055 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004056 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004057 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004058 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4059 emitEmptyBoundParameters);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004060 emitPostUpdateForReductionClause(
4061 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004062}
4063
4064void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4065 CodeGenModule &CGM, StringRef ParentName,
4066 const OMPTargetParallelDirective &S) {
4067 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4068 emitTargetParallelRegion(CGF, S, Action);
4069 };
4070 llvm::Function *Fn;
4071 llvm::Constant *Addr;
4072 // Emit target region as a standalone region.
4073 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4074 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4075 assert(Fn && Addr && "Target device function emission failed.");
4076}
4077
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004078void CodeGenFunction::EmitOMPTargetParallelDirective(
4079 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004080 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4081 emitTargetParallelRegion(CGF, S, Action);
4082 };
4083 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004084}
4085
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004086void CodeGenFunction::EmitOMPTargetParallelForDirective(
4087 const OMPTargetParallelForDirective &S) {
4088 // TODO: codegen for target parallel for.
4089}
4090
Alexey Bataev7292c292016-04-25 12:22:29 +00004091/// Emit a helper variable and return corresponding lvalue.
4092static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4093 const ImplicitParamDecl *PVD,
4094 CodeGenFunction::OMPPrivateScope &Privates) {
4095 auto *VDecl = cast<VarDecl>(Helper->getDecl());
4096 Privates.addPrivate(
4097 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
4098}
4099
4100void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4101 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4102 // Emit outlined function for task construct.
4103 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
4104 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
4105 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4106 const Expr *IfCond = nullptr;
4107 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4108 if (C->getNameModifier() == OMPD_unknown ||
4109 C->getNameModifier() == OMPD_taskloop) {
4110 IfCond = C->getCondition();
4111 break;
4112 }
4113 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004114
4115 OMPTaskDataTy Data;
4116 // Check if taskloop must be emitted without taskgroup.
4117 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004118 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004119 Data.Tied = true;
4120 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004121 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4122 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004123 Data.Schedule.setInt(/*IntVal=*/false);
4124 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004125 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4126 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004127 Data.Schedule.setInt(/*IntVal=*/true);
4128 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004129 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004130
4131 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4132 // if (PreCond) {
4133 // for (IV in 0..LastIteration) BODY;
4134 // <Final counter/linear vars updates>;
4135 // }
4136 //
4137
4138 // Emit: if (PreCond) - begin.
4139 // If the condition constant folds and can be elided, avoid emitting the
4140 // whole loop.
4141 bool CondConstant;
4142 llvm::BasicBlock *ContBlock = nullptr;
4143 OMPLoopScope PreInitScope(CGF, S);
4144 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4145 if (!CondConstant)
4146 return;
4147 } else {
4148 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4149 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4150 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4151 CGF.getProfileCount(&S));
4152 CGF.EmitBlock(ThenBlock);
4153 CGF.incrementProfileCounter(&S);
4154 }
4155
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004156 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4157 CGF.EmitOMPSimdInit(S);
4158
Alexey Bataev7292c292016-04-25 12:22:29 +00004159 OMPPrivateScope LoopScope(CGF);
4160 // Emit helper vars inits.
4161 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4162 auto *I = CS->getCapturedDecl()->param_begin();
4163 auto *LBP = std::next(I, LowerBound);
4164 auto *UBP = std::next(I, UpperBound);
4165 auto *STP = std::next(I, Stride);
4166 auto *LIP = std::next(I, LastIter);
4167 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4168 LoopScope);
4169 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4170 LoopScope);
4171 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4172 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4173 LoopScope);
4174 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004175 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004176 (void)LoopScope.Privatize();
4177 // Emit the loop iteration variable.
4178 const Expr *IVExpr = S.getIterationVariable();
4179 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4180 CGF.EmitVarDecl(*IVDecl);
4181 CGF.EmitIgnoredExpr(S.getInit());
4182
4183 // Emit the iterations count variable.
4184 // If it is not a variable, Sema decided to calculate iterations count on
4185 // each iteration (e.g., it is foldable into a constant).
4186 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4187 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4188 // Emit calculation of the iterations count.
4189 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4190 }
4191
4192 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4193 S.getInc(),
4194 [&S](CodeGenFunction &CGF) {
4195 CGF.EmitOMPLoopBody(S, JumpDest());
4196 CGF.EmitStopPoint(&S);
4197 },
4198 [](CodeGenFunction &) {});
4199 // Emit: if (PreCond) - end.
4200 if (ContBlock) {
4201 CGF.EmitBranch(ContBlock);
4202 CGF.EmitBlock(ContBlock, true);
4203 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004204 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4205 if (HasLastprivateClause) {
4206 CGF.EmitOMPLastprivateClauseFinal(
4207 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4208 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4209 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4210 (*LIP)->getType(), S.getLocStart())));
4211 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004212 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004213 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4214 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4215 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004216 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4217 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004218 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4219 OutlinedFn, SharedsTy,
4220 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004221 };
4222 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4223 CodeGen);
4224 };
Alexey Bataev33446032017-07-12 18:09:32 +00004225 if (Data.Nogroup)
4226 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4227 else {
4228 CGM.getOpenMPRuntime().emitTaskgroupRegion(
4229 *this,
4230 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4231 PrePostActionTy &Action) {
4232 Action.Enter(CGF);
4233 CGF.EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4234 },
4235 S.getLocStart());
4236 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004237}
4238
Alexey Bataev49f6e782015-12-01 04:18:41 +00004239void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004240 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004241}
4242
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004243void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4244 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004245 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004246}
Samuel Antao686c70c2016-05-26 17:30:50 +00004247
4248// Generate the instructions for '#pragma omp target update' directive.
4249void CodeGenFunction::EmitOMPTargetUpdateDirective(
4250 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00004251 // If we don't have target devices, don't bother emitting the data mapping
4252 // code.
4253 if (CGM.getLangOpts().OMPTargetTriples.empty())
4254 return;
4255
4256 // Check if we have any if clause associated with the directive.
4257 const Expr *IfCond = nullptr;
4258 if (auto *C = S.getSingleClause<OMPIfClause>())
4259 IfCond = C->getCondition();
4260
4261 // Check if we have any device clause associated with the directive.
4262 const Expr *Device = nullptr;
4263 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4264 Device = C->getDevice();
4265
4266 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00004267}