blob: f738dd0750faa2f6d4af326afdf7a14c9fdf3f7b [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 Bataev2377fe92015-09-10 08:12:02 +0000242llvm::Function *
Samuel Antao6d004262016-06-16 18:39:34 +0000243CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000244 assert(
245 CapturedStmtInfo &&
246 "CapturedStmtInfo should be set when generating the captured function");
247 const CapturedDecl *CD = S.getCapturedDecl();
248 const RecordDecl *RD = S.getCapturedRecordDecl();
249 assert(CD->hasBody() && "missing CapturedDecl body");
250
251 // Build the argument list.
252 ASTContext &Ctx = CGM.getContext();
253 FunctionArgList Args;
254 Args.append(CD->param_begin(),
255 std::next(CD->param_begin(), CD->getContextParamPosition()));
256 auto I = S.captures().begin();
257 for (auto *FD : RD->fields()) {
258 QualType ArgType = FD->getType();
259 IdentifierInfo *II = nullptr;
260 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000261
262 // If this is a capture by copy and the type is not a pointer, the outlined
263 // function argument type should be uintptr and the value properly casted to
264 // uintptr. This is necessary given that the runtime library is only able to
265 // deal with pointers. We can pass in the same way the VLA type sizes to the
266 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000267 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
268 I->capturesVariableArrayType())
269 ArgType = Ctx.getUIntPtrType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000270
271 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000272 CapVar = I->getCapturedVar();
273 II = CapVar->getIdentifier();
274 } else if (I->capturesThis())
275 II = &getContext().Idents.get("this");
276 else {
277 assert(I->capturesVariableArrayType());
278 II = &getContext().Idents.get("vla");
279 }
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000280 if (ArgType->isVariablyModifiedType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000281 ArgType =
Alexey Bataevf7ce1662017-04-10 19:16:45 +0000282 getCanonicalParamType(getContext(), ArgType.getNonReferenceType());
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000283 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000284 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
285 FD->getLocation(), II, ArgType));
286 ++I;
287 }
288 Args.append(
289 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
290 CD->param_end());
291
292 // Create the function declaration.
293 FunctionType::ExtInfo ExtInfo;
294 const CGFunctionInfo &FuncInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000295 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000296 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
297
298 llvm::Function *F = llvm::Function::Create(
299 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
300 CapturedStmtInfo->getHelperName(), &CGM.getModule());
301 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
302 if (CD->isNothrow())
303 F->addFnAttr(llvm::Attribute::NoUnwind);
304
305 // Generate the function.
306 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
307 CD->getBody()->getLocStart());
308 unsigned Cnt = CD->getContextParamPosition();
309 I = S.captures().begin();
310 for (auto *FD : RD->fields()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000311 // If we are capturing a pointer by copy we don't need to do anything, just
312 // use the value that we get from the arguments.
313 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000314 const VarDecl *CurVD = I->getCapturedVar();
315 Address LocalAddr = GetAddrOfLocalVar(Args[Cnt]);
316 // If the variable is a reference we need to materialize it here.
317 if (CurVD->getType()->isReferenceType()) {
318 Address RefAddr = CreateMemTemp(CurVD->getType(), getPointerAlign(),
319 ".materialized_ref");
320 EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr, /*Volatile=*/false,
321 CurVD->getType());
322 LocalAddr = RefAddr;
323 }
324 setAddrOfLocalVar(CurVD, LocalAddr);
Richard Trieucc3949d2016-02-18 22:34:54 +0000325 ++Cnt;
326 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000327 continue;
328 }
329
Alexey Bataev2377fe92015-09-10 08:12:02 +0000330 LValue ArgLVal =
331 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
332 AlignmentSource::Decl);
333 if (FD->hasCapturedVLAType()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000334 LValue CastedArgLVal =
Samuel Antao6d004262016-06-16 18:39:34 +0000335 MakeAddrLValue(castValueFromUintptr(*this, FD->getType(),
336 Args[Cnt]->getName(), ArgLVal),
337 FD->getType(), AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000338 auto *ExprArg =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000339 EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000340 auto VAT = FD->getCapturedVLAType();
341 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
342 } else if (I->capturesVariable()) {
343 auto *Var = I->getCapturedVar();
344 QualType VarTy = Var->getType();
345 Address ArgAddr = ArgLVal.getAddress();
346 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000347 if (ArgLVal.getType()->isLValueReferenceType()) {
348 ArgAddr = EmitLoadOfReference(
349 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000350 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000351 assert(ArgLVal.getType()->isPointerType());
352 ArgAddr = EmitLoadOfPointer(
353 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
354 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000355 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000356 setAddrOfLocalVar(
357 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000358 } else if (I->capturesVariableByCopy()) {
359 assert(!FD->getType()->isAnyPointerType() &&
360 "Not expecting a captured pointer.");
361 auto *Var = I->getCapturedVar();
362 QualType VarTy = Var->getType();
Samuel Antao6d004262016-06-16 18:39:34 +0000363 setAddrOfLocalVar(Var, castValueFromUintptr(*this, FD->getType(),
364 Args[Cnt]->getName(), ArgLVal,
365 VarTy->isReferenceType()));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000366 } else {
367 // If 'this' is captured, load it into CXXThisValue.
368 assert(I->capturesThis());
369 CXXThisValue =
370 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
371 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000372 ++Cnt;
373 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000374 }
375
Serge Pavlov3a561452015-12-06 14:32:39 +0000376 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000377 CapturedStmtInfo->EmitBody(*this, CD->getBody());
378 FinishFunction(CD->getBodyRBrace());
379
380 return F;
381}
382
Alexey Bataev9959db52014-05-06 10:08:46 +0000383//===----------------------------------------------------------------------===//
384// OpenMP Directive Emission
385//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000386void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000387 Address DestAddr, Address SrcAddr, QualType OriginalType,
388 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000389 // Perform element-by-element initialization.
390 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000391
392 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000393 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000394 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
395 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
396
397 auto SrcBegin = SrcAddr.getPointer();
398 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000399 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000400 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
401 // The basic structure here is a while-do loop.
402 auto BodyBB = createBasicBlock("omp.arraycpy.body");
403 auto DoneBB = createBasicBlock("omp.arraycpy.done");
404 auto IsEmpty =
405 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
406 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000407
Alexey Bataev420d45b2015-04-14 05:11:24 +0000408 // Enter the loop body, making that address the current address.
409 auto EntryBB = Builder.GetInsertBlock();
410 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000411
412 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
413
414 llvm::PHINode *SrcElementPHI =
415 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
416 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
417 Address SrcElementCurrent =
418 Address(SrcElementPHI,
419 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
420
421 llvm::PHINode *DestElementPHI =
422 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
423 DestElementPHI->addIncoming(DestBegin, EntryBB);
424 Address DestElementCurrent =
425 Address(DestElementPHI,
426 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000427
Alexey Bataev420d45b2015-04-14 05:11:24 +0000428 // Emit copy.
429 CopyGen(DestElementCurrent, SrcElementCurrent);
430
431 // Shift the address forward by one element.
432 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000433 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000434 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000435 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000436 // Check whether we've reached the end.
437 auto Done =
438 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
439 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000440 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
441 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000442
443 // Done.
444 EmitBlock(DoneBB, /*IsFinished=*/true);
445}
446
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000447/// Check if the combiner is a call to UDR combiner and if it is so return the
448/// UDR decl used for reduction.
449static const OMPDeclareReductionDecl *
450getReductionInit(const Expr *ReductionOp) {
451 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
452 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
453 if (auto *DRE =
454 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
455 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
456 return DRD;
457 return nullptr;
458}
459
460static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
461 const OMPDeclareReductionDecl *DRD,
462 const Expr *InitOp,
463 Address Private, Address Original,
464 QualType Ty) {
465 if (DRD->getInitializer()) {
466 std::pair<llvm::Function *, llvm::Function *> Reduction =
467 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
468 auto *CE = cast<CallExpr>(InitOp);
469 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
470 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
471 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
472 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
473 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
474 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
475 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
476 [=]() -> Address { return Private; });
477 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
478 [=]() -> Address { return Original; });
479 (void)PrivateScope.Privatize();
480 RValue Func = RValue::get(Reduction.second);
481 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
482 CGF.EmitIgnoredExpr(InitOp);
483 } else {
484 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
485 auto *GV = new llvm::GlobalVariable(
486 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
487 llvm::GlobalValue::PrivateLinkage, Init, ".init");
488 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
489 RValue InitRVal;
490 switch (CGF.getEvaluationKind(Ty)) {
491 case TEK_Scalar:
492 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
493 break;
494 case TEK_Complex:
495 InitRVal =
496 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
497 break;
498 case TEK_Aggregate:
499 InitRVal = RValue::getAggregate(LV.getAddress());
500 break;
501 }
502 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
503 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
504 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
505 /*IsInitializer=*/false);
506 }
507}
508
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000509/// \brief Emit initialization of arrays of complex types.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000510/// \param DestAddr Address of the array.
511/// \param Type Type of array.
512/// \param Init Initial expression of array.
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000513/// \param SrcAddr Address of the original array.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000514static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000515 QualType Type, const Expr *Init,
516 Address SrcAddr = Address::invalid()) {
517 auto *DRD = getReductionInit(Init);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000518 // Perform element-by-element initialization.
519 QualType ElementTy;
520
521 // Drill down to the base element type on both arrays.
522 auto ArrayTy = Type->getAsArrayTypeUnsafe();
523 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
524 DestAddr =
525 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000526 if (DRD)
527 SrcAddr =
528 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000529
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000530 llvm::Value *SrcBegin = nullptr;
531 if (DRD)
532 SrcBegin = SrcAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000533 auto DestBegin = DestAddr.getPointer();
534 // Cast from pointer to array type to pointer to single element.
535 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
536 // The basic structure here is a while-do loop.
537 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
538 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
539 auto IsEmpty =
540 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
541 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
542
543 // Enter the loop body, making that address the current address.
544 auto EntryBB = CGF.Builder.GetInsertBlock();
545 CGF.EmitBlock(BodyBB);
546
547 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
548
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000549 llvm::PHINode *SrcElementPHI = nullptr;
550 Address SrcElementCurrent = Address::invalid();
551 if (DRD) {
552 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
553 "omp.arraycpy.srcElementPast");
554 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
555 SrcElementCurrent =
556 Address(SrcElementPHI,
557 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
558 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000559 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
560 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
561 DestElementPHI->addIncoming(DestBegin, EntryBB);
562 Address DestElementCurrent =
563 Address(DestElementPHI,
564 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
565
566 // Emit copy.
567 {
568 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +0000569 if (DRD && (DRD->getInitializer() || !Init)) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000570 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
571 SrcElementCurrent, ElementTy);
572 } else
573 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
574 /*IsInitializer=*/false);
575 }
576
577 if (DRD) {
578 // Shift the address forward by one element.
579 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
580 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
581 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000582 }
583
584 // Shift the address forward by one element.
585 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
586 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
587 // Check whether we've reached the end.
588 auto Done =
589 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
590 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
591 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
592
593 // Done.
594 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
595}
596
John McCall7f416cc2015-09-08 08:05:57 +0000597void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
598 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000599 const VarDecl *SrcVD, const Expr *Copy) {
600 if (OriginalType->isArrayType()) {
601 auto *BO = dyn_cast<BinaryOperator>(Copy);
602 if (BO && BO->getOpcode() == BO_Assign) {
603 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000604 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000605 } else {
606 // For arrays with complex element types perform element by element
607 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000608 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000609 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000610 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000611 // Working with the single array element, so have to remap
612 // destination and source variables to corresponding array
613 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000614 CodeGenFunction::OMPPrivateScope Remap(*this);
615 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000616 return DestElement;
617 });
618 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000619 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000620 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000621 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000622 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000623 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000624 } else {
625 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000626 CodeGenFunction::OMPPrivateScope Remap(*this);
627 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
628 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000629 (void)Remap.Privatize();
630 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000631 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000632 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000633}
634
Alexey Bataev69c62a92015-04-15 04:52:20 +0000635bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
636 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000637 if (!HaveInsertPoint())
638 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000639 bool FirstprivateIsLastprivate = false;
640 llvm::DenseSet<const VarDecl *> Lastprivates;
641 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
642 for (const auto *D : C->varlists())
643 Lastprivates.insert(
644 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
645 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000646 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000647 CGCapturedStmtInfo CapturesInfo(cast<CapturedStmt>(*D.getAssociatedStmt()));
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000648 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000649 auto IRef = C->varlist_begin();
650 auto InitsRef = C->inits().begin();
651 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000652 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000653 bool ThisFirstprivateIsLastprivate =
654 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000655 auto *CapFD = CapturesInfo.lookup(OrigVD);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000656 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9afe5752016-05-24 07:40:12 +0000657 if (!ThisFirstprivateIsLastprivate && FD && (FD == CapFD) &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000658 !FD->getType()->isReferenceType()) {
659 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
660 ++IRef;
661 ++InitsRef;
662 continue;
663 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000664 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000665 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000666 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000667 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
668 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
669 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000670 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
671 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
672 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000673 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000674 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000675 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000676 // Emit VarDecl with copy init for arrays.
677 // Get the address of the original variable captured in current
678 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000679 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000680 auto Emission = EmitAutoVarAlloca(*VD);
681 auto *Init = VD->getInit();
682 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
683 // Perform simple memcpy.
684 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000685 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000686 } else {
687 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000688 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000689 [this, VDInit, Init](Address DestElement,
690 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000691 // Clean up any temporaries needed by the initialization.
692 RunCleanupsScope InitScope(*this);
693 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000694 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000695 EmitAnyExprToMem(Init, DestElement,
696 Init->getType().getQualifiers(),
697 /*IsInitializer*/ false);
698 LocalDeclMap.erase(VDInit);
699 });
700 }
701 EmitAutoVarCleanups(Emission);
702 return Emission.getAllocatedAddress();
703 });
704 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000705 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000706 // Emit private VarDecl with copy init.
707 // Remap temp VDInit variable to the address of the original
708 // variable
709 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000710 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000711 EmitDecl(*VD);
712 LocalDeclMap.erase(VDInit);
713 return GetAddrOfLocalVar(VD);
714 });
715 }
716 assert(IsRegistered &&
717 "firstprivate var already registered as private");
718 // Silence the warning about unused variable.
719 (void)IsRegistered;
720 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000721 ++IRef;
722 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000723 }
724 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000725 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000726}
727
Alexey Bataev03b340a2014-10-21 03:16:40 +0000728void CodeGenFunction::EmitOMPPrivateClause(
729 const OMPExecutableDirective &D,
730 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000731 if (!HaveInsertPoint())
732 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000733 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000734 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000735 auto IRef = C->varlist_begin();
736 for (auto IInit : C->private_copies()) {
737 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000738 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
739 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
740 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000741 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000742 // Emit private VarDecl with copy init.
743 EmitDecl(*VD);
744 return GetAddrOfLocalVar(VD);
745 });
746 assert(IsRegistered && "private var already registered as private");
747 // Silence the warning about unused variable.
748 (void)IsRegistered;
749 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000750 ++IRef;
751 }
752 }
753}
754
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000755bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000756 if (!HaveInsertPoint())
757 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000758 // threadprivate_var1 = master_threadprivate_var1;
759 // operator=(threadprivate_var2, master_threadprivate_var2);
760 // ...
761 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000762 llvm::DenseSet<const VarDecl *> CopiedVars;
763 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000764 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000765 auto IRef = C->varlist_begin();
766 auto ISrcRef = C->source_exprs().begin();
767 auto IDestRef = C->destination_exprs().begin();
768 for (auto *AssignOp : C->assignment_ops()) {
769 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000770 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000771 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000772 // Get the address of the master variable. If we are emitting code with
773 // TLS support, the address is passed from the master as field in the
774 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000775 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000776 if (getLangOpts().OpenMPUseTLS &&
777 getContext().getTargetInfo().isTLSSupported()) {
778 assert(CapturedStmtInfo->lookup(VD) &&
779 "Copyin threadprivates should have been captured!");
780 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
781 VK_LValue, (*IRef)->getExprLoc());
782 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000783 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000784 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000785 MasterAddr =
786 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
787 : CGM.GetAddrOfGlobal(VD),
788 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000789 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000790 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000791 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000792 if (CopiedVars.size() == 1) {
793 // At first check if current thread is a master thread. If it is, no
794 // need to copy data.
795 CopyBegin = createBasicBlock("copyin.not.master");
796 CopyEnd = createBasicBlock("copyin.not.master.end");
797 Builder.CreateCondBr(
798 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000799 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
800 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000801 CopyBegin, CopyEnd);
802 EmitBlock(CopyBegin);
803 }
804 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
805 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000806 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000807 }
808 ++IRef;
809 ++ISrcRef;
810 ++IDestRef;
811 }
812 }
813 if (CopyEnd) {
814 // Exit out of copying procedure for non-master thread.
815 EmitBlock(CopyEnd, /*IsFinished=*/true);
816 return true;
817 }
818 return false;
819}
820
Alexey Bataev38e89532015-04-16 04:54:05 +0000821bool CodeGenFunction::EmitOMPLastprivateClauseInit(
822 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000823 if (!HaveInsertPoint())
824 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000825 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000826 llvm::DenseSet<const VarDecl *> SIMDLCVs;
827 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
828 auto *LoopDirective = cast<OMPLoopDirective>(&D);
829 for (auto *C : LoopDirective->counters()) {
830 SIMDLCVs.insert(
831 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
832 }
833 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000834 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000835 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000836 HasAtLeastOneLastprivate = true;
Alexey Bataevf93095a2016-05-05 08:46:22 +0000837 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()))
838 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000839 auto IRef = C->varlist_begin();
840 auto IDestRef = C->destination_exprs().begin();
841 for (auto *IInit : C->private_copies()) {
842 // Keep the address of the original variable for future update at the end
843 // of the loop.
844 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000845 // Taskloops do not require additional initialization, it is done in
846 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000847 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
848 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000849 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000850 DeclRefExpr DRE(
851 const_cast<VarDecl *>(OrigVD),
852 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
853 OrigVD) != nullptr,
854 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
855 return EmitLValue(&DRE).getAddress();
856 });
857 // Check if the variable is also a firstprivate: in this case IInit is
858 // not generated. Initialization of this variable will happen in codegen
859 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000860 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000861 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000862 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
863 // Emit private VarDecl with copy init.
864 EmitDecl(*VD);
865 return GetAddrOfLocalVar(VD);
866 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000867 assert(IsRegistered &&
868 "lastprivate var already registered as private");
869 (void)IsRegistered;
870 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000871 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000872 ++IRef;
873 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000874 }
875 }
876 return HasAtLeastOneLastprivate;
877}
878
879void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000880 const OMPExecutableDirective &D, bool NoFinals,
881 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000882 if (!HaveInsertPoint())
883 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000884 // Emit following code:
885 // if (<IsLastIterCond>) {
886 // orig_var1 = private_orig_var1;
887 // ...
888 // orig_varn = private_orig_varn;
889 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000890 llvm::BasicBlock *ThenBB = nullptr;
891 llvm::BasicBlock *DoneBB = nullptr;
892 if (IsLastIterCond) {
893 ThenBB = createBasicBlock(".omp.lastprivate.then");
894 DoneBB = createBasicBlock(".omp.lastprivate.done");
895 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
896 EmitBlock(ThenBB);
897 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000898 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
899 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000900 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000901 auto IC = LoopDirective->counters().begin();
902 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000903 auto *D =
904 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
905 if (NoFinals)
906 AlreadyEmittedVars.insert(D);
907 else
908 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000909 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000910 }
911 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000912 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
913 auto IRef = C->varlist_begin();
914 auto ISrcRef = C->source_exprs().begin();
915 auto IDestRef = C->destination_exprs().begin();
916 for (auto *AssignOp : C->assignment_ops()) {
917 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
918 QualType Type = PrivateVD->getType();
919 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
920 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
921 // If lastprivate variable is a loop control variable for loop-based
922 // directive, update its value before copyin back to original
923 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000924 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
925 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000926 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
927 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
928 // Get the address of the original variable.
929 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
930 // Get the address of the private variable.
931 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
932 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
933 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000934 Address(Builder.CreateLoad(PrivateAddr),
935 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000936 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000937 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000938 ++IRef;
939 ++ISrcRef;
940 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000941 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000942 if (auto *PostUpdate = C->getPostUpdateExpr())
943 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000944 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000945 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000946 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000947}
948
Alexey Bataev31300ed2016-02-04 11:27:03 +0000949static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
950 LValue BaseLV, llvm::Value *Addr) {
951 Address Tmp = Address::invalid();
952 Address TopTmp = Address::invalid();
953 Address MostTopTmp = Address::invalid();
954 BaseTy = BaseTy.getNonReferenceType();
955 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
956 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
957 Tmp = CGF.CreateMemTemp(BaseTy);
958 if (TopTmp.isValid())
959 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
960 else
961 MostTopTmp = Tmp;
962 TopTmp = Tmp;
963 BaseTy = BaseTy->getPointeeType();
964 }
965 llvm::Type *Ty = BaseLV.getPointer()->getType();
966 if (Tmp.isValid())
967 Ty = Tmp.getElementType();
968 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
969 if (Tmp.isValid()) {
970 CGF.Builder.CreateStore(Addr, Tmp);
971 return MostTopTmp;
972 }
973 return Address(Addr, BaseLV.getAlignment());
974}
975
976static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
977 LValue BaseLV) {
978 BaseTy = BaseTy.getNonReferenceType();
979 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
980 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
981 if (auto *PtrTy = BaseTy->getAs<PointerType>())
982 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
983 else {
984 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
985 BaseTy->castAs<ReferenceType>());
986 }
987 BaseTy = BaseTy->getPointeeType();
988 }
989 return CGF.MakeAddrLValue(
990 Address(
991 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
992 BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()),
993 BaseLV.getAlignment()),
994 BaseLV.getType(), BaseLV.getAlignmentSource());
995}
996
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000997void CodeGenFunction::EmitOMPReductionClauseInit(
998 const OMPExecutableDirective &D,
999 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001000 if (!HaveInsertPoint())
1001 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001002 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001003 auto ILHS = C->lhs_exprs().begin();
1004 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001005 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001006 auto IRed = C->reduction_ops().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001007 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001008 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001009 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
1010 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001011 auto *DRD = getReductionInit(*IRed);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001012 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
1013 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
1014 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1015 Base = TempOASE->getBase()->IgnoreParenImpCasts();
1016 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1017 Base = TempASE->getBase()->IgnoreParenImpCasts();
1018 auto *DE = cast<DeclRefExpr>(Base);
1019 auto *OrigVD = cast<VarDecl>(DE->getDecl());
1020 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
1021 auto OASELValueUB =
1022 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
1023 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +00001024 LValue BaseLValue =
1025 loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(),
1026 OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001027 // Store the address of the original variable associated with the LHS
1028 // implicit variable.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00001029 PrivateScope.addPrivate(LHSVD, [OASELValueLB]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001030 return OASELValueLB.getAddress();
1031 });
1032 // Emit reduction copy.
1033 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +00001034 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001035 OASELValueUB, OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001036 // Emit VarDecl with copy init for arrays.
1037 // Get the address of the original variable captured in current
1038 // captured region.
1039 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
1040 OASELValueLB.getPointer());
1041 Size = Builder.CreateNUWAdd(
1042 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
1043 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1044 *this, cast<OpaqueValueExpr>(
1045 getContext()
1046 .getAsVariableArrayType(PrivateVD->getType())
1047 ->getSizeExpr()),
1048 RValue::get(Size));
1049 EmitVariablyModifiedType(PrivateVD->getType());
1050 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1051 auto Addr = Emission.getAllocatedAddress();
1052 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001053 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
1054 DRD ? *IRed : Init,
1055 OASELValueLB.getAddress());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001056 EmitAutoVarCleanups(Emission);
1057 // Emit private VarDecl with reduction init.
1058 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
1059 OASELValueLB.getPointer());
1060 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +00001061 return castToBase(*this, OrigVD->getType(),
1062 OASELValueLB.getType(), OriginalBaseLValue,
1063 Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001064 });
1065 assert(IsRegistered && "private var already registered as private");
1066 // Silence the warning about unused variable.
1067 (void)IsRegistered;
1068 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1069 return GetAddrOfLocalVar(PrivateVD);
1070 });
1071 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
1072 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1073 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1074 Base = TempASE->getBase()->IgnoreParenImpCasts();
1075 auto *DE = cast<DeclRefExpr>(Base);
1076 auto *OrigVD = cast<VarDecl>(DE->getDecl());
1077 auto ASELValue = EmitLValue(ASE);
1078 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +00001079 LValue BaseLValue = loadToBegin(
1080 *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001081 // Store the address of the original variable associated with the LHS
1082 // implicit variable.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00001083 PrivateScope.addPrivate(
1084 LHSVD, [ASELValue]() -> Address { return ASELValue.getAddress(); });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001085 // Emit reduction copy.
1086 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +00001087 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001088 OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001089 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001090 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1091 auto Addr = Emission.getAllocatedAddress();
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +00001092 if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001093 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
1094 ASELValue.getAddress(),
1095 ASELValue.getType());
1096 } else
1097 EmitAutoVarInit(Emission);
1098 EmitAutoVarCleanups(Emission);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001099 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
1100 ASELValue.getPointer());
1101 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +00001102 return castToBase(*this, OrigVD->getType(), ASELValue.getType(),
1103 OriginalBaseLValue, Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001104 });
1105 assert(IsRegistered && "private var already registered as private");
1106 // Silence the warning about unused variable.
1107 (void)IsRegistered;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001108 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1109 return Builder.CreateElementBitCast(
1110 GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
1111 "rhs.begin");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001112 });
1113 } else {
1114 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
Alexey Bataev1189bd02016-01-26 12:20:39 +00001115 QualType Type = PrivateVD->getType();
1116 if (getContext().getAsArrayType(Type)) {
1117 // Store the address of the original variable associated with the LHS
1118 // implicit variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001119 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1120 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1121 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataev1189bd02016-01-26 12:20:39 +00001122 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001123 PrivateScope.addPrivate(LHSVD, [this, &OriginalAddr,
Alexey Bataev1189bd02016-01-26 12:20:39 +00001124 LHSVD]() -> Address {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001125 OriginalAddr = Builder.CreateElementBitCast(
1126 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1127 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001128 });
1129 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
1130 if (Type->isVariablyModifiedType()) {
1131 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1132 *this, cast<OpaqueValueExpr>(
1133 getContext()
1134 .getAsVariableArrayType(PrivateVD->getType())
1135 ->getSizeExpr()),
1136 RValue::get(
1137 getTypeSize(OrigVD->getType().getNonReferenceType())));
1138 EmitVariablyModifiedType(Type);
1139 }
1140 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1141 auto Addr = Emission.getAllocatedAddress();
1142 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001143 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
1144 DRD ? *IRed : Init, OriginalAddr);
Alexey Bataev1189bd02016-01-26 12:20:39 +00001145 EmitAutoVarCleanups(Emission);
1146 return Emission.getAllocatedAddress();
1147 });
1148 assert(IsRegistered && "private var already registered as private");
1149 // Silence the warning about unused variable.
1150 (void)IsRegistered;
1151 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1152 return Builder.CreateElementBitCast(
1153 GetAddrOfLocalVar(PrivateVD),
1154 ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
1155 });
1156 } else {
1157 // Store the address of the original variable associated with the LHS
1158 // implicit variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001159 Address OriginalAddr = Address::invalid();
1160 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef,
1161 &OriginalAddr]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001162 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1163 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1164 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001165 OriginalAddr = EmitLValue(&DRE).getAddress();
1166 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001167 });
1168 // Emit reduction copy.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001169 bool IsRegistered = PrivateScope.addPrivate(
1170 OrigVD, [this, PrivateVD, OriginalAddr, DRD, IRed]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001171 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001172 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1173 auto Addr = Emission.getAllocatedAddress();
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +00001174 if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001175 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
1176 OriginalAddr,
1177 PrivateVD->getType());
1178 } else
1179 EmitAutoVarInit(Emission);
1180 EmitAutoVarCleanups(Emission);
1181 return Addr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001182 });
1183 assert(IsRegistered && "private var already registered as private");
1184 // Silence the warning about unused variable.
1185 (void)IsRegistered;
1186 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1187 return GetAddrOfLocalVar(PrivateVD);
1188 });
1189 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001190 }
Richard Trieucc3949d2016-02-18 22:34:54 +00001191 ++ILHS;
1192 ++IRHS;
1193 ++IPriv;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001194 ++IRed;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001195 }
1196 }
1197}
1198
1199void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001200 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001201 if (!HaveInsertPoint())
1202 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001203 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001204 llvm::SmallVector<const Expr *, 8> LHSExprs;
1205 llvm::SmallVector<const Expr *, 8> RHSExprs;
1206 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001207 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001208 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001209 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001210 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001211 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1212 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1213 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1214 }
1215 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001216 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1217 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1218 D.getDirectiveKind() == OMPD_simd;
1219 bool SimpleReduction = D.getDirectiveKind() == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001220 // Emit nowait reduction if nowait clause is present or directive is a
1221 // parallel directive (it always has implicit barrier).
1222 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001223 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001224 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001225 }
1226}
1227
Alexey Bataev61205072016-03-02 04:57:40 +00001228static void emitPostUpdateForReductionClause(
1229 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1230 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1231 if (!CGF.HaveInsertPoint())
1232 return;
1233 llvm::BasicBlock *DoneBB = nullptr;
1234 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1235 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1236 if (!DoneBB) {
1237 if (auto *Cond = CondGen(CGF)) {
1238 // If the first post-update expression is found, emit conditional
1239 // block if it was requested.
1240 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1241 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1242 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1243 CGF.EmitBlock(ThenBB);
1244 }
1245 }
1246 CGF.EmitIgnoredExpr(PostUpdate);
1247 }
1248 }
1249 if (DoneBB)
1250 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1251}
1252
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001253namespace {
1254/// Codegen lambda for appending distribute lower and upper bounds to outlined
1255/// parallel function. This is necessary for combined constructs such as
1256/// 'distribute parallel for'
1257typedef llvm::function_ref<void(CodeGenFunction &,
1258 const OMPExecutableDirective &,
1259 llvm::SmallVectorImpl<llvm::Value *> &)>
1260 CodeGenBoundParametersTy;
1261} // anonymous namespace
1262
1263static void emitCommonOMPParallelDirective(
1264 CodeGenFunction &CGF, const OMPExecutableDirective &S,
1265 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1266 const CodeGenBoundParametersTy &CodeGenBoundParameters) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001267 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1268 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1269 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001270 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001271 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001272 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1273 /*IgnoreResultAssign*/ true);
1274 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1275 CGF, NumThreads, NumThreadsClause->getLocStart());
1276 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001277 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001278 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001279 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1280 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1281 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001282 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001283 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1284 if (C->getNameModifier() == OMPD_unknown ||
1285 C->getNameModifier() == OMPD_parallel) {
1286 IfCond = C->getCondition();
1287 break;
1288 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001289 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001290
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001291 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001292 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001293 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1294 // lower and upper bounds with the pragma 'for' chunking mechanism.
1295 // The following lambda takes care of appending the lower and upper bound
1296 // parameters when necessary
1297 CodeGenBoundParameters(CGF, S, CapturedVars);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001298 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001299 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001300 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001301}
1302
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001303static void emitEmptyBoundParameters(CodeGenFunction &,
1304 const OMPExecutableDirective &,
1305 llvm::SmallVectorImpl<llvm::Value *> &) {}
1306
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001307void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001308 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001309 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001310 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001311 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001312 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1313 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001314 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001315 // propagation master's thread values of threadprivate variables to local
1316 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001317 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1318 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1319 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001320 }
1321 CGF.EmitOMPPrivateClause(S, PrivateScope);
1322 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1323 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001324 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001325 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001326 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001327 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1328 emitEmptyBoundParameters);
Alexey Bataev61205072016-03-02 04:57:40 +00001329 emitPostUpdateForReductionClause(
1330 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001331}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001332
Alexey Bataev0f34da12015-07-02 04:17:07 +00001333void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1334 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001335 RunCleanupsScope BodyScope(*this);
1336 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001337 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001338 EmitIgnoredExpr(I);
1339 }
Alexander Musman3276a272015-03-21 10:12:56 +00001340 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001341 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001342 for (auto *U : C->updates())
Alexander Musman3276a272015-03-21 10:12:56 +00001343 EmitIgnoredExpr(U);
Alexander Musman3276a272015-03-21 10:12:56 +00001344 }
1345
Alexander Musmana5f070a2014-10-01 06:03:56 +00001346 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001347 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001348 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001349 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001350 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001351 // The end (updates/cleanups).
1352 EmitBlock(Continue.getBlock());
1353 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001354}
1355
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001356void CodeGenFunction::EmitOMPInnerLoop(
1357 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1358 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001359 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1360 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001361 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001362
1363 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001364 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001365 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001366 const SourceRange &R = S.getSourceRange();
1367 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1368 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001369
1370 // If there are any cleanups between here and the loop-exit scope,
1371 // create a block to stage a loop exit along.
1372 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001373 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001374 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001375
Alexander Musmand196ef22014-10-07 08:57:09 +00001376 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001377
Alexey Bataev2df54a02015-03-12 08:53:29 +00001378 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001379 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001380 if (ExitBlock != LoopExit.getBlock()) {
1381 EmitBlock(ExitBlock);
1382 EmitBranchThroughCleanup(LoopExit);
1383 }
1384
1385 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001386 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001387
1388 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001389 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001390 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1391
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001392 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001393
1394 // Emit "IV = IV + 1" and a back-edge to the condition block.
1395 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001396 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001397 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001398 BreakContinueStack.pop_back();
1399 EmitBranch(CondBlock);
1400 LoopStack.pop();
1401 // Emit the fall-through block.
1402 EmitBlock(LoopExit.getBlock());
1403}
1404
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001405void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001406 if (!HaveInsertPoint())
1407 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001408 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001409 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001410 for (auto *Init : C->inits()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001411 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001412 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1413 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1414 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1415 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1416 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1417 VD->getInit()->getType(), VK_LValue,
1418 VD->getInit()->getExprLoc());
1419 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1420 VD->getType()),
1421 /*capturedByInit=*/false);
1422 EmitAutoVarCleanups(Emission);
1423 } else
1424 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001425 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001426 // Emit the linear steps for the linear clauses.
1427 // If a step is not constant, it is pre-calculated before the loop.
1428 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1429 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001430 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001431 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001432 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001433 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001434 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001435}
1436
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001437void CodeGenFunction::EmitOMPLinearClauseFinal(
1438 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001439 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001440 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001441 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001442 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001443 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001444 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001445 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001446 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001447 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001448 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001449 // If the first post-update expression is found, emit conditional
1450 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001451 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1452 DoneBB = createBasicBlock(".omp.linear.pu.done");
1453 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1454 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001455 }
1456 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001457 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1458 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001459 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001460 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001461 Address OrigAddr = EmitLValue(&DRE).getAddress();
1462 CodeGenFunction::OMPPrivateScope VarScope(*this);
1463 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001464 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001465 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001466 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001467 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001468 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001469 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001470 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001471 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001472 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001473}
1474
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001475static void emitAlignedClause(CodeGenFunction &CGF,
1476 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001477 if (!CGF.HaveInsertPoint())
1478 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001479 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001480 unsigned ClauseAlignment = 0;
1481 if (auto AlignmentExpr = Clause->getAlignment()) {
1482 auto AlignmentCI =
1483 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1484 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001485 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001486 for (auto E : Clause->varlists()) {
1487 unsigned Alignment = ClauseAlignment;
1488 if (Alignment == 0) {
1489 // OpenMP [2.8.1, Description]
1490 // If no optional parameter is specified, implementation-defined default
1491 // alignments for SIMD instructions on the target platforms are assumed.
1492 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001493 CGF.getContext()
1494 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1495 E->getType()->getPointeeType()))
1496 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001497 }
1498 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1499 "alignment is not power of 2");
1500 if (Alignment != 0) {
1501 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1502 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1503 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001504 }
1505 }
1506}
1507
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001508void CodeGenFunction::EmitOMPPrivateLoopCounters(
1509 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1510 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001511 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001512 auto I = S.private_counters().begin();
1513 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001514 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1515 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001516 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001517 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001518 if (!LocalDeclMap.count(PrivateVD)) {
1519 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1520 EmitAutoVarCleanups(VarEmission);
1521 }
1522 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1523 /*RefersToEnclosingVariableOrCapture=*/false,
1524 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1525 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001526 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001527 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1528 VD->hasGlobalStorage()) {
1529 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1530 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1531 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1532 E->getType(), VK_LValue, E->getExprLoc());
1533 return EmitLValue(&DRE).getAddress();
1534 });
1535 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001536 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001537 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001538}
1539
Alexey Bataev62dbb972015-04-22 11:59:37 +00001540static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1541 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1542 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001543 if (!CGF.HaveInsertPoint())
1544 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001545 {
1546 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001547 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001548 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001549 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001550 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001551 CGF.EmitIgnoredExpr(I);
1552 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001553 }
1554 // Check that loop is executed at least one time.
1555 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1556}
1557
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001558void CodeGenFunction::EmitOMPLinearClause(
1559 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1560 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001561 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001562 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1563 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1564 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1565 for (auto *C : LoopDirective->counters()) {
1566 SIMDLCVs.insert(
1567 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1568 }
1569 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001570 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001571 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001572 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001573 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1574 auto *PrivateVD =
1575 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001576 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1577 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1578 // Emit private VarDecl with copy init.
1579 EmitVarDecl(*PrivateVD);
1580 return GetAddrOfLocalVar(PrivateVD);
1581 });
1582 assert(IsRegistered && "linear var already registered as private");
1583 // Silence the warning about unused variable.
1584 (void)IsRegistered;
1585 } else
1586 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001587 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001588 }
1589 }
1590}
1591
Alexey Bataev45bfad52015-08-21 12:19:04 +00001592static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001593 const OMPExecutableDirective &D,
1594 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001595 if (!CGF.HaveInsertPoint())
1596 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001597 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001598 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1599 /*ignoreResult=*/true);
1600 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1601 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1602 // In presence of finite 'safelen', it may be unsafe to mark all
1603 // the memory instructions parallel, because loop-carried
1604 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001605 if (!IsMonotonic)
1606 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001607 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001608 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1609 /*ignoreResult=*/true);
1610 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001611 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001612 // In presence of finite 'safelen', it may be unsafe to mark all
1613 // the memory instructions parallel, because loop-carried
1614 // dependences of 'safelen' iterations are possible.
1615 CGF.LoopStack.setParallel(false);
1616 }
1617}
1618
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001619void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1620 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001621 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001622 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001623 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001624 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001625}
1626
Alexey Bataevef549a82016-03-09 09:49:09 +00001627void CodeGenFunction::EmitOMPSimdFinal(
1628 const OMPLoopDirective &D,
1629 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001630 if (!HaveInsertPoint())
1631 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001632 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001633 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001634 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001635 for (auto F : D.finals()) {
1636 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001637 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1638 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1639 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1640 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001641 if (!DoneBB) {
1642 if (auto *Cond = CondGen(*this)) {
1643 // If the first post-update expression is found, emit conditional
1644 // block if it was requested.
1645 auto *ThenBB = createBasicBlock(".omp.final.then");
1646 DoneBB = createBasicBlock(".omp.final.done");
1647 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1648 EmitBlock(ThenBB);
1649 }
1650 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001651 Address OrigAddr = Address::invalid();
1652 if (CED)
1653 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1654 else {
1655 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1656 /*RefersToEnclosingVariableOrCapture=*/false,
1657 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1658 OrigAddr = EmitLValue(&DRE).getAddress();
1659 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001660 OMPPrivateScope VarScope(*this);
1661 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001662 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001663 (void)VarScope.Privatize();
1664 EmitIgnoredExpr(F);
1665 }
1666 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001667 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001668 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001669 if (DoneBB)
1670 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001671}
1672
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001673static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1674 const OMPLoopDirective &S,
1675 CodeGenFunction::JumpDest LoopExit) {
1676 CGF.EmitOMPLoopBody(S, LoopExit);
1677 CGF.EmitStopPoint(&S);
1678};
1679
Alexander Musman515ad8c2014-05-22 08:54:05 +00001680void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001681 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00001682 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001683 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001684 // for (IV in 0..LastIteration) BODY;
1685 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001686 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001687 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001688
Alexey Bataev62dbb972015-04-22 11:59:37 +00001689 // Emit: if (PreCond) - begin.
1690 // If the condition constant folds and can be elided, avoid emitting the
1691 // whole loop.
1692 bool CondConstant;
1693 llvm::BasicBlock *ContBlock = nullptr;
1694 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1695 if (!CondConstant)
1696 return;
1697 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001698 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1699 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001700 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1701 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001702 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001703 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001704 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001705
1706 // Emit the loop iteration variable.
1707 const Expr *IVExpr = S.getIterationVariable();
1708 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1709 CGF.EmitVarDecl(*IVDecl);
1710 CGF.EmitIgnoredExpr(S.getInit());
1711
1712 // Emit the iterations count variable.
1713 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001714 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001715 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1716 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1717 // Emit calculation of the iterations count.
1718 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001719 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001720
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001721 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001722
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001723 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001724 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001725 {
1726 OMPPrivateScope LoopScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001727 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1728 CGF.EmitOMPLinearClause(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001729 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001730 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001731 bool HasLastprivateClause =
1732 CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001733 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001734 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1735 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001736 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001737 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001738 CGF.EmitStopPoint(&S);
1739 },
1740 [](CodeGenFunction &) {});
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001741 CGF.EmitOMPSimdFinal(
1742 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001743 // Emit final copy of the lastprivate variables at the end of loops.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001744 if (HasLastprivateClause)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001745 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001746 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
Alexey Bataev61205072016-03-02 04:57:40 +00001747 emitPostUpdateForReductionClause(
1748 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001749 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001750 CGF.EmitOMPLinearClauseFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001751 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001752 // Emit: if (PreCond) - end.
1753 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001754 CGF.EmitBranch(ContBlock);
1755 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001756 }
1757 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00001758 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001759 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001760}
1761
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001762void CodeGenFunction::EmitOMPOuterLoop(
1763 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1764 CodeGenFunction::OMPPrivateScope &LoopScope,
1765 const CodeGenFunction::OMPLoopArguments &LoopArgs,
1766 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1767 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001768 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001769
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001770 const Expr *IVExpr = S.getIterationVariable();
1771 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1772 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1773
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001774 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1775
1776 // Start the loop with a block that tests the condition.
1777 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1778 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001779 const SourceRange &R = S.getSourceRange();
1780 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1781 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001782
1783 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001784 if (!DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001785 // UB = min(UB, GlobalUB) or
1786 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1787 // 'distribute parallel for')
1788 EmitIgnoredExpr(LoopArgs.EUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001789 // IV = LB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001790 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001791 // IV < UB
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001792 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001793 } else {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001794 BoolCondVal =
1795 RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1796 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001797 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001798
1799 // If there are any cleanups between here and the loop-exit scope,
1800 // create a block to stage a loop exit along.
1801 auto ExitBlock = LoopExit.getBlock();
1802 if (LoopScope.requiresCleanups())
1803 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1804
1805 auto LoopBody = createBasicBlock("omp.dispatch.body");
1806 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1807 if (ExitBlock != LoopExit.getBlock()) {
1808 EmitBlock(ExitBlock);
1809 EmitBranchThroughCleanup(LoopExit);
1810 }
1811 EmitBlock(LoopBody);
1812
Alexander Musman92bdaab2015-03-12 13:37:50 +00001813 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1814 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001815 if (DynamicOrOrdered)
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001816 EmitIgnoredExpr(LoopArgs.Init);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001817
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001818 // Create a block for the increment.
1819 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1820 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1821
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001822 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1823 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001824 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1825 LoopStack.setParallel(!IsMonotonic);
1826 else
1827 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001828
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001829 SourceLocation Loc = S.getLocStart();
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001830
1831 // when 'distribute' is not combined with a 'for':
1832 // while (idx <= UB) { BODY; ++idx; }
1833 // when 'distribute' is combined with a 'for'
1834 // (e.g. 'distribute parallel for')
1835 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1836 EmitOMPInnerLoop(
1837 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1838 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1839 CodeGenLoop(CGF, S, LoopExit);
1840 },
1841 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1842 CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1843 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001844
1845 EmitBlock(Continue.getBlock());
1846 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001847 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001848 // Emit "LB = LB + Stride", "UB = UB + Stride".
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001849 EmitIgnoredExpr(LoopArgs.NextLB);
1850 EmitIgnoredExpr(LoopArgs.NextUB);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001851 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001852
1853 EmitBranch(CondBlock);
1854 LoopStack.pop();
1855 // Emit the fall-through block.
1856 EmitBlock(LoopExit.getBlock());
1857
1858 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001859 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1860 if (!DynamicOrOrdered)
1861 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
1862 };
1863 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001864}
1865
1866void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001867 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001868 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001869 const OMPLoopArguments &LoopArgs,
1870 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001871 auto &RT = CGM.getOpenMPRuntime();
1872
1873 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001874 const bool DynamicOrOrdered =
1875 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001876
1877 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001878 !RT.isStaticNonchunked(ScheduleKind.Schedule,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001879 LoopArgs.Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001880 "static non-chunked schedule does not need outer loop");
1881
1882 // Emit outer loop.
1883 //
1884 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1885 // When schedule(dynamic,chunk_size) is specified, the iterations are
1886 // distributed to threads in the team in chunks as the threads request them.
1887 // Each thread executes a chunk of iterations, then requests another chunk,
1888 // until no chunks remain to be distributed. Each chunk contains chunk_size
1889 // iterations, except for the last chunk to be distributed, which may have
1890 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1891 //
1892 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1893 // to threads in the team in chunks as the executing threads request them.
1894 // Each thread executes a chunk of iterations, then requests another chunk,
1895 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1896 // each chunk is proportional to the number of unassigned iterations divided
1897 // by the number of threads in the team, decreasing to 1. For a chunk_size
1898 // with value k (greater than 1), the size of each chunk is determined in the
1899 // same way, with the restriction that the chunks do not contain fewer than k
1900 // iterations (except for the last chunk to be assigned, which may have fewer
1901 // than k iterations).
1902 //
1903 // When schedule(auto) is specified, the decision regarding scheduling is
1904 // delegated to the compiler and/or runtime system. The programmer gives the
1905 // implementation the freedom to choose any possible mapping of iterations to
1906 // threads in the team.
1907 //
1908 // When schedule(runtime) is specified, the decision regarding scheduling is
1909 // deferred until run time, and the schedule and chunk size are taken from the
1910 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1911 // implementation defined
1912 //
1913 // while(__kmpc_dispatch_next(&LB, &UB)) {
1914 // idx = LB;
1915 // while (idx <= UB) { BODY; ++idx;
1916 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1917 // } // inner loop
1918 // }
1919 //
1920 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1921 // When schedule(static, chunk_size) is specified, iterations are divided into
1922 // chunks of size chunk_size, and the chunks are assigned to the threads in
1923 // the team in a round-robin fashion in the order of the thread number.
1924 //
1925 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1926 // while (idx <= UB) { BODY; ++idx; } // inner loop
1927 // LB = LB + ST;
1928 // UB = UB + ST;
1929 // }
1930 //
1931
1932 const Expr *IVExpr = S.getIterationVariable();
1933 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1934 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1935
1936 if (DynamicOrOrdered) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001937 auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1938 llvm::Value *LBVal = DispatchBounds.first;
1939 llvm::Value *UBVal = DispatchBounds.second;
1940 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1941 LoopArgs.Chunk};
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001942 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001943 IVSigned, Ordered, DipatchRTInputValues);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001944 } else {
1945 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001946 Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1947 LoopArgs.ST, LoopArgs.Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001948 }
1949
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001950 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1951 const unsigned IVSize,
1952 const bool IVSigned) {
1953 if (Ordered) {
1954 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1955 IVSigned);
1956 }
1957 };
1958
1959 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1960 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1961 OuterLoopArgs.IncExpr = S.getInc();
1962 OuterLoopArgs.Init = S.getInit();
1963 OuterLoopArgs.Cond = S.getCond();
1964 OuterLoopArgs.NextLB = S.getNextLowerBound();
1965 OuterLoopArgs.NextUB = S.getNextUpperBound();
1966 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1967 emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001968}
1969
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001970static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1971 const unsigned IVSize, const bool IVSigned) {}
1972
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001973void CodeGenFunction::EmitOMPDistributeOuterLoop(
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001974 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1975 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1976 const CodeGenLoopTy &CodeGenLoopContent) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001977
1978 auto &RT = CGM.getOpenMPRuntime();
1979
1980 // Emit outer loop.
1981 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1982 // dynamic
1983 //
1984
1985 const Expr *IVExpr = S.getIterationVariable();
1986 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1987 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1988
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001989 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize,
1990 IVSigned, /* Ordered = */ false, LoopArgs.IL,
1991 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1992 LoopArgs.Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001993
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00001994 // for combined 'distribute' and 'for' the increment expression of distribute
1995 // is store in DistInc. For 'distribute' alone, it is in Inc.
1996 Expr *IncExpr;
1997 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1998 IncExpr = S.getDistInc();
1999 else
2000 IncExpr = S.getInc();
2001
2002 // this routine is shared by 'omp distribute parallel for' and
2003 // 'omp distribute': select the right EUB expression depending on the
2004 // directive
2005 OMPLoopArguments OuterLoopArgs;
2006 OuterLoopArgs.LB = LoopArgs.LB;
2007 OuterLoopArgs.UB = LoopArgs.UB;
2008 OuterLoopArgs.ST = LoopArgs.ST;
2009 OuterLoopArgs.IL = LoopArgs.IL;
2010 OuterLoopArgs.Chunk = LoopArgs.Chunk;
2011 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2012 ? S.getCombinedEnsureUpperBound()
2013 : S.getEnsureUpperBound();
2014 OuterLoopArgs.IncExpr = IncExpr;
2015 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2016 ? S.getCombinedInit()
2017 : S.getInit();
2018 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2019 ? S.getCombinedCond()
2020 : S.getCond();
2021 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2022 ? S.getCombinedNextLowerBound()
2023 : S.getNextLowerBound();
2024 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2025 ? S.getCombinedNextUpperBound()
2026 : S.getNextUpperBound();
2027
2028 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
2029 LoopScope, OuterLoopArgs, CodeGenLoopContent,
2030 emitEmptyOrdered);
2031}
2032
2033/// Emit a helper variable and return corresponding lvalue.
2034static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
2035 const DeclRefExpr *Helper) {
2036 auto VDecl = cast<VarDecl>(Helper->getDecl());
2037 CGF.EmitVarDecl(*VDecl);
2038 return CGF.EmitLValue(Helper);
2039}
2040
2041static std::pair<LValue, LValue>
2042emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
2043 const OMPExecutableDirective &S) {
2044 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2045 LValue LB =
2046 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2047 LValue UB =
2048 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2049
2050 // When composing 'distribute' with 'for' (e.g. as in 'distribute
2051 // parallel for') we need to use the 'distribute'
2052 // chunk lower and upper bounds rather than the whole loop iteration
2053 // space. These are parameters to the outlined function for 'parallel'
2054 // and we copy the bounds of the previous schedule into the
2055 // the current ones.
2056 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
2057 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
2058 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(PrevLB, SourceLocation());
2059 PrevLBVal = CGF.EmitScalarConversion(
2060 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
2061 LS.getIterationVariable()->getType(), SourceLocation());
2062 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(PrevUB, SourceLocation());
2063 PrevUBVal = CGF.EmitScalarConversion(
2064 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
2065 LS.getIterationVariable()->getType(), SourceLocation());
2066
2067 CGF.EmitStoreOfScalar(PrevLBVal, LB);
2068 CGF.EmitStoreOfScalar(PrevUBVal, UB);
2069
2070 return {LB, UB};
2071}
2072
2073/// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
2074/// we need to use the LB and UB expressions generated by the worksharing
2075/// code generation support, whereas in non combined situations we would
2076/// just emit 0 and the LastIteration expression
2077/// This function is necessary due to the difference of the LB and UB
2078/// types for the RT emission routines for 'for_static_init' and
2079/// 'for_dispatch_init'
2080static std::pair<llvm::Value *, llvm::Value *>
2081emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
2082 const OMPExecutableDirective &S,
2083 Address LB, Address UB) {
2084 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2085 const Expr *IVExpr = LS.getIterationVariable();
2086 // when implementing a dynamic schedule for a 'for' combined with a
2087 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
2088 // is not normalized as each team only executes its own assigned
2089 // distribute chunk
2090 QualType IteratorTy = IVExpr->getType();
2091 llvm::Value *LBVal = CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy,
2092 SourceLocation());
2093 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy,
2094 SourceLocation());
2095 return {LBVal, UBVal};
2096};
2097
2098static void emitDistributeParallelForDistributeInnerBoundParams(
2099 CodeGenFunction &CGF, const OMPExecutableDirective &S,
2100 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2101 const auto &Dir = cast<OMPLoopDirective>(S);
2102 LValue LB =
2103 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
2104 auto LBCast = CGF.Builder.CreateIntCast(
2105 CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2106 CapturedVars.push_back(LBCast);
2107 LValue UB =
2108 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2109
2110 auto UBCast = CGF.Builder.CreateIntCast(
2111 CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2112 CapturedVars.push_back(UBCast);
2113};
2114
2115static void
2116emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2117 const OMPLoopDirective &S,
2118 CodeGenFunction::JumpDest LoopExit) {
2119 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
2120 PrePostActionTy &) {
2121 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2122 emitDistributeParallelForInnerBounds,
2123 emitDistributeParallelForDispatchBounds);
2124 };
2125
2126 emitCommonOMPParallelDirective(
2127 CGF, S, OMPD_for, CGInlinedWorksharingLoop,
2128 emitDistributeParallelForDistributeInnerBoundParams);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002129}
2130
Carlo Bertolli9925f152016-06-27 14:55:37 +00002131void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2132 const OMPDistributeParallelForDirective &S) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002133 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2134 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2135 S.getDistInc());
2136 };
Carlo Bertolli9925f152016-06-27 14:55:37 +00002137 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002138 OMPCancelStackRAII CancelRegion(*this, OMPD_distribute_parallel_for,
2139 /*HasCancel=*/false);
2140 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
2141 /*HasCancel=*/false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002142}
2143
Kelvin Li4a39add2016-07-05 05:00:15 +00002144void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2145 const OMPDistributeParallelForSimdDirective &S) {
2146 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2147 CGM.getOpenMPRuntime().emitInlinedDirective(
2148 *this, OMPD_distribute_parallel_for_simd,
2149 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2150 OMPLoopScope PreInitScope(CGF, S);
2151 CGF.EmitStmt(
2152 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2153 });
2154}
Kelvin Li787f3fc2016-07-06 04:45:38 +00002155
2156void CodeGenFunction::EmitOMPDistributeSimdDirective(
2157 const OMPDistributeSimdDirective &S) {
2158 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2159 CGM.getOpenMPRuntime().emitInlinedDirective(
2160 *this, OMPD_distribute_simd,
2161 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2162 OMPLoopScope PreInitScope(CGF, S);
2163 CGF.EmitStmt(
2164 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2165 });
2166}
2167
Kelvin Lia579b912016-07-14 02:54:56 +00002168void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
2169 const OMPTargetParallelForSimdDirective &S) {
2170 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2171 CGM.getOpenMPRuntime().emitInlinedDirective(
2172 *this, OMPD_target_parallel_for_simd,
2173 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2174 OMPLoopScope PreInitScope(CGF, S);
2175 CGF.EmitStmt(
2176 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2177 });
2178}
2179
Kelvin Li986330c2016-07-20 22:57:10 +00002180void CodeGenFunction::EmitOMPTargetSimdDirective(
2181 const OMPTargetSimdDirective &S) {
2182 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2183 CGM.getOpenMPRuntime().emitInlinedDirective(
2184 *this, OMPD_target_simd, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2185 OMPLoopScope PreInitScope(CGF, S);
2186 CGF.EmitStmt(
2187 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2188 });
2189}
2190
Kelvin Li02532872016-08-05 14:37:37 +00002191void CodeGenFunction::EmitOMPTeamsDistributeDirective(
2192 const OMPTeamsDistributeDirective &S) {
2193 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2194 CGM.getOpenMPRuntime().emitInlinedDirective(
2195 *this, OMPD_teams_distribute,
2196 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2197 OMPLoopScope PreInitScope(CGF, S);
2198 CGF.EmitStmt(
2199 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2200 });
2201}
2202
Kelvin Li4e325f72016-10-25 12:50:55 +00002203void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
2204 const OMPTeamsDistributeSimdDirective &S) {
2205 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2206 CGM.getOpenMPRuntime().emitInlinedDirective(
2207 *this, OMPD_teams_distribute_simd,
2208 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2209 OMPLoopScope PreInitScope(CGF, S);
2210 CGF.EmitStmt(
2211 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2212 });
2213}
2214
Kelvin Li579e41c2016-11-30 23:51:03 +00002215void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
2216 const OMPTeamsDistributeParallelForSimdDirective &S) {
2217 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2218 CGM.getOpenMPRuntime().emitInlinedDirective(
2219 *this, OMPD_teams_distribute_parallel_for_simd,
2220 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2221 OMPLoopScope PreInitScope(CGF, S);
2222 CGF.EmitStmt(
2223 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2224 });
2225}
Kelvin Li4e325f72016-10-25 12:50:55 +00002226
Kelvin Li7ade93f2016-12-09 03:24:30 +00002227void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
2228 const OMPTeamsDistributeParallelForDirective &S) {
2229 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2230 CGM.getOpenMPRuntime().emitInlinedDirective(
2231 *this, OMPD_teams_distribute_parallel_for,
2232 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2233 OMPLoopScope PreInitScope(CGF, S);
2234 CGF.EmitStmt(
2235 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2236 });
2237}
2238
Kelvin Li83c451e2016-12-25 04:52:54 +00002239void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
2240 const OMPTargetTeamsDistributeDirective &S) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002241 CGM.getOpenMPRuntime().emitInlinedDirective(
2242 *this, OMPD_target_teams_distribute,
Kelvin Li83c451e2016-12-25 04:52:54 +00002243 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002244 CGF.EmitStmt(
2245 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Kelvin Li83c451e2016-12-25 04:52:54 +00002246 });
2247}
2248
Kelvin Li80e8f562016-12-29 22:16:30 +00002249void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
2250 const OMPTargetTeamsDistributeParallelForDirective &S) {
2251 CGM.getOpenMPRuntime().emitInlinedDirective(
2252 *this, OMPD_target_teams_distribute_parallel_for,
2253 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2254 CGF.EmitStmt(
2255 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2256 });
2257}
2258
Kelvin Li1851df52017-01-03 05:23:48 +00002259void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2260 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
2261 CGM.getOpenMPRuntime().emitInlinedDirective(
2262 *this, OMPD_target_teams_distribute_parallel_for_simd,
2263 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2264 CGF.EmitStmt(
2265 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2266 });
2267}
2268
Kelvin Lida681182017-01-10 18:08:18 +00002269void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
2270 const OMPTargetTeamsDistributeSimdDirective &S) {
2271 CGM.getOpenMPRuntime().emitInlinedDirective(
2272 *this, OMPD_target_teams_distribute_simd,
2273 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2274 CGF.EmitStmt(
2275 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2276 });
2277}
2278
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002279namespace {
2280 struct ScheduleKindModifiersTy {
2281 OpenMPScheduleClauseKind Kind;
2282 OpenMPScheduleClauseModifier M1;
2283 OpenMPScheduleClauseModifier M2;
2284 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2285 OpenMPScheduleClauseModifier M1,
2286 OpenMPScheduleClauseModifier M2)
2287 : Kind(Kind), M1(M1), M2(M2) {}
2288 };
2289} // namespace
2290
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002291bool CodeGenFunction::EmitOMPWorksharingLoop(
2292 const OMPLoopDirective &S, Expr *EUB,
2293 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2294 const CodeGenDispatchBoundsTy &CGDispatchBounds) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002295 // Emit the loop iteration variable.
2296 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2297 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2298 EmitVarDecl(*IVDecl);
2299
2300 // Emit the iterations count variable.
2301 // If it is not a variable, Sema decided to calculate iterations count on each
2302 // iteration (e.g., it is foldable into a constant).
2303 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2304 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2305 // Emit calculation of the iterations count.
2306 EmitIgnoredExpr(S.getCalcLastIteration());
2307 }
2308
2309 auto &RT = CGM.getOpenMPRuntime();
2310
Alexey Bataev38e89532015-04-16 04:54:05 +00002311 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002312 // Check pre-condition.
2313 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002314 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002315 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002316 // If the condition constant folds and can be elided, avoid emitting the
2317 // whole loop.
2318 bool CondConstant;
2319 llvm::BasicBlock *ContBlock = nullptr;
2320 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2321 if (!CondConstant)
2322 return false;
2323 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002324 auto *ThenBlock = createBasicBlock("omp.precond.then");
2325 ContBlock = createBasicBlock("omp.precond.end");
2326 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002327 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002328 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002329 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002330 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002331
Alexey Bataev8b427062016-05-25 12:36:08 +00002332 bool Ordered = false;
2333 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2334 if (OrderedClause->getNumForLoops())
2335 RT.emitDoacrossInit(*this, S);
2336 else
2337 Ordered = true;
2338 }
2339
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002340 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002341 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002342 EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002343 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002344
2345 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2346 LValue LB = Bounds.first;
2347 LValue UB = Bounds.second;
Alexey Bataevef549a82016-03-09 09:49:09 +00002348 LValue ST =
2349 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2350 LValue IL =
2351 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2352
Alexander Musmanc6388682014-12-15 07:07:06 +00002353 // Emit 'then' code.
2354 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002355 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002356 if (EmitOMPFirstprivateClause(S, LoopScope)) {
2357 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002358 // initialization of firstprivate variables and post-update of
2359 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002360 CGM.getOpenMPRuntime().emitBarrierCall(
2361 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2362 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002363 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002364 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002365 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002366 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002367 EmitOMPPrivateLoopCounters(S, LoopScope);
2368 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002369 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002370
2371 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002372 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002373 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002374 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002375 ScheduleKind.Schedule = C->getScheduleKind();
2376 ScheduleKind.M1 = C->getFirstScheduleModifier();
2377 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002378 if (const auto *Ch = C->getChunkSize()) {
2379 Chunk = EmitScalarExpr(Ch);
2380 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2381 S.getIterationVariable()->getType(),
2382 S.getLocStart());
2383 }
2384 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002385 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2386 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002387 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2388 // If the static schedule kind is specified or if the ordered clause is
2389 // specified, and if no monotonic modifier is specified, the effect will
2390 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002391 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002392 /* Chunked */ Chunk != nullptr) &&
2393 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002394 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2395 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002396 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2397 // When no chunk_size is specified, the iteration space is divided into
2398 // chunks that are approximately equal in size, and at most one chunk is
2399 // distributed to each thread. Note that the size of the chunks is
2400 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00002401 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
2402 IVSize, IVSigned, Ordered,
2403 IL.getAddress(), LB.getAddress(),
2404 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002405 auto LoopExit =
2406 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002407 // UB = min(UB, GlobalUB);
2408 EmitIgnoredExpr(S.getEnsureUpperBound());
2409 // IV = LB;
2410 EmitIgnoredExpr(S.getInit());
2411 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002412 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2413 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002414 [&S, LoopExit](CodeGenFunction &CGF) {
2415 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002416 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002417 },
2418 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002419 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002420 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002421 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2422 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
2423 };
2424 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002425 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002426 const bool IsMonotonic =
2427 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2428 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2429 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2430 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002431 // Emit the outer loop, which requests its work chunk [LB..UB] from
2432 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002433 const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2434 ST.getAddress(), IL.getAddress(),
2435 Chunk, EUB);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002436 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002437 LoopArguments, CGDispatchBounds);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002438 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002439 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2440 EmitOMPSimdFinal(S,
2441 [&](CodeGenFunction &CGF) -> llvm::Value * {
2442 return CGF.Builder.CreateIsNotNull(
2443 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2444 });
2445 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002446 EmitOMPReductionClauseFinal(
2447 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2448 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2449 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002450 // Emit post-update of the reduction variables if IsLastIter != 0.
2451 emitPostUpdateForReductionClause(
2452 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2453 return CGF.Builder.CreateIsNotNull(
2454 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2455 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002456 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2457 if (HasLastprivateClause)
2458 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002459 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2460 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002461 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002462 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002463 return CGF.Builder.CreateIsNotNull(
2464 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2465 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002466 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002467 if (ContBlock) {
2468 EmitBranch(ContBlock);
2469 EmitBlock(ContBlock, true);
2470 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002471 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002472 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002473}
2474
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002475/// The following two functions generate expressions for the loop lower
2476/// and upper bounds in case of static and dynamic (dispatch) schedule
2477/// of the associated 'for' or 'distribute' loop.
2478static std::pair<LValue, LValue>
2479emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2480 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2481 LValue LB =
2482 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2483 LValue UB =
2484 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2485 return {LB, UB};
2486}
2487
2488/// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2489/// consider the lower and upper bound expressions generated by the
2490/// worksharing loop support, but we use 0 and the iteration space size as
2491/// constants
2492static std::pair<llvm::Value *, llvm::Value *>
2493emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2494 Address LB, Address UB) {
2495 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2496 const Expr *IVExpr = LS.getIterationVariable();
2497 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2498 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2499 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2500 return {LBVal, UBVal};
2501}
2502
Alexander Musmanc6388682014-12-15 07:07:06 +00002503void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002504 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002505 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2506 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002507 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002508 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2509 emitForLoopBounds,
2510 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002511 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002512 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002513 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002514 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2515 S.hasCancel());
2516 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002517
2518 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002519 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002520 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2521 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002522}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002523
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002524void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002525 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002526 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2527 PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002528 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2529 emitForLoopBounds,
2530 emitDispatchForLoopBounds);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002531 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002532 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002533 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002534 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2535 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002536
2537 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002538 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002539 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2540 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002541}
2542
Alexey Bataev2df54a02015-03-12 08:53:29 +00002543static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2544 const Twine &Name,
2545 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002546 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002547 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002548 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002549 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002550}
2551
Alexey Bataev3392d762016-02-16 11:18:12 +00002552void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00002553 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2554 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002555 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002556 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2557 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002558 auto &C = CGF.CGM.getContext();
2559 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2560 // Emit helper vars inits.
2561 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2562 CGF.Builder.getInt32(0));
2563 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2564 : CGF.Builder.getInt32(0);
2565 LValue UB =
2566 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2567 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2568 CGF.Builder.getInt32(1));
2569 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2570 CGF.Builder.getInt32(0));
2571 // Loop counter.
2572 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2573 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2574 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2575 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2576 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2577 // Generate condition for loop.
2578 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002579 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002580 // Increment for loop counter.
2581 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2582 S.getLocStart());
2583 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2584 // Iterate through all sections and emit a switch construct:
2585 // switch (IV) {
2586 // case 0:
2587 // <SectionStmt[0]>;
2588 // break;
2589 // ...
2590 // case <NumSection> - 1:
2591 // <SectionStmt[<NumSection> - 1]>;
2592 // break;
2593 // }
2594 // .omp.sections.exit:
2595 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2596 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2597 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2598 CS == nullptr ? 1 : CS->size());
2599 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002600 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002601 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002602 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2603 CGF.EmitBlock(CaseBB);
2604 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002605 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002606 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002607 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002608 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002609 } else {
2610 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2611 CGF.EmitBlock(CaseBB);
2612 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2613 CGF.EmitStmt(Stmt);
2614 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002615 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002616 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002617 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002618
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002619 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2620 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002621 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002622 // initialization of firstprivate variables and post-update of lastprivate
2623 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002624 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2625 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2626 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002627 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002628 CGF.EmitOMPPrivateClause(S, LoopScope);
2629 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2630 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2631 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002632
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002633 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002634 OpenMPScheduleTy ScheduleKind;
2635 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002636 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002637 CGF, S.getLocStart(), ScheduleKind, /*IVSize=*/32,
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002638 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
2639 UB.getAddress(), ST.getAddress());
2640 // UB = min(UB, GlobalUB);
2641 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2642 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2643 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2644 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2645 // IV = LB;
2646 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2647 // while (idx <= UB) { BODY; ++idx; }
2648 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2649 [](CodeGenFunction &) {});
2650 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002651 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2652 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
2653 };
2654 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002655 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002656 // Emit post-update of the reduction variables if IsLastIter != 0.
2657 emitPostUpdateForReductionClause(
2658 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2659 return CGF.Builder.CreateIsNotNull(
2660 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2661 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002662
2663 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2664 if (HasLastprivates)
2665 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002666 S, /*NoFinals=*/false,
2667 CGF.Builder.CreateIsNotNull(
2668 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002669 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002670
2671 bool HasCancel = false;
2672 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2673 HasCancel = OSD->hasCancel();
2674 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2675 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002676 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002677 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2678 HasCancel);
2679 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2680 // clause. Otherwise the barrier will be generated by the codegen for the
2681 // directive.
2682 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002683 // Emit implicit barrier to synchronize threads and avoid data races on
2684 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002685 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2686 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002687 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002688}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002689
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002690void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002691 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002692 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002693 EmitSections(S);
2694 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002695 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002696 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002697 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2698 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002699 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002700}
2701
2702void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002703 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002704 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002705 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002706 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002707 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2708 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002709}
2710
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002711void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002712 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002713 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002714 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002715 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002716 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002717 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002718 // Build a list of copyprivate variables along with helper expressions
2719 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002720 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002721 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002722 DestExprs.append(C->destination_exprs().begin(),
2723 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002724 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002725 AssignmentOps.append(C->assignment_ops().begin(),
2726 C->assignment_ops().end());
2727 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002728 // Emit code for 'single' region along with 'copyprivate' clauses
2729 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2730 Action.Enter(CGF);
2731 OMPPrivateScope SingleScope(CGF);
2732 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2733 CGF.EmitOMPPrivateClause(S, SingleScope);
2734 (void)SingleScope.Privatize();
2735 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2736 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002737 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002738 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002739 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2740 CopyprivateVars, DestExprs,
2741 SrcExprs, AssignmentOps);
2742 }
2743 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2744 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002745 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002746 CGM.getOpenMPRuntime().emitBarrierCall(
2747 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002748 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002749 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002750}
2751
Alexey Bataev8d690652014-12-04 07:23:53 +00002752void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002753 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2754 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002755 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002756 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002757 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002758 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002759}
2760
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002761void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002762 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2763 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002764 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002765 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002766 Expr *Hint = nullptr;
2767 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2768 Hint = HintClause->getHint();
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002769 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002770 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2771 S.getDirectiveName().getAsString(),
2772 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002773}
2774
Alexey Bataev671605e2015-04-13 05:28:11 +00002775void CodeGenFunction::EmitOMPParallelForDirective(
2776 const OMPParallelForDirective &S) {
2777 // Emit directive as a combined directive that consists of two implicit
2778 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002779 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002780 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002781 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2782 emitDispatchForLoopBounds);
Alexey Bataev671605e2015-04-13 05:28:11 +00002783 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002784 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2785 emitEmptyBoundParameters);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002786}
2787
Alexander Musmane4e893b2014-09-23 09:33:00 +00002788void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002789 const OMPParallelForSimdDirective &S) {
2790 // Emit directive as a combined directive that consists of two implicit
2791 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002792 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002793 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2794 emitDispatchForLoopBounds);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002795 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002796 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2797 emitEmptyBoundParameters);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002798}
2799
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002800void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002801 const OMPParallelSectionsDirective &S) {
2802 // Emit directive as a combined directive that consists of two implicit
2803 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002804 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2805 CGF.EmitSections(S);
2806 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002807 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2808 emitEmptyBoundParameters);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002809}
2810
Alexey Bataev7292c292016-04-25 12:22:29 +00002811void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2812 const RegionCodeGenTy &BodyGen,
2813 const TaskGenTy &TaskGen,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002814 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002815 // Emit outlined function for task construct.
2816 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002817 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002818 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002819 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002820 // Check if the task is final
2821 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2822 // If the condition constant folds and can be elided, try to avoid emitting
2823 // the condition and the dead arm of the if/else.
2824 auto *Cond = Clause->getCondition();
2825 bool CondConstant;
2826 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2827 Data.Final.setInt(CondConstant);
2828 else
2829 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2830 } else {
2831 // By default the task is not final.
2832 Data.Final.setInt(/*IntVal=*/false);
2833 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002834 // Check if the task has 'priority' clause.
2835 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002836 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002837 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002838 Data.Priority.setPointer(EmitScalarConversion(
2839 EmitScalarExpr(Prio), Prio->getType(),
2840 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2841 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002842 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002843 // The first function argument for tasks is a thread id, the second one is a
2844 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002845 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2846 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002847 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002848 auto IRef = C->varlist_begin();
2849 for (auto *IInit : C->private_copies()) {
2850 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2851 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002852 Data.PrivateVars.push_back(*IRef);
2853 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002854 }
2855 ++IRef;
2856 }
2857 }
2858 EmittedAsPrivate.clear();
2859 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002860 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002861 auto IRef = C->varlist_begin();
2862 auto IElemInitRef = C->inits().begin();
2863 for (auto *IInit : C->private_copies()) {
2864 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2865 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002866 Data.FirstprivateVars.push_back(*IRef);
2867 Data.FirstprivateCopies.push_back(IInit);
2868 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002869 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002870 ++IRef;
2871 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002872 }
2873 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002874 // Get list of lastprivate variables (for taskloops).
2875 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2876 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2877 auto IRef = C->varlist_begin();
2878 auto ID = C->destination_exprs().begin();
2879 for (auto *IInit : C->private_copies()) {
2880 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2881 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2882 Data.LastprivateVars.push_back(*IRef);
2883 Data.LastprivateCopies.push_back(IInit);
2884 }
2885 LastprivateDstsOrigs.insert(
2886 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2887 cast<DeclRefExpr>(*IRef)});
2888 ++IRef;
2889 ++ID;
2890 }
2891 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002892 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002893 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2894 for (auto *IRef : C->varlists())
2895 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00002896 auto &&CodeGen = [&Data, CS, &BodyGen, &LastprivateDstsOrigs](
Alexey Bataevf93095a2016-05-05 08:46:22 +00002897 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002898 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002899 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002900 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2901 !Data.LastprivateVars.empty()) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002902 auto *CopyFn = CGF.Builder.CreateLoad(
2903 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2904 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2905 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2906 // Map privates.
2907 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2908 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2909 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002910 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002911 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2912 Address PrivatePtr = CGF.CreateMemTemp(
2913 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2914 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2915 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002916 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002917 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002918 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2919 Address PrivatePtr =
2920 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2921 ".firstpriv.ptr.addr");
2922 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2923 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002924 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002925 for (auto *E : Data.LastprivateVars) {
2926 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2927 Address PrivatePtr =
2928 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2929 ".lastpriv.ptr.addr");
2930 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2931 CallArgs.push_back(PrivatePtr.getPointer());
2932 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002933 CGF.EmitRuntimeCall(CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002934 for (auto &&Pair : LastprivateDstsOrigs) {
2935 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2936 DeclRefExpr DRE(
2937 const_cast<VarDecl *>(OrigVD),
2938 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2939 OrigVD) != nullptr,
2940 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2941 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2942 return CGF.EmitLValue(&DRE).getAddress();
2943 });
2944 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002945 for (auto &&Pair : PrivatePtrs) {
2946 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2947 CGF.getContext().getDeclAlign(Pair.first));
2948 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2949 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002950 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002951 (void)Scope.Privatize();
2952
2953 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002954 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002955 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002956 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2957 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2958 Data.NumberOfParts);
2959 OMPLexicalScope Scope(*this, S);
2960 TaskGen(*this, OutlinedFn, Data);
2961}
2962
2963void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2964 // Emit outlined function for task construct.
2965 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2966 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002967 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002968 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002969 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2970 if (C->getNameModifier() == OMPD_unknown ||
2971 C->getNameModifier() == OMPD_task) {
2972 IfCond = C->getCondition();
2973 break;
2974 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002975 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002976
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002977 OMPTaskDataTy Data;
2978 // Check if we should emit tied or untied task.
2979 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00002980 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
2981 CGF.EmitStmt(CS->getCapturedStmt());
2982 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002983 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00002984 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002985 const OMPTaskDataTy &Data) {
2986 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
2987 SharedsTy, CapturedStruct, IfCond,
2988 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00002989 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002990 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002991}
2992
Alexey Bataev9f797f32015-02-05 05:57:51 +00002993void CodeGenFunction::EmitOMPTaskyieldDirective(
2994 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002995 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002996}
2997
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002998void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002999 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003000}
3001
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003002void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
3003 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00003004}
3005
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003006void CodeGenFunction::EmitOMPTaskgroupDirective(
3007 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003008 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3009 Action.Enter(CGF);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003010 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003011 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003012 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003013 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
3014}
3015
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003016void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003017 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003018 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003019 return llvm::makeArrayRef(FlushClause->varlist_begin(),
3020 FlushClause->varlist_end());
3021 }
3022 return llvm::None;
3023 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00003024}
3025
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003026void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3027 const CodeGenLoopTy &CodeGenLoop,
3028 Expr *IncExpr) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003029 // Emit the loop iteration variable.
3030 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3031 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
3032 EmitVarDecl(*IVDecl);
3033
3034 // Emit the iterations count variable.
3035 // If it is not a variable, Sema decided to calculate iterations count on each
3036 // iteration (e.g., it is foldable into a constant).
3037 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3038 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3039 // Emit calculation of the iterations count.
3040 EmitIgnoredExpr(S.getCalcLastIteration());
3041 }
3042
3043 auto &RT = CGM.getOpenMPRuntime();
3044
Carlo Bertolli962bb802017-01-03 18:24:42 +00003045 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003046 // Check pre-condition.
3047 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003048 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003049 // Skip the entire loop if we don't meet the precondition.
3050 // If the condition constant folds and can be elided, avoid emitting the
3051 // whole loop.
3052 bool CondConstant;
3053 llvm::BasicBlock *ContBlock = nullptr;
3054 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3055 if (!CondConstant)
3056 return;
3057 } else {
3058 auto *ThenBlock = createBasicBlock("omp.precond.then");
3059 ContBlock = createBasicBlock("omp.precond.end");
3060 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3061 getProfileCount(&S));
3062 EmitBlock(ThenBlock);
3063 incrementProfileCounter(&S);
3064 }
3065
3066 // Emit 'then' code.
3067 {
3068 // Emit helper vars inits.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003069
3070 LValue LB = EmitOMPHelperVar(
3071 *this, cast<DeclRefExpr>(
3072 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3073 ? S.getCombinedLowerBoundVariable()
3074 : S.getLowerBoundVariable())));
3075 LValue UB = EmitOMPHelperVar(
3076 *this, cast<DeclRefExpr>(
3077 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3078 ? S.getCombinedUpperBoundVariable()
3079 : S.getUpperBoundVariable())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003080 LValue ST =
3081 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3082 LValue IL =
3083 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3084
3085 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00003086 if (EmitOMPFirstprivateClause(S, LoopScope)) {
3087 // Emit implicit barrier to synchronize threads and avoid data races on
3088 // initialization of firstprivate variables and post-update of
3089 // lastprivate variables.
3090 CGM.getOpenMPRuntime().emitBarrierCall(
3091 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3092 /*ForceSimpleCall=*/true);
3093 }
3094 EmitOMPPrivateClause(S, LoopScope);
3095 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003096 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003097 (void)LoopScope.Privatize();
3098
3099 // Detect the distribute schedule kind and chunk.
3100 llvm::Value *Chunk = nullptr;
3101 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3102 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3103 ScheduleKind = C->getDistScheduleKind();
3104 if (const auto *Ch = C->getChunkSize()) {
3105 Chunk = EmitScalarExpr(Ch);
3106 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
3107 S.getIterationVariable()->getType(),
3108 S.getLocStart());
3109 }
3110 }
3111 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3112 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3113
3114 // OpenMP [2.10.8, distribute Construct, Description]
3115 // If dist_schedule is specified, kind must be static. If specified,
3116 // iterations are divided into chunks of size chunk_size, chunks are
3117 // assigned to the teams of the league in a round-robin fashion in the
3118 // order of the team number. When no chunk_size is specified, the
3119 // iteration space is divided into chunks that are approximately equal
3120 // in size, and at most one chunk is distributed to each team of the
3121 // league. The size of the chunks is unspecified in this case.
3122 if (RT.isStaticNonchunked(ScheduleKind,
3123 /* Chunked */ Chunk != nullptr)) {
3124 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
3125 IVSize, IVSigned, /* Ordered = */ false,
3126 IL.getAddress(), LB.getAddress(),
3127 UB.getAddress(), ST.getAddress());
3128 auto LoopExit =
3129 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3130 // UB = min(UB, GlobalUB);
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003131 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3132 ? S.getCombinedEnsureUpperBound()
3133 : S.getEnsureUpperBound());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003134 // IV = LB;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003135 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3136 ? S.getCombinedInit()
3137 : S.getInit());
3138
3139 Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3140 ? S.getCombinedCond()
3141 : S.getCond();
3142
3143 // for distribute alone, codegen
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003144 // while (idx <= UB) { BODY; ++idx; }
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003145 // when combined with 'for' (e.g. as in 'distribute parallel for')
3146 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3147 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3148 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3149 CodeGenLoop(CGF, S, LoopExit);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003150 },
3151 [](CodeGenFunction &) {});
3152 EmitBlock(LoopExit.getBlock());
3153 // Tell the runtime we are done.
3154 RT.emitForStaticFinish(*this, S.getLocStart());
3155 } else {
3156 // Emit the outer loop, which requests its work chunk [LB..UB] from
3157 // runtime and runs the inner loop to process it.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003158 const OMPLoopArguments LoopArguments = {
3159 LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3160 Chunk};
3161 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3162 CodeGenLoop);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003163 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00003164
3165 // Emit final copy of the lastprivate variables if IsLastIter != 0.
3166 if (HasLastprivateClause)
3167 EmitOMPLastprivateClauseFinal(
3168 S, /*NoFinals=*/false,
3169 Builder.CreateIsNotNull(
3170 EmitLoadOfScalar(IL, S.getLocStart())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003171 }
3172
3173 // We're now done with the loop, so jump to the continuation block.
3174 if (ContBlock) {
3175 EmitBranch(ContBlock);
3176 EmitBlock(ContBlock, true);
3177 }
3178 }
3179}
3180
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003181void CodeGenFunction::EmitOMPDistributeDirective(
3182 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003183 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003184
3185 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003186 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003187 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003188 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
3189 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003190}
3191
Alexey Bataev5f600d62015-09-29 03:48:57 +00003192static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3193 const CapturedStmt *S) {
3194 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3195 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3196 CGF.CapturedStmtInfo = &CapStmtInfo;
3197 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3198 Fn->addFnAttr(llvm::Attribute::NoInline);
3199 return Fn;
3200}
3201
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003202void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8b427062016-05-25 12:36:08 +00003203 if (!S.getAssociatedStmt()) {
3204 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3205 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00003206 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00003207 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003208 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003209 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3210 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00003211 if (C) {
3212 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3213 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3214 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3215 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
3216 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
3217 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003218 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003219 CGF.EmitStmt(
3220 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3221 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003222 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003223 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev5f600d62015-09-29 03:48:57 +00003224 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003225}
3226
Alexey Bataevb57056f2015-01-22 06:17:56 +00003227static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003228 QualType SrcType, QualType DestType,
3229 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003230 assert(CGF.hasScalarEvaluationKind(DestType) &&
3231 "DestType must have scalar evaluation kind.");
3232 assert(!Val.isAggregate() && "Must be a scalar or complex.");
3233 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003234 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3235 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00003236 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003237 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003238}
3239
3240static CodeGenFunction::ComplexPairTy
3241convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003242 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003243 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3244 "DestType must have complex evaluation kind.");
3245 CodeGenFunction::ComplexPairTy ComplexVal;
3246 if (Val.isScalar()) {
3247 // Convert the input element to the element type of the complex.
3248 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003249 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3250 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003251 ComplexVal = CodeGenFunction::ComplexPairTy(
3252 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3253 } else {
3254 assert(Val.isComplex() && "Must be a scalar or complex.");
3255 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3256 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3257 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003258 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003259 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003260 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003261 }
3262 return ComplexVal;
3263}
3264
Alexey Bataev5e018f92015-04-23 06:35:10 +00003265static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3266 LValue LVal, RValue RVal) {
3267 if (LVal.isGlobalReg()) {
3268 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3269 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003270 CGF.EmitAtomicStore(RVal, LVal,
3271 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3272 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003273 LVal.isVolatile(), /*IsInit=*/false);
3274 }
3275}
3276
Alexey Bataev8524d152016-01-21 12:35:58 +00003277void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3278 QualType RValTy, SourceLocation Loc) {
3279 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003280 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003281 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3282 *this, RVal, RValTy, LVal.getType(), Loc)),
3283 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003284 break;
3285 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003286 EmitStoreOfComplex(
3287 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003288 /*isInit=*/false);
3289 break;
3290 case TEK_Aggregate:
3291 llvm_unreachable("Must be a scalar or complex.");
3292 }
3293}
3294
Alexey Bataevb57056f2015-01-22 06:17:56 +00003295static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3296 const Expr *X, const Expr *V,
3297 SourceLocation Loc) {
3298 // v = x;
3299 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3300 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3301 LValue XLValue = CGF.EmitLValue(X);
3302 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003303 RValue Res = XLValue.isGlobalReg()
3304 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003305 : CGF.EmitAtomicLoad(
3306 XLValue, Loc,
3307 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3308 : llvm::AtomicOrdering::Monotonic,
3309 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003310 // OpenMP, 2.12.6, atomic Construct
3311 // Any atomic construct with a seq_cst clause forces the atomically
3312 // performed operation to include an implicit flush operation without a
3313 // list.
3314 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003315 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003316 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003317}
3318
Alexey Bataevb8329262015-02-27 06:33:30 +00003319static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3320 const Expr *X, const Expr *E,
3321 SourceLocation Loc) {
3322 // x = expr;
3323 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003324 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003325 // OpenMP, 2.12.6, atomic Construct
3326 // Any atomic construct with a seq_cst clause forces the atomically
3327 // performed operation to include an implicit flush operation without a
3328 // list.
3329 if (IsSeqCst)
3330 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3331}
3332
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003333static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3334 RValue Update,
3335 BinaryOperatorKind BO,
3336 llvm::AtomicOrdering AO,
3337 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003338 auto &Context = CGF.CGM.getContext();
3339 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003340 // expression is simple and atomic is allowed for the given type for the
3341 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003342 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003343 !Update.getScalarVal()->getType()->isIntegerTy() ||
3344 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3345 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003346 X.getAddress().getElementType())) ||
3347 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003348 !Context.getTargetInfo().hasBuiltinAtomic(
3349 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003350 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003351
3352 llvm::AtomicRMWInst::BinOp RMWOp;
3353 switch (BO) {
3354 case BO_Add:
3355 RMWOp = llvm::AtomicRMWInst::Add;
3356 break;
3357 case BO_Sub:
3358 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003359 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003360 RMWOp = llvm::AtomicRMWInst::Sub;
3361 break;
3362 case BO_And:
3363 RMWOp = llvm::AtomicRMWInst::And;
3364 break;
3365 case BO_Or:
3366 RMWOp = llvm::AtomicRMWInst::Or;
3367 break;
3368 case BO_Xor:
3369 RMWOp = llvm::AtomicRMWInst::Xor;
3370 break;
3371 case BO_LT:
3372 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3373 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3374 : llvm::AtomicRMWInst::Max)
3375 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3376 : llvm::AtomicRMWInst::UMax);
3377 break;
3378 case BO_GT:
3379 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3380 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3381 : llvm::AtomicRMWInst::Min)
3382 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3383 : llvm::AtomicRMWInst::UMin);
3384 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003385 case BO_Assign:
3386 RMWOp = llvm::AtomicRMWInst::Xchg;
3387 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003388 case BO_Mul:
3389 case BO_Div:
3390 case BO_Rem:
3391 case BO_Shl:
3392 case BO_Shr:
3393 case BO_LAnd:
3394 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003395 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003396 case BO_PtrMemD:
3397 case BO_PtrMemI:
3398 case BO_LE:
3399 case BO_GE:
3400 case BO_EQ:
3401 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003402 case BO_AddAssign:
3403 case BO_SubAssign:
3404 case BO_AndAssign:
3405 case BO_OrAssign:
3406 case BO_XorAssign:
3407 case BO_MulAssign:
3408 case BO_DivAssign:
3409 case BO_RemAssign:
3410 case BO_ShlAssign:
3411 case BO_ShrAssign:
3412 case BO_Comma:
3413 llvm_unreachable("Unsupported atomic update operation");
3414 }
3415 auto *UpdateVal = Update.getScalarVal();
3416 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3417 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003418 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003419 X.getType()->hasSignedIntegerRepresentation());
3420 }
John McCall7f416cc2015-09-08 08:05:57 +00003421 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003422 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003423}
3424
Alexey Bataev5e018f92015-04-23 06:35:10 +00003425std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003426 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3427 llvm::AtomicOrdering AO, SourceLocation Loc,
3428 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3429 // Update expressions are allowed to have the following forms:
3430 // x binop= expr; -> xrval + expr;
3431 // x++, ++x -> xrval + 1;
3432 // x--, --x -> xrval - 1;
3433 // x = x binop expr; -> xrval binop expr
3434 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003435 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3436 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003437 if (X.isGlobalReg()) {
3438 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3439 // 'xrval'.
3440 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3441 } else {
3442 // Perform compare-and-swap procedure.
3443 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003444 }
3445 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003446 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003447}
3448
3449static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3450 const Expr *X, const Expr *E,
3451 const Expr *UE, bool IsXLHSInRHSPart,
3452 SourceLocation Loc) {
3453 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3454 "Update expr in 'atomic update' must be a binary operator.");
3455 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3456 // Update expressions are allowed to have the following forms:
3457 // x binop= expr; -> xrval + expr;
3458 // x++, ++x -> xrval + 1;
3459 // x--, --x -> xrval - 1;
3460 // x = x binop expr; -> xrval binop expr
3461 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003462 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003463 LValue XLValue = CGF.EmitLValue(X);
3464 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003465 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3466 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003467 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3468 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3469 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3470 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3471 auto Gen =
3472 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3473 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3474 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3475 return CGF.EmitAnyExpr(UE);
3476 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003477 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3478 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3479 // OpenMP, 2.12.6, atomic Construct
3480 // Any atomic construct with a seq_cst clause forces the atomically
3481 // performed operation to include an implicit flush operation without a
3482 // list.
3483 if (IsSeqCst)
3484 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3485}
3486
3487static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003488 QualType SourceType, QualType ResType,
3489 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003490 switch (CGF.getEvaluationKind(ResType)) {
3491 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003492 return RValue::get(
3493 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003494 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003495 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003496 return RValue::getComplex(Res.first, Res.second);
3497 }
3498 case TEK_Aggregate:
3499 break;
3500 }
3501 llvm_unreachable("Must be a scalar or complex.");
3502}
3503
3504static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3505 bool IsPostfixUpdate, const Expr *V,
3506 const Expr *X, const Expr *E,
3507 const Expr *UE, bool IsXLHSInRHSPart,
3508 SourceLocation Loc) {
3509 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3510 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3511 RValue NewVVal;
3512 LValue VLValue = CGF.EmitLValue(V);
3513 LValue XLValue = CGF.EmitLValue(X);
3514 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003515 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3516 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003517 QualType NewVValType;
3518 if (UE) {
3519 // 'x' is updated with some additional value.
3520 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3521 "Update expr in 'atomic capture' must be a binary operator.");
3522 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3523 // Update expressions are allowed to have the following forms:
3524 // x binop= expr; -> xrval + expr;
3525 // x++, ++x -> xrval + 1;
3526 // x--, --x -> xrval - 1;
3527 // x = x binop expr; -> xrval binop expr
3528 // x = expr Op x; - > expr binop xrval;
3529 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3530 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3531 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3532 NewVValType = XRValExpr->getType();
3533 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3534 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003535 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003536 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3537 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3538 RValue Res = CGF.EmitAnyExpr(UE);
3539 NewVVal = IsPostfixUpdate ? XRValue : Res;
3540 return Res;
3541 };
3542 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3543 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3544 if (Res.first) {
3545 // 'atomicrmw' instruction was generated.
3546 if (IsPostfixUpdate) {
3547 // Use old value from 'atomicrmw'.
3548 NewVVal = Res.second;
3549 } else {
3550 // 'atomicrmw' does not provide new value, so evaluate it using old
3551 // value of 'x'.
3552 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3553 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3554 NewVVal = CGF.EmitAnyExpr(UE);
3555 }
3556 }
3557 } else {
3558 // 'x' is simply rewritten with some 'expr'.
3559 NewVValType = X->getType().getNonReferenceType();
3560 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003561 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003562 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003563 NewVVal = XRValue;
3564 return ExprRValue;
3565 };
3566 // Try to perform atomicrmw xchg, otherwise simple exchange.
3567 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3568 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3569 Loc, Gen);
3570 if (Res.first) {
3571 // 'atomicrmw' instruction was generated.
3572 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3573 }
3574 }
3575 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003576 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003577 // OpenMP, 2.12.6, atomic Construct
3578 // Any atomic construct with a seq_cst clause forces the atomically
3579 // performed operation to include an implicit flush operation without a
3580 // list.
3581 if (IsSeqCst)
3582 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3583}
3584
Alexey Bataevb57056f2015-01-22 06:17:56 +00003585static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003586 bool IsSeqCst, bool IsPostfixUpdate,
3587 const Expr *X, const Expr *V, const Expr *E,
3588 const Expr *UE, bool IsXLHSInRHSPart,
3589 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003590 switch (Kind) {
3591 case OMPC_read:
3592 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3593 break;
3594 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003595 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3596 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003597 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003598 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003599 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3600 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003601 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003602 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3603 IsXLHSInRHSPart, Loc);
3604 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003605 case OMPC_if:
3606 case OMPC_final:
3607 case OMPC_num_threads:
3608 case OMPC_private:
3609 case OMPC_firstprivate:
3610 case OMPC_lastprivate:
3611 case OMPC_reduction:
3612 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003613 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003614 case OMPC_collapse:
3615 case OMPC_default:
3616 case OMPC_seq_cst:
3617 case OMPC_shared:
3618 case OMPC_linear:
3619 case OMPC_aligned:
3620 case OMPC_copyin:
3621 case OMPC_copyprivate:
3622 case OMPC_flush:
3623 case OMPC_proc_bind:
3624 case OMPC_schedule:
3625 case OMPC_ordered:
3626 case OMPC_nowait:
3627 case OMPC_untied:
3628 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003629 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003630 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003631 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003632 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003633 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003634 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003635 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003636 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003637 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003638 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003639 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003640 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003641 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003642 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003643 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003644 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003645 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003646 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003647 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003648 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003649 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3650 }
3651}
3652
3653void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003654 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003655 OpenMPClauseKind Kind = OMPC_unknown;
3656 for (auto *C : S.clauses()) {
3657 // Find first clause (skip seq_cst clause, if it is first).
3658 if (C->getClauseKind() != OMPC_seq_cst) {
3659 Kind = C->getClauseKind();
3660 break;
3661 }
3662 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003663
3664 const auto *CS =
3665 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003666 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003667 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003668 }
3669 // Processing for statements under 'atomic capture'.
3670 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3671 for (const auto *C : Compound->body()) {
3672 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3673 enterFullExpression(EWC);
3674 }
3675 }
3676 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003677
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003678 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3679 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003680 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003681 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3682 S.getV(), S.getExpr(), S.getUpdateExpr(),
3683 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003684 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003685 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003686 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003687}
3688
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003689static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3690 const OMPExecutableDirective &S,
3691 const RegionCodeGenTy &CodeGen) {
3692 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3693 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00003694 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
3695
Samuel Antaoee8fb302016-01-06 13:42:12 +00003696 llvm::Function *Fn = nullptr;
3697 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003698
Samuel Antaobed3c462015-10-02 16:14:20 +00003699 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003700 // Check for the at most one if clause associated with the target region.
3701 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3702 if (C->getNameModifier() == OMPD_unknown ||
3703 C->getNameModifier() == OMPD_target) {
3704 IfCond = C->getCondition();
3705 break;
3706 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003707 }
3708
3709 // Check if we have any device clause associated with the directive.
3710 const Expr *Device = nullptr;
3711 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3712 Device = C->getDevice();
3713 }
3714
Samuel Antaoee8fb302016-01-06 13:42:12 +00003715 // Check if we have an if clause whose conditional always evaluates to false
3716 // or if we do not have any targets specified. If so the target region is not
3717 // an offload entry point.
3718 bool IsOffloadEntry = true;
3719 if (IfCond) {
3720 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003721 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003722 IsOffloadEntry = false;
3723 }
3724 if (CGM.getLangOpts().OMPTargetTriples.empty())
3725 IsOffloadEntry = false;
3726
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003727 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003728 StringRef ParentName;
3729 // In case we have Ctors/Dtors we use the complete type variant to produce
3730 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003731 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003732 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003733 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003734 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3735 else
3736 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003737 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003738
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003739 // Emit target region as a standalone region.
3740 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3741 IsOffloadEntry, CodeGen);
3742 OMPLexicalScope Scope(CGF, S);
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003743 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3744 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003745 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003746 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003747}
3748
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003749static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3750 PrePostActionTy &Action) {
3751 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3752 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3753 CGF.EmitOMPPrivateClause(S, PrivateScope);
3754 (void)PrivateScope.Privatize();
3755
3756 Action.Enter(CGF);
3757 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3758}
3759
3760void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3761 StringRef ParentName,
3762 const OMPTargetDirective &S) {
3763 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3764 emitTargetRegion(CGF, S, Action);
3765 };
3766 llvm::Function *Fn;
3767 llvm::Constant *Addr;
3768 // Emit target region as a standalone region.
3769 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3770 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3771 assert(Fn && Addr && "Target device function emission failed.");
3772}
3773
3774void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3775 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3776 emitTargetRegion(CGF, S, Action);
3777 };
3778 emitCommonOMPTargetDirective(*this, S, CodeGen);
3779}
3780
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003781static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3782 const OMPExecutableDirective &S,
3783 OpenMPDirectiveKind InnermostKind,
3784 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003785 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
3786 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
3787 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003788
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003789 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
3790 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003791 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003792 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3793 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003794
Carlo Bertollic6872252016-04-04 15:55:02 +00003795 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3796 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003797 }
3798
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003799 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003800 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3801 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003802 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3803 CapturedVars);
3804}
3805
3806void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00003807 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003808 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003809 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003810 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3811 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003812 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003813 (void)PrivateScope.Privatize();
3814 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003815 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003816 };
3817 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003818 emitPostUpdateForReductionClause(
3819 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00003820}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003821
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003822static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
3823 const OMPTargetTeamsDirective &S) {
3824 auto *CS = S.getCapturedStmt(OMPD_teams);
3825 Action.Enter(CGF);
3826 auto &&CodeGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3827 // TODO: Add support for clauses.
3828 CGF.EmitStmt(CS->getCapturedStmt());
3829 };
3830 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
3831}
3832
3833void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
3834 CodeGenModule &CGM, StringRef ParentName,
3835 const OMPTargetTeamsDirective &S) {
3836 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3837 emitTargetTeamsRegion(CGF, Action, S);
3838 };
3839 llvm::Function *Fn;
3840 llvm::Constant *Addr;
3841 // Emit target region as a standalone region.
3842 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3843 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3844 assert(Fn && Addr && "Target device function emission failed.");
3845}
3846
3847void CodeGenFunction::EmitOMPTargetTeamsDirective(
3848 const OMPTargetTeamsDirective &S) {
3849 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3850 emitTargetTeamsRegion(CGF, Action, S);
3851 };
3852 emitCommonOMPTargetDirective(*this, S, CodeGen);
3853}
3854
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003855void CodeGenFunction::EmitOMPCancellationPointDirective(
3856 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00003857 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
3858 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003859}
3860
Alexey Bataev80909872015-07-02 11:25:17 +00003861void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003862 const Expr *IfCond = nullptr;
3863 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3864 if (C->getNameModifier() == OMPD_unknown ||
3865 C->getNameModifier() == OMPD_cancel) {
3866 IfCond = C->getCondition();
3867 break;
3868 }
3869 }
3870 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003871 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00003872}
3873
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003874CodeGenFunction::JumpDest
3875CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00003876 if (Kind == OMPD_parallel || Kind == OMPD_task ||
3877 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003878 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003879 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00003880 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
3881 Kind == OMPD_distribute_parallel_for ||
3882 Kind == OMPD_target_parallel_for);
3883 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003884}
Michael Wong65f367f2015-07-21 13:44:28 +00003885
Samuel Antaocc10b852016-07-28 14:23:26 +00003886void CodeGenFunction::EmitOMPUseDevicePtrClause(
3887 const OMPClause &NC, OMPPrivateScope &PrivateScope,
3888 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
3889 const auto &C = cast<OMPUseDevicePtrClause>(NC);
3890 auto OrigVarIt = C.varlist_begin();
3891 auto InitIt = C.inits().begin();
3892 for (auto PvtVarIt : C.private_copies()) {
3893 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
3894 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
3895 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
3896
3897 // In order to identify the right initializer we need to match the
3898 // declaration used by the mapping logic. In some cases we may get
3899 // OMPCapturedExprDecl that refers to the original declaration.
3900 const ValueDecl *MatchingVD = OrigVD;
3901 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
3902 // OMPCapturedExprDecl are used to privative fields of the current
3903 // structure.
3904 auto *ME = cast<MemberExpr>(OED->getInit());
3905 assert(isa<CXXThisExpr>(ME->getBase()) &&
3906 "Base should be the current struct!");
3907 MatchingVD = ME->getMemberDecl();
3908 }
3909
3910 // If we don't have information about the current list item, move on to
3911 // the next one.
3912 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
3913 if (InitAddrIt == CaptureDeviceAddrMap.end())
3914 continue;
3915
3916 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
3917 // Initialize the temporary initialization variable with the address we
3918 // get from the runtime library. We have to cast the source address
3919 // because it is always a void *. References are materialized in the
3920 // privatization scope, so the initialization here disregards the fact
3921 // the original variable is a reference.
3922 QualType AddrQTy =
3923 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
3924 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
3925 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
3926 setAddrOfLocalVar(InitVD, InitAddr);
3927
3928 // Emit private declaration, it will be initialized by the value we
3929 // declaration we just added to the local declarations map.
3930 EmitDecl(*PvtVD);
3931
3932 // The initialization variables reached its purpose in the emission
3933 // ofthe previous declaration, so we don't need it anymore.
3934 LocalDeclMap.erase(InitVD);
3935
3936 // Return the address of the private variable.
3937 return GetAddrOfLocalVar(PvtVD);
3938 });
3939 assert(IsRegistered && "firstprivate var already registered as private");
3940 // Silence the warning about unused variable.
3941 (void)IsRegistered;
3942
3943 ++OrigVarIt;
3944 ++InitIt;
3945 }
3946}
3947
Michael Wong65f367f2015-07-21 13:44:28 +00003948// Generate the instructions for '#pragma omp target data' directive.
3949void CodeGenFunction::EmitOMPTargetDataDirective(
3950 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00003951 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
3952
3953 // Create a pre/post action to signal the privatization of the device pointer.
3954 // This action can be replaced by the OpenMP runtime code generation to
3955 // deactivate privatization.
3956 bool PrivatizeDevicePointers = false;
3957 class DevicePointerPrivActionTy : public PrePostActionTy {
3958 bool &PrivatizeDevicePointers;
3959
3960 public:
3961 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
3962 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
3963 void Enter(CodeGenFunction &CGF) override {
3964 PrivatizeDevicePointers = true;
3965 }
Samuel Antaodf158d52016-04-27 22:58:19 +00003966 };
Samuel Antaocc10b852016-07-28 14:23:26 +00003967 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
3968
3969 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
3970 CodeGenFunction &CGF, PrePostActionTy &Action) {
3971 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3972 CGF.EmitStmt(
3973 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3974 };
3975
3976 // Codegen that selects wheather to generate the privatization code or not.
3977 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
3978 &InnermostCodeGen](CodeGenFunction &CGF,
3979 PrePostActionTy &Action) {
3980 RegionCodeGenTy RCG(InnermostCodeGen);
3981 PrivatizeDevicePointers = false;
3982
3983 // Call the pre-action to change the status of PrivatizeDevicePointers if
3984 // needed.
3985 Action.Enter(CGF);
3986
3987 if (PrivatizeDevicePointers) {
3988 OMPPrivateScope PrivateScope(CGF);
3989 // Emit all instances of the use_device_ptr clause.
3990 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
3991 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
3992 Info.CaptureDeviceAddrMap);
3993 (void)PrivateScope.Privatize();
3994 RCG(CGF);
3995 } else
3996 RCG(CGF);
3997 };
3998
3999 // Forward the provided action to the privatization codegen.
4000 RegionCodeGenTy PrivRCG(PrivCodeGen);
4001 PrivRCG.setAction(Action);
4002
4003 // Notwithstanding the body of the region is emitted as inlined directive,
4004 // we don't use an inline scope as changes in the references inside the
4005 // region are expected to be visible outside, so we do not privative them.
4006 OMPLexicalScope Scope(CGF, S);
4007 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4008 PrivRCG);
4009 };
4010
4011 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00004012
4013 // If we don't have target devices, don't bother emitting the data mapping
4014 // code.
4015 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00004016 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00004017 return;
4018 }
4019
4020 // Check if we have any if clause associated with the directive.
4021 const Expr *IfCond = nullptr;
4022 if (auto *C = S.getSingleClause<OMPIfClause>())
4023 IfCond = C->getCondition();
4024
4025 // Check if we have any device clause associated with the directive.
4026 const Expr *Device = nullptr;
4027 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4028 Device = C->getDevice();
4029
Samuel Antaocc10b852016-07-28 14:23:26 +00004030 // Set the action to signal privatization of device pointers.
4031 RCG.setAction(PrivAction);
4032
4033 // Emit region code.
4034 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4035 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00004036}
Alexey Bataev49f6e782015-12-01 04:18:41 +00004037
Samuel Antaodf67fc42016-01-19 19:15:56 +00004038void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4039 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00004040 // If we don't have target devices, don't bother emitting the data mapping
4041 // code.
4042 if (CGM.getLangOpts().OMPTargetTriples.empty())
4043 return;
4044
4045 // Check if we have any if clause associated with the directive.
4046 const Expr *IfCond = nullptr;
4047 if (auto *C = S.getSingleClause<OMPIfClause>())
4048 IfCond = C->getCondition();
4049
4050 // Check if we have any device clause associated with the directive.
4051 const Expr *Device = nullptr;
4052 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4053 Device = C->getDevice();
4054
Samuel Antao8d2d7302016-05-26 18:30:22 +00004055 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004056}
4057
Samuel Antao72590762016-01-19 20:04:50 +00004058void CodeGenFunction::EmitOMPTargetExitDataDirective(
4059 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00004060 // If we don't have target devices, don't bother emitting the data mapping
4061 // code.
4062 if (CGM.getLangOpts().OMPTargetTriples.empty())
4063 return;
4064
4065 // Check if we have any if clause associated with the directive.
4066 const Expr *IfCond = nullptr;
4067 if (auto *C = S.getSingleClause<OMPIfClause>())
4068 IfCond = C->getCondition();
4069
4070 // Check if we have any device clause associated with the directive.
4071 const Expr *Device = nullptr;
4072 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4073 Device = C->getDevice();
4074
Samuel Antao8d2d7302016-05-26 18:30:22 +00004075 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00004076}
4077
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004078static void emitTargetParallelRegion(CodeGenFunction &CGF,
4079 const OMPTargetParallelDirective &S,
4080 PrePostActionTy &Action) {
4081 // Get the captured statement associated with the 'parallel' region.
4082 auto *CS = S.getCapturedStmt(OMPD_parallel);
4083 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004084 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
4085 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4086 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4087 CGF.EmitOMPPrivateClause(S, PrivateScope);
4088 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4089 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004090 // TODO: Add support for clauses.
4091 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004092 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004093 };
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00004094 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4095 emitEmptyBoundParameters);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004096 emitPostUpdateForReductionClause(
4097 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004098}
4099
4100void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4101 CodeGenModule &CGM, StringRef ParentName,
4102 const OMPTargetParallelDirective &S) {
4103 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4104 emitTargetParallelRegion(CGF, S, Action);
4105 };
4106 llvm::Function *Fn;
4107 llvm::Constant *Addr;
4108 // Emit target region as a standalone region.
4109 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4110 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4111 assert(Fn && Addr && "Target device function emission failed.");
4112}
4113
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004114void CodeGenFunction::EmitOMPTargetParallelDirective(
4115 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004116 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4117 emitTargetParallelRegion(CGF, S, Action);
4118 };
4119 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004120}
4121
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004122void CodeGenFunction::EmitOMPTargetParallelForDirective(
4123 const OMPTargetParallelForDirective &S) {
4124 // TODO: codegen for target parallel for.
4125}
4126
Alexey Bataev7292c292016-04-25 12:22:29 +00004127/// Emit a helper variable and return corresponding lvalue.
4128static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4129 const ImplicitParamDecl *PVD,
4130 CodeGenFunction::OMPPrivateScope &Privates) {
4131 auto *VDecl = cast<VarDecl>(Helper->getDecl());
4132 Privates.addPrivate(
4133 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
4134}
4135
4136void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4137 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4138 // Emit outlined function for task construct.
4139 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
4140 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
4141 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4142 const Expr *IfCond = nullptr;
4143 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4144 if (C->getNameModifier() == OMPD_unknown ||
4145 C->getNameModifier() == OMPD_taskloop) {
4146 IfCond = C->getCondition();
4147 break;
4148 }
4149 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004150
4151 OMPTaskDataTy Data;
4152 // Check if taskloop must be emitted without taskgroup.
4153 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00004154 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004155 Data.Tied = true;
4156 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004157 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4158 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004159 Data.Schedule.setInt(/*IntVal=*/false);
4160 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004161 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4162 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004163 Data.Schedule.setInt(/*IntVal=*/true);
4164 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004165 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004166
4167 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4168 // if (PreCond) {
4169 // for (IV in 0..LastIteration) BODY;
4170 // <Final counter/linear vars updates>;
4171 // }
4172 //
4173
4174 // Emit: if (PreCond) - begin.
4175 // If the condition constant folds and can be elided, avoid emitting the
4176 // whole loop.
4177 bool CondConstant;
4178 llvm::BasicBlock *ContBlock = nullptr;
4179 OMPLoopScope PreInitScope(CGF, S);
4180 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4181 if (!CondConstant)
4182 return;
4183 } else {
4184 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4185 ContBlock = CGF.createBasicBlock("taskloop.if.end");
4186 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4187 CGF.getProfileCount(&S));
4188 CGF.EmitBlock(ThenBlock);
4189 CGF.incrementProfileCounter(&S);
4190 }
4191
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004192 if (isOpenMPSimdDirective(S.getDirectiveKind()))
4193 CGF.EmitOMPSimdInit(S);
4194
Alexey Bataev7292c292016-04-25 12:22:29 +00004195 OMPPrivateScope LoopScope(CGF);
4196 // Emit helper vars inits.
4197 enum { LowerBound = 5, UpperBound, Stride, LastIter };
4198 auto *I = CS->getCapturedDecl()->param_begin();
4199 auto *LBP = std::next(I, LowerBound);
4200 auto *UBP = std::next(I, UpperBound);
4201 auto *STP = std::next(I, Stride);
4202 auto *LIP = std::next(I, LastIter);
4203 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4204 LoopScope);
4205 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4206 LoopScope);
4207 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4208 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4209 LoopScope);
4210 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004211 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00004212 (void)LoopScope.Privatize();
4213 // Emit the loop iteration variable.
4214 const Expr *IVExpr = S.getIterationVariable();
4215 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4216 CGF.EmitVarDecl(*IVDecl);
4217 CGF.EmitIgnoredExpr(S.getInit());
4218
4219 // Emit the iterations count variable.
4220 // If it is not a variable, Sema decided to calculate iterations count on
4221 // each iteration (e.g., it is foldable into a constant).
4222 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4223 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4224 // Emit calculation of the iterations count.
4225 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4226 }
4227
4228 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4229 S.getInc(),
4230 [&S](CodeGenFunction &CGF) {
4231 CGF.EmitOMPLoopBody(S, JumpDest());
4232 CGF.EmitStopPoint(&S);
4233 },
4234 [](CodeGenFunction &) {});
4235 // Emit: if (PreCond) - end.
4236 if (ContBlock) {
4237 CGF.EmitBranch(ContBlock);
4238 CGF.EmitBlock(ContBlock, true);
4239 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004240 // Emit final copy of the lastprivate variables if IsLastIter != 0.
4241 if (HasLastprivateClause) {
4242 CGF.EmitOMPLastprivateClauseFinal(
4243 S, isOpenMPSimdDirective(S.getDirectiveKind()),
4244 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4245 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4246 (*LIP)->getType(), S.getLocStart())));
4247 }
Alexey Bataev7292c292016-04-25 12:22:29 +00004248 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004249 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4250 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4251 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004252 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4253 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004254 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4255 OutlinedFn, SharedsTy,
4256 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004257 };
4258 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4259 CodeGen);
4260 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004261 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004262}
4263
Alexey Bataev49f6e782015-12-01 04:18:41 +00004264void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004265 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004266}
4267
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004268void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4269 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004270 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004271}
Samuel Antao686c70c2016-05-26 17:30:50 +00004272
4273// Generate the instructions for '#pragma omp target update' directive.
4274void CodeGenFunction::EmitOMPTargetUpdateDirective(
4275 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00004276 // If we don't have target devices, don't bother emitting the data mapping
4277 // code.
4278 if (CGM.getLangOpts().OMPTargetTriples.empty())
4279 return;
4280
4281 // Check if we have any if clause associated with the directive.
4282 const Expr *IfCond = nullptr;
4283 if (auto *C = S.getSingleClause<OMPIfClause>())
4284 IfCond = C->getCondition();
4285
4286 // Check if we have any device clause associated with the directive.
4287 const Expr *Device = nullptr;
4288 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4289 Device = C->getDevice();
4290
4291 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00004292}