blob: 71d8ea271439525c15b76b534fb1b19048aaeacc [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();
90 return !isOpenMPTargetExecutionDirective(Kind) &&
91 isOpenMPParallelDirective(Kind);
92 }
93
94public:
95 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
96 : OMPLexicalScope(CGF, S,
97 /*AsInlined=*/false,
98 /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
99};
100
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +0000101/// Lexical scope for OpenMP teams construct, that handles correct codegen
102/// for captured expressions.
103class OMPTeamsScope final : public OMPLexicalScope {
104 bool EmitPreInitStmt(const OMPExecutableDirective &S) {
105 OpenMPDirectiveKind Kind = S.getDirectiveKind();
106 return !isOpenMPTargetExecutionDirective(Kind) &&
107 isOpenMPTeamsDirective(Kind);
108 }
109
110public:
111 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
112 : OMPLexicalScope(CGF, S,
113 /*AsInlined=*/false,
114 /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
115};
116
Alexey Bataev5a3af132016-03-29 08:58:54 +0000117/// Private scope for OpenMP loop-based directives, that supports capturing
118/// of used expression from loop statement.
119class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
120 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
121 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
122 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
123 for (const auto *I : PreInits->decls())
124 CGF.EmitVarDecl(cast<VarDecl>(*I));
125 }
126 }
127 }
128
129public:
130 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
131 : CodeGenFunction::RunCleanupsScope(CGF) {
132 emitPreInitStmt(CGF, S);
133 }
134};
135
Alexey Bataev3392d762016-02-16 11:18:12 +0000136} // namespace
137
Alexey Bataev1189bd02016-01-26 12:20:39 +0000138llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
139 auto &C = getContext();
140 llvm::Value *Size = nullptr;
141 auto SizeInChars = C.getTypeSizeInChars(Ty);
142 if (SizeInChars.isZero()) {
143 // getTypeSizeInChars() returns 0 for a VLA.
144 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
145 llvm::Value *ArraySize;
146 std::tie(ArraySize, Ty) = getVLASize(VAT);
147 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
148 }
149 SizeInChars = C.getTypeSizeInChars(Ty);
150 if (SizeInChars.isZero())
151 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
152 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
153 } else
154 Size = CGM.getSize(SizeInChars);
155 return Size;
156}
157
Alexey Bataev2377fe92015-09-10 08:12:02 +0000158void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000159 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000160 const RecordDecl *RD = S.getCapturedRecordDecl();
161 auto CurField = RD->field_begin();
162 auto CurCap = S.captures().begin();
163 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
164 E = S.capture_init_end();
165 I != E; ++I, ++CurField, ++CurCap) {
166 if (CurField->hasCapturedVLAType()) {
167 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000168 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000169 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000170 } else if (CurCap->capturesThis())
171 CapturedVars.push_back(CXXThisValue);
Samuel Antao6d004262016-06-16 18:39:34 +0000172 else if (CurCap->capturesVariableByCopy()) {
173 llvm::Value *CV =
174 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal();
175
176 // If the field is not a pointer, we need to save the actual value
177 // and load it as a void pointer.
178 if (!CurField->getType()->isAnyPointerType()) {
179 auto &Ctx = getContext();
180 auto DstAddr = CreateMemTemp(
181 Ctx.getUIntPtrType(),
182 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
183 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
184
185 auto *SrcAddrVal = EmitScalarConversion(
186 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
187 Ctx.getPointerType(CurField->getType()), SourceLocation());
188 LValue SrcLV =
189 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
190
191 // Store the value using the source type pointer.
192 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
193
194 // Load the value using the destination type pointer.
195 CV = EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
196 }
197 CapturedVars.push_back(CV);
198 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000199 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000200 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000201 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000202 }
203}
204
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000205static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
206 StringRef Name, LValue AddrLV,
207 bool isReferenceType = false) {
208 ASTContext &Ctx = CGF.getContext();
209
210 auto *CastedPtr = CGF.EmitScalarConversion(
211 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
212 Ctx.getPointerType(DstType), SourceLocation());
213 auto TmpAddr =
214 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
215 .getAddress();
216
217 // If we are dealing with references we need to return the address of the
218 // reference instead of the reference of the value.
219 if (isReferenceType) {
220 QualType RefType = Ctx.getLValueReferenceType(DstType);
221 auto *RefVal = TmpAddr.getPointer();
222 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
223 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
Akira Hatanaka642f7992016-10-18 19:05:41 +0000224 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000225 }
226
227 return TmpAddr;
228}
229
Alexey Bataev2377fe92015-09-10 08:12:02 +0000230llvm::Function *
Samuel Antao6d004262016-06-16 18:39:34 +0000231CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000232 assert(
233 CapturedStmtInfo &&
234 "CapturedStmtInfo should be set when generating the captured function");
235 const CapturedDecl *CD = S.getCapturedDecl();
236 const RecordDecl *RD = S.getCapturedRecordDecl();
237 assert(CD->hasBody() && "missing CapturedDecl body");
238
239 // Build the argument list.
240 ASTContext &Ctx = CGM.getContext();
241 FunctionArgList Args;
242 Args.append(CD->param_begin(),
243 std::next(CD->param_begin(), CD->getContextParamPosition()));
244 auto I = S.captures().begin();
245 for (auto *FD : RD->fields()) {
246 QualType ArgType = FD->getType();
247 IdentifierInfo *II = nullptr;
248 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000249
250 // If this is a capture by copy and the type is not a pointer, the outlined
251 // function argument type should be uintptr and the value properly casted to
252 // uintptr. This is necessary given that the runtime library is only able to
253 // deal with pointers. We can pass in the same way the VLA type sizes to the
254 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000255 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
256 I->capturesVariableArrayType())
257 ArgType = Ctx.getUIntPtrType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000258
259 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000260 CapVar = I->getCapturedVar();
261 II = CapVar->getIdentifier();
262 } else if (I->capturesThis())
263 II = &getContext().Idents.get("this");
264 else {
265 assert(I->capturesVariableArrayType());
266 II = &getContext().Idents.get("vla");
267 }
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000268 if (ArgType->isVariablyModifiedType()) {
269 bool IsReference = ArgType->isLValueReferenceType();
270 ArgType =
271 getContext().getCanonicalParamType(ArgType.getNonReferenceType());
272 if (IsReference && !ArgType->isPointerType()) {
273 ArgType = getContext().getLValueReferenceType(
274 ArgType, /*SpelledAsLValue=*/false);
275 }
276 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000277 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
278 FD->getLocation(), II, ArgType));
279 ++I;
280 }
281 Args.append(
282 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
283 CD->param_end());
284
285 // Create the function declaration.
286 FunctionType::ExtInfo ExtInfo;
287 const CGFunctionInfo &FuncInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000288 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000289 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
290
291 llvm::Function *F = llvm::Function::Create(
292 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
293 CapturedStmtInfo->getHelperName(), &CGM.getModule());
294 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
295 if (CD->isNothrow())
296 F->addFnAttr(llvm::Attribute::NoUnwind);
297
298 // Generate the function.
299 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
300 CD->getBody()->getLocStart());
301 unsigned Cnt = CD->getContextParamPosition();
302 I = S.captures().begin();
303 for (auto *FD : RD->fields()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000304 // If we are capturing a pointer by copy we don't need to do anything, just
305 // use the value that we get from the arguments.
306 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000307 const VarDecl *CurVD = I->getCapturedVar();
308 Address LocalAddr = GetAddrOfLocalVar(Args[Cnt]);
309 // If the variable is a reference we need to materialize it here.
310 if (CurVD->getType()->isReferenceType()) {
311 Address RefAddr = CreateMemTemp(CurVD->getType(), getPointerAlign(),
312 ".materialized_ref");
313 EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr, /*Volatile=*/false,
314 CurVD->getType());
315 LocalAddr = RefAddr;
316 }
317 setAddrOfLocalVar(CurVD, LocalAddr);
Richard Trieucc3949d2016-02-18 22:34:54 +0000318 ++Cnt;
319 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000320 continue;
321 }
322
Alexey Bataev2377fe92015-09-10 08:12:02 +0000323 LValue ArgLVal =
324 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
325 AlignmentSource::Decl);
326 if (FD->hasCapturedVLAType()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000327 LValue CastedArgLVal =
Samuel Antao6d004262016-06-16 18:39:34 +0000328 MakeAddrLValue(castValueFromUintptr(*this, FD->getType(),
329 Args[Cnt]->getName(), ArgLVal),
330 FD->getType(), AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000331 auto *ExprArg =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000332 EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000333 auto VAT = FD->getCapturedVLAType();
334 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
335 } else if (I->capturesVariable()) {
336 auto *Var = I->getCapturedVar();
337 QualType VarTy = Var->getType();
338 Address ArgAddr = ArgLVal.getAddress();
339 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000340 if (ArgLVal.getType()->isLValueReferenceType()) {
341 ArgAddr = EmitLoadOfReference(
342 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000343 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000344 assert(ArgLVal.getType()->isPointerType());
345 ArgAddr = EmitLoadOfPointer(
346 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
347 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000348 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000349 setAddrOfLocalVar(
350 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000351 } else if (I->capturesVariableByCopy()) {
352 assert(!FD->getType()->isAnyPointerType() &&
353 "Not expecting a captured pointer.");
354 auto *Var = I->getCapturedVar();
355 QualType VarTy = Var->getType();
Samuel Antao6d004262016-06-16 18:39:34 +0000356 setAddrOfLocalVar(Var, castValueFromUintptr(*this, FD->getType(),
357 Args[Cnt]->getName(), ArgLVal,
358 VarTy->isReferenceType()));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000359 } else {
360 // If 'this' is captured, load it into CXXThisValue.
361 assert(I->capturesThis());
362 CXXThisValue =
363 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
364 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000365 ++Cnt;
366 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000367 }
368
Serge Pavlov3a561452015-12-06 14:32:39 +0000369 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000370 CapturedStmtInfo->EmitBody(*this, CD->getBody());
371 FinishFunction(CD->getBodyRBrace());
372
373 return F;
374}
375
Alexey Bataev9959db52014-05-06 10:08:46 +0000376//===----------------------------------------------------------------------===//
377// OpenMP Directive Emission
378//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000379void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000380 Address DestAddr, Address SrcAddr, QualType OriginalType,
381 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000382 // Perform element-by-element initialization.
383 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000384
385 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000386 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000387 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
388 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
389
390 auto SrcBegin = SrcAddr.getPointer();
391 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000392 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000393 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
394 // The basic structure here is a while-do loop.
395 auto BodyBB = createBasicBlock("omp.arraycpy.body");
396 auto DoneBB = createBasicBlock("omp.arraycpy.done");
397 auto IsEmpty =
398 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
399 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000400
Alexey Bataev420d45b2015-04-14 05:11:24 +0000401 // Enter the loop body, making that address the current address.
402 auto EntryBB = Builder.GetInsertBlock();
403 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000404
405 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
406
407 llvm::PHINode *SrcElementPHI =
408 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
409 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
410 Address SrcElementCurrent =
411 Address(SrcElementPHI,
412 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
413
414 llvm::PHINode *DestElementPHI =
415 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
416 DestElementPHI->addIncoming(DestBegin, EntryBB);
417 Address DestElementCurrent =
418 Address(DestElementPHI,
419 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000420
Alexey Bataev420d45b2015-04-14 05:11:24 +0000421 // Emit copy.
422 CopyGen(DestElementCurrent, SrcElementCurrent);
423
424 // Shift the address forward by one element.
425 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000426 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000427 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000428 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000429 // Check whether we've reached the end.
430 auto Done =
431 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
432 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000433 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
434 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000435
436 // Done.
437 EmitBlock(DoneBB, /*IsFinished=*/true);
438}
439
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000440/// Check if the combiner is a call to UDR combiner and if it is so return the
441/// UDR decl used for reduction.
442static const OMPDeclareReductionDecl *
443getReductionInit(const Expr *ReductionOp) {
444 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
445 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
446 if (auto *DRE =
447 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
448 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
449 return DRD;
450 return nullptr;
451}
452
453static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
454 const OMPDeclareReductionDecl *DRD,
455 const Expr *InitOp,
456 Address Private, Address Original,
457 QualType Ty) {
458 if (DRD->getInitializer()) {
459 std::pair<llvm::Function *, llvm::Function *> Reduction =
460 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
461 auto *CE = cast<CallExpr>(InitOp);
462 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
463 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
464 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
465 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
466 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
467 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
468 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
469 [=]() -> Address { return Private; });
470 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
471 [=]() -> Address { return Original; });
472 (void)PrivateScope.Privatize();
473 RValue Func = RValue::get(Reduction.second);
474 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
475 CGF.EmitIgnoredExpr(InitOp);
476 } else {
477 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
478 auto *GV = new llvm::GlobalVariable(
479 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
480 llvm::GlobalValue::PrivateLinkage, Init, ".init");
481 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
482 RValue InitRVal;
483 switch (CGF.getEvaluationKind(Ty)) {
484 case TEK_Scalar:
485 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
486 break;
487 case TEK_Complex:
488 InitRVal =
489 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
490 break;
491 case TEK_Aggregate:
492 InitRVal = RValue::getAggregate(LV.getAddress());
493 break;
494 }
495 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
496 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
497 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
498 /*IsInitializer=*/false);
499 }
500}
501
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000502/// \brief Emit initialization of arrays of complex types.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000503/// \param DestAddr Address of the array.
504/// \param Type Type of array.
505/// \param Init Initial expression of array.
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000506/// \param SrcAddr Address of the original array.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000507static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000508 QualType Type, const Expr *Init,
509 Address SrcAddr = Address::invalid()) {
510 auto *DRD = getReductionInit(Init);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000511 // Perform element-by-element initialization.
512 QualType ElementTy;
513
514 // Drill down to the base element type on both arrays.
515 auto ArrayTy = Type->getAsArrayTypeUnsafe();
516 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
517 DestAddr =
518 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000519 if (DRD)
520 SrcAddr =
521 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000522
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000523 llvm::Value *SrcBegin = nullptr;
524 if (DRD)
525 SrcBegin = SrcAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000526 auto DestBegin = DestAddr.getPointer();
527 // Cast from pointer to array type to pointer to single element.
528 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
529 // The basic structure here is a while-do loop.
530 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
531 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
532 auto IsEmpty =
533 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
534 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
535
536 // Enter the loop body, making that address the current address.
537 auto EntryBB = CGF.Builder.GetInsertBlock();
538 CGF.EmitBlock(BodyBB);
539
540 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
541
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000542 llvm::PHINode *SrcElementPHI = nullptr;
543 Address SrcElementCurrent = Address::invalid();
544 if (DRD) {
545 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
546 "omp.arraycpy.srcElementPast");
547 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
548 SrcElementCurrent =
549 Address(SrcElementPHI,
550 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
551 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000552 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
553 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
554 DestElementPHI->addIncoming(DestBegin, EntryBB);
555 Address DestElementCurrent =
556 Address(DestElementPHI,
557 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
558
559 // Emit copy.
560 {
561 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +0000562 if (DRD && (DRD->getInitializer() || !Init)) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000563 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
564 SrcElementCurrent, ElementTy);
565 } else
566 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
567 /*IsInitializer=*/false);
568 }
569
570 if (DRD) {
571 // Shift the address forward by one element.
572 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
573 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
574 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000575 }
576
577 // Shift the address forward by one element.
578 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
579 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
580 // Check whether we've reached the end.
581 auto Done =
582 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
583 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
584 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
585
586 // Done.
587 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
588}
589
John McCall7f416cc2015-09-08 08:05:57 +0000590void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
591 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000592 const VarDecl *SrcVD, const Expr *Copy) {
593 if (OriginalType->isArrayType()) {
594 auto *BO = dyn_cast<BinaryOperator>(Copy);
595 if (BO && BO->getOpcode() == BO_Assign) {
596 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000597 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000598 } else {
599 // For arrays with complex element types perform element by element
600 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000601 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000602 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000603 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000604 // Working with the single array element, so have to remap
605 // destination and source variables to corresponding array
606 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000607 CodeGenFunction::OMPPrivateScope Remap(*this);
608 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000609 return DestElement;
610 });
611 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000612 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000613 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000614 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000615 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000616 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000617 } else {
618 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000619 CodeGenFunction::OMPPrivateScope Remap(*this);
620 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
621 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000622 (void)Remap.Privatize();
623 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000624 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000625 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000626}
627
Alexey Bataev69c62a92015-04-15 04:52:20 +0000628bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
629 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000630 if (!HaveInsertPoint())
631 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000632 bool FirstprivateIsLastprivate = false;
633 llvm::DenseSet<const VarDecl *> Lastprivates;
634 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
635 for (const auto *D : C->varlists())
636 Lastprivates.insert(
637 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
638 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000639 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000640 CGCapturedStmtInfo CapturesInfo(cast<CapturedStmt>(*D.getAssociatedStmt()));
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000641 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000642 auto IRef = C->varlist_begin();
643 auto InitsRef = C->inits().begin();
644 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000645 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000646 bool ThisFirstprivateIsLastprivate =
647 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000648 auto *CapFD = CapturesInfo.lookup(OrigVD);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000649 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9afe5752016-05-24 07:40:12 +0000650 if (!ThisFirstprivateIsLastprivate && FD && (FD == CapFD) &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000651 !FD->getType()->isReferenceType()) {
652 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
653 ++IRef;
654 ++InitsRef;
655 continue;
656 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000657 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000658 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000659 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000660 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
661 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
662 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000663 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
664 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
665 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000666 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000667 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000668 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000669 // Emit VarDecl with copy init for arrays.
670 // Get the address of the original variable captured in current
671 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000672 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000673 auto Emission = EmitAutoVarAlloca(*VD);
674 auto *Init = VD->getInit();
675 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
676 // Perform simple memcpy.
677 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000678 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000679 } else {
680 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000681 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000682 [this, VDInit, Init](Address DestElement,
683 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000684 // Clean up any temporaries needed by the initialization.
685 RunCleanupsScope InitScope(*this);
686 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000687 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000688 EmitAnyExprToMem(Init, DestElement,
689 Init->getType().getQualifiers(),
690 /*IsInitializer*/ false);
691 LocalDeclMap.erase(VDInit);
692 });
693 }
694 EmitAutoVarCleanups(Emission);
695 return Emission.getAllocatedAddress();
696 });
697 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000698 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000699 // Emit private VarDecl with copy init.
700 // Remap temp VDInit variable to the address of the original
701 // variable
702 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000703 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000704 EmitDecl(*VD);
705 LocalDeclMap.erase(VDInit);
706 return GetAddrOfLocalVar(VD);
707 });
708 }
709 assert(IsRegistered &&
710 "firstprivate var already registered as private");
711 // Silence the warning about unused variable.
712 (void)IsRegistered;
713 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000714 ++IRef;
715 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000716 }
717 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000718 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000719}
720
Alexey Bataev03b340a2014-10-21 03:16:40 +0000721void CodeGenFunction::EmitOMPPrivateClause(
722 const OMPExecutableDirective &D,
723 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000724 if (!HaveInsertPoint())
725 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000726 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000727 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000728 auto IRef = C->varlist_begin();
729 for (auto IInit : C->private_copies()) {
730 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000731 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
732 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
733 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000734 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000735 // Emit private VarDecl with copy init.
736 EmitDecl(*VD);
737 return GetAddrOfLocalVar(VD);
738 });
739 assert(IsRegistered && "private var already registered as private");
740 // Silence the warning about unused variable.
741 (void)IsRegistered;
742 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000743 ++IRef;
744 }
745 }
746}
747
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000748bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000749 if (!HaveInsertPoint())
750 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000751 // threadprivate_var1 = master_threadprivate_var1;
752 // operator=(threadprivate_var2, master_threadprivate_var2);
753 // ...
754 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000755 llvm::DenseSet<const VarDecl *> CopiedVars;
756 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000757 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000758 auto IRef = C->varlist_begin();
759 auto ISrcRef = C->source_exprs().begin();
760 auto IDestRef = C->destination_exprs().begin();
761 for (auto *AssignOp : C->assignment_ops()) {
762 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000763 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000764 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000765 // Get the address of the master variable. If we are emitting code with
766 // TLS support, the address is passed from the master as field in the
767 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000768 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000769 if (getLangOpts().OpenMPUseTLS &&
770 getContext().getTargetInfo().isTLSSupported()) {
771 assert(CapturedStmtInfo->lookup(VD) &&
772 "Copyin threadprivates should have been captured!");
773 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
774 VK_LValue, (*IRef)->getExprLoc());
775 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000776 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000777 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000778 MasterAddr =
779 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
780 : CGM.GetAddrOfGlobal(VD),
781 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000782 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000783 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000784 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000785 if (CopiedVars.size() == 1) {
786 // At first check if current thread is a master thread. If it is, no
787 // need to copy data.
788 CopyBegin = createBasicBlock("copyin.not.master");
789 CopyEnd = createBasicBlock("copyin.not.master.end");
790 Builder.CreateCondBr(
791 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000792 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
793 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000794 CopyBegin, CopyEnd);
795 EmitBlock(CopyBegin);
796 }
797 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
798 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000799 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000800 }
801 ++IRef;
802 ++ISrcRef;
803 ++IDestRef;
804 }
805 }
806 if (CopyEnd) {
807 // Exit out of copying procedure for non-master thread.
808 EmitBlock(CopyEnd, /*IsFinished=*/true);
809 return true;
810 }
811 return false;
812}
813
Alexey Bataev38e89532015-04-16 04:54:05 +0000814bool CodeGenFunction::EmitOMPLastprivateClauseInit(
815 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000816 if (!HaveInsertPoint())
817 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000818 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000819 llvm::DenseSet<const VarDecl *> SIMDLCVs;
820 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
821 auto *LoopDirective = cast<OMPLoopDirective>(&D);
822 for (auto *C : LoopDirective->counters()) {
823 SIMDLCVs.insert(
824 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
825 }
826 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000827 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000828 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000829 HasAtLeastOneLastprivate = true;
Alexey Bataevf93095a2016-05-05 08:46:22 +0000830 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()))
831 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000832 auto IRef = C->varlist_begin();
833 auto IDestRef = C->destination_exprs().begin();
834 for (auto *IInit : C->private_copies()) {
835 // Keep the address of the original variable for future update at the end
836 // of the loop.
837 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000838 // Taskloops do not require additional initialization, it is done in
839 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000840 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
841 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000842 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000843 DeclRefExpr DRE(
844 const_cast<VarDecl *>(OrigVD),
845 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
846 OrigVD) != nullptr,
847 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
848 return EmitLValue(&DRE).getAddress();
849 });
850 // Check if the variable is also a firstprivate: in this case IInit is
851 // not generated. Initialization of this variable will happen in codegen
852 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000853 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000854 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000855 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
856 // Emit private VarDecl with copy init.
857 EmitDecl(*VD);
858 return GetAddrOfLocalVar(VD);
859 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000860 assert(IsRegistered &&
861 "lastprivate var already registered as private");
862 (void)IsRegistered;
863 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000864 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000865 ++IRef;
866 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000867 }
868 }
869 return HasAtLeastOneLastprivate;
870}
871
872void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000873 const OMPExecutableDirective &D, bool NoFinals,
874 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000875 if (!HaveInsertPoint())
876 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000877 // Emit following code:
878 // if (<IsLastIterCond>) {
879 // orig_var1 = private_orig_var1;
880 // ...
881 // orig_varn = private_orig_varn;
882 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000883 llvm::BasicBlock *ThenBB = nullptr;
884 llvm::BasicBlock *DoneBB = nullptr;
885 if (IsLastIterCond) {
886 ThenBB = createBasicBlock(".omp.lastprivate.then");
887 DoneBB = createBasicBlock(".omp.lastprivate.done");
888 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
889 EmitBlock(ThenBB);
890 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000891 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
892 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000893 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000894 auto IC = LoopDirective->counters().begin();
895 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000896 auto *D =
897 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
898 if (NoFinals)
899 AlreadyEmittedVars.insert(D);
900 else
901 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000902 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000903 }
904 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000905 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
906 auto IRef = C->varlist_begin();
907 auto ISrcRef = C->source_exprs().begin();
908 auto IDestRef = C->destination_exprs().begin();
909 for (auto *AssignOp : C->assignment_ops()) {
910 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
911 QualType Type = PrivateVD->getType();
912 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
913 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
914 // If lastprivate variable is a loop control variable for loop-based
915 // directive, update its value before copyin back to original
916 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000917 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
918 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000919 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
920 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
921 // Get the address of the original variable.
922 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
923 // Get the address of the private variable.
924 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
925 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
926 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000927 Address(Builder.CreateLoad(PrivateAddr),
928 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000929 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000930 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000931 ++IRef;
932 ++ISrcRef;
933 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000934 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000935 if (auto *PostUpdate = C->getPostUpdateExpr())
936 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000937 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000938 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000939 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000940}
941
Alexey Bataev31300ed2016-02-04 11:27:03 +0000942static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
943 LValue BaseLV, llvm::Value *Addr) {
944 Address Tmp = Address::invalid();
945 Address TopTmp = Address::invalid();
946 Address MostTopTmp = Address::invalid();
947 BaseTy = BaseTy.getNonReferenceType();
948 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
949 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
950 Tmp = CGF.CreateMemTemp(BaseTy);
951 if (TopTmp.isValid())
952 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
953 else
954 MostTopTmp = Tmp;
955 TopTmp = Tmp;
956 BaseTy = BaseTy->getPointeeType();
957 }
958 llvm::Type *Ty = BaseLV.getPointer()->getType();
959 if (Tmp.isValid())
960 Ty = Tmp.getElementType();
961 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
962 if (Tmp.isValid()) {
963 CGF.Builder.CreateStore(Addr, Tmp);
964 return MostTopTmp;
965 }
966 return Address(Addr, BaseLV.getAlignment());
967}
968
969static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
970 LValue BaseLV) {
971 BaseTy = BaseTy.getNonReferenceType();
972 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
973 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
974 if (auto *PtrTy = BaseTy->getAs<PointerType>())
975 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
976 else {
977 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
978 BaseTy->castAs<ReferenceType>());
979 }
980 BaseTy = BaseTy->getPointeeType();
981 }
982 return CGF.MakeAddrLValue(
983 Address(
984 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
985 BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()),
986 BaseLV.getAlignment()),
987 BaseLV.getType(), BaseLV.getAlignmentSource());
988}
989
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000990void CodeGenFunction::EmitOMPReductionClauseInit(
991 const OMPExecutableDirective &D,
992 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000993 if (!HaveInsertPoint())
994 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000995 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000996 auto ILHS = C->lhs_exprs().begin();
997 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000998 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000999 auto IRed = C->reduction_ops().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001000 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001001 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001002 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
1003 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001004 auto *DRD = getReductionInit(*IRed);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001005 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
1006 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
1007 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1008 Base = TempOASE->getBase()->IgnoreParenImpCasts();
1009 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1010 Base = TempASE->getBase()->IgnoreParenImpCasts();
1011 auto *DE = cast<DeclRefExpr>(Base);
1012 auto *OrigVD = cast<VarDecl>(DE->getDecl());
1013 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
1014 auto OASELValueUB =
1015 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
1016 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +00001017 LValue BaseLValue =
1018 loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(),
1019 OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001020 // Store the address of the original variable associated with the LHS
1021 // implicit variable.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00001022 PrivateScope.addPrivate(LHSVD, [OASELValueLB]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001023 return OASELValueLB.getAddress();
1024 });
1025 // Emit reduction copy.
1026 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +00001027 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001028 OASELValueUB, OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001029 // Emit VarDecl with copy init for arrays.
1030 // Get the address of the original variable captured in current
1031 // captured region.
1032 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
1033 OASELValueLB.getPointer());
1034 Size = Builder.CreateNUWAdd(
1035 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
1036 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1037 *this, cast<OpaqueValueExpr>(
1038 getContext()
1039 .getAsVariableArrayType(PrivateVD->getType())
1040 ->getSizeExpr()),
1041 RValue::get(Size));
1042 EmitVariablyModifiedType(PrivateVD->getType());
1043 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1044 auto Addr = Emission.getAllocatedAddress();
1045 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001046 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
1047 DRD ? *IRed : Init,
1048 OASELValueLB.getAddress());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001049 EmitAutoVarCleanups(Emission);
1050 // Emit private VarDecl with reduction init.
1051 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
1052 OASELValueLB.getPointer());
1053 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +00001054 return castToBase(*this, OrigVD->getType(),
1055 OASELValueLB.getType(), OriginalBaseLValue,
1056 Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001057 });
1058 assert(IsRegistered && "private var already registered as private");
1059 // Silence the warning about unused variable.
1060 (void)IsRegistered;
1061 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1062 return GetAddrOfLocalVar(PrivateVD);
1063 });
1064 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
1065 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1066 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1067 Base = TempASE->getBase()->IgnoreParenImpCasts();
1068 auto *DE = cast<DeclRefExpr>(Base);
1069 auto *OrigVD = cast<VarDecl>(DE->getDecl());
1070 auto ASELValue = EmitLValue(ASE);
1071 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +00001072 LValue BaseLValue = loadToBegin(
1073 *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001074 // Store the address of the original variable associated with the LHS
1075 // implicit variable.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00001076 PrivateScope.addPrivate(
1077 LHSVD, [ASELValue]() -> Address { return ASELValue.getAddress(); });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001078 // Emit reduction copy.
1079 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +00001080 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001081 OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001082 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001083 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1084 auto Addr = Emission.getAllocatedAddress();
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +00001085 if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001086 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
1087 ASELValue.getAddress(),
1088 ASELValue.getType());
1089 } else
1090 EmitAutoVarInit(Emission);
1091 EmitAutoVarCleanups(Emission);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001092 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
1093 ASELValue.getPointer());
1094 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +00001095 return castToBase(*this, OrigVD->getType(), ASELValue.getType(),
1096 OriginalBaseLValue, Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001097 });
1098 assert(IsRegistered && "private var already registered as private");
1099 // Silence the warning about unused variable.
1100 (void)IsRegistered;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001101 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1102 return Builder.CreateElementBitCast(
1103 GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
1104 "rhs.begin");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001105 });
1106 } else {
1107 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
Alexey Bataev1189bd02016-01-26 12:20:39 +00001108 QualType Type = PrivateVD->getType();
1109 if (getContext().getAsArrayType(Type)) {
1110 // Store the address of the original variable associated with the LHS
1111 // implicit variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001112 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1113 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1114 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataev1189bd02016-01-26 12:20:39 +00001115 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001116 PrivateScope.addPrivate(LHSVD, [this, &OriginalAddr,
Alexey Bataev1189bd02016-01-26 12:20:39 +00001117 LHSVD]() -> Address {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001118 OriginalAddr = Builder.CreateElementBitCast(
1119 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1120 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001121 });
1122 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
1123 if (Type->isVariablyModifiedType()) {
1124 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1125 *this, cast<OpaqueValueExpr>(
1126 getContext()
1127 .getAsVariableArrayType(PrivateVD->getType())
1128 ->getSizeExpr()),
1129 RValue::get(
1130 getTypeSize(OrigVD->getType().getNonReferenceType())));
1131 EmitVariablyModifiedType(Type);
1132 }
1133 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1134 auto Addr = Emission.getAllocatedAddress();
1135 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001136 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
1137 DRD ? *IRed : Init, OriginalAddr);
Alexey Bataev1189bd02016-01-26 12:20:39 +00001138 EmitAutoVarCleanups(Emission);
1139 return Emission.getAllocatedAddress();
1140 });
1141 assert(IsRegistered && "private var already registered as private");
1142 // Silence the warning about unused variable.
1143 (void)IsRegistered;
1144 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1145 return Builder.CreateElementBitCast(
1146 GetAddrOfLocalVar(PrivateVD),
1147 ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
1148 });
1149 } else {
1150 // Store the address of the original variable associated with the LHS
1151 // implicit variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001152 Address OriginalAddr = Address::invalid();
1153 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef,
1154 &OriginalAddr]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001155 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1156 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1157 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001158 OriginalAddr = EmitLValue(&DRE).getAddress();
1159 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001160 });
1161 // Emit reduction copy.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001162 bool IsRegistered = PrivateScope.addPrivate(
1163 OrigVD, [this, PrivateVD, OriginalAddr, DRD, IRed]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001164 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001165 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1166 auto Addr = Emission.getAllocatedAddress();
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +00001167 if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001168 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
1169 OriginalAddr,
1170 PrivateVD->getType());
1171 } else
1172 EmitAutoVarInit(Emission);
1173 EmitAutoVarCleanups(Emission);
1174 return Addr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001175 });
1176 assert(IsRegistered && "private var already registered as private");
1177 // Silence the warning about unused variable.
1178 (void)IsRegistered;
1179 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1180 return GetAddrOfLocalVar(PrivateVD);
1181 });
1182 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001183 }
Richard Trieucc3949d2016-02-18 22:34:54 +00001184 ++ILHS;
1185 ++IRHS;
1186 ++IPriv;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001187 ++IRed;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001188 }
1189 }
1190}
1191
1192void CodeGenFunction::EmitOMPReductionClauseFinal(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001193 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001194 if (!HaveInsertPoint())
1195 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001196 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001197 llvm::SmallVector<const Expr *, 8> LHSExprs;
1198 llvm::SmallVector<const Expr *, 8> RHSExprs;
1199 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001200 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001201 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001202 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001203 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001204 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1205 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1206 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1207 }
1208 if (HasAtLeastOneReduction) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001209 bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1210 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1211 D.getDirectiveKind() == OMPD_simd;
1212 bool SimpleReduction = D.getDirectiveKind() == OMPD_simd;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001213 // Emit nowait reduction if nowait clause is present or directive is a
1214 // parallel directive (it always has implicit barrier).
1215 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001216 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001217 {WithNowait, SimpleReduction, ReductionKind});
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001218 }
1219}
1220
Alexey Bataev61205072016-03-02 04:57:40 +00001221static void emitPostUpdateForReductionClause(
1222 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1223 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1224 if (!CGF.HaveInsertPoint())
1225 return;
1226 llvm::BasicBlock *DoneBB = nullptr;
1227 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1228 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1229 if (!DoneBB) {
1230 if (auto *Cond = CondGen(CGF)) {
1231 // If the first post-update expression is found, emit conditional
1232 // block if it was requested.
1233 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1234 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1235 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1236 CGF.EmitBlock(ThenBB);
1237 }
1238 }
1239 CGF.EmitIgnoredExpr(PostUpdate);
1240 }
1241 }
1242 if (DoneBB)
1243 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1244}
1245
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001246static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
1247 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001248 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001249 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001250 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1251 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1252 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001253 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001254 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001255 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1256 /*IgnoreResultAssign*/ true);
1257 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1258 CGF, NumThreads, NumThreadsClause->getLocStart());
1259 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001260 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001261 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001262 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1263 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1264 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001265 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001266 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1267 if (C->getNameModifier() == OMPD_unknown ||
1268 C->getNameModifier() == OMPD_parallel) {
1269 IfCond = C->getCondition();
1270 break;
1271 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001272 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001273
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001274 OMPParallelScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001275 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
1276 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001277 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001278 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001279}
1280
1281void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001282 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001283 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001284 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001285 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001286 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1287 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001288 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001289 // propagation master's thread values of threadprivate variables to local
1290 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001291 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1292 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1293 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001294 }
1295 CGF.EmitOMPPrivateClause(S, PrivateScope);
1296 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1297 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001298 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001299 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001300 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001301 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev61205072016-03-02 04:57:40 +00001302 emitPostUpdateForReductionClause(
1303 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001304}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001305
Alexey Bataev0f34da12015-07-02 04:17:07 +00001306void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1307 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001308 RunCleanupsScope BodyScope(*this);
1309 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001310 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001311 EmitIgnoredExpr(I);
1312 }
Alexander Musman3276a272015-03-21 10:12:56 +00001313 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001314 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001315 for (auto *U : C->updates())
Alexander Musman3276a272015-03-21 10:12:56 +00001316 EmitIgnoredExpr(U);
Alexander Musman3276a272015-03-21 10:12:56 +00001317 }
1318
Alexander Musmana5f070a2014-10-01 06:03:56 +00001319 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001320 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001321 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001322 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001323 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001324 // The end (updates/cleanups).
1325 EmitBlock(Continue.getBlock());
1326 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001327}
1328
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001329void CodeGenFunction::EmitOMPInnerLoop(
1330 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1331 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001332 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1333 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001334 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001335
1336 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001337 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001338 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001339 const SourceRange &R = S.getSourceRange();
1340 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1341 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001342
1343 // If there are any cleanups between here and the loop-exit scope,
1344 // create a block to stage a loop exit along.
1345 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001346 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001347 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001348
Alexander Musmand196ef22014-10-07 08:57:09 +00001349 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001350
Alexey Bataev2df54a02015-03-12 08:53:29 +00001351 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001352 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001353 if (ExitBlock != LoopExit.getBlock()) {
1354 EmitBlock(ExitBlock);
1355 EmitBranchThroughCleanup(LoopExit);
1356 }
1357
1358 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001359 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001360
1361 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001362 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001363 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1364
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001365 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001366
1367 // Emit "IV = IV + 1" and a back-edge to the condition block.
1368 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001369 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001370 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001371 BreakContinueStack.pop_back();
1372 EmitBranch(CondBlock);
1373 LoopStack.pop();
1374 // Emit the fall-through block.
1375 EmitBlock(LoopExit.getBlock());
1376}
1377
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001378void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001379 if (!HaveInsertPoint())
1380 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001381 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001382 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001383 for (auto *Init : C->inits()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001384 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001385 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1386 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1387 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1388 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1389 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1390 VD->getInit()->getType(), VK_LValue,
1391 VD->getInit()->getExprLoc());
1392 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1393 VD->getType()),
1394 /*capturedByInit=*/false);
1395 EmitAutoVarCleanups(Emission);
1396 } else
1397 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001398 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001399 // Emit the linear steps for the linear clauses.
1400 // If a step is not constant, it is pre-calculated before the loop.
1401 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1402 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001403 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001404 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001405 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001406 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001407 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001408}
1409
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001410void CodeGenFunction::EmitOMPLinearClauseFinal(
1411 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001412 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001413 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001414 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001415 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001416 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001417 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001418 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001419 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001420 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001421 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001422 // If the first post-update expression is found, emit conditional
1423 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001424 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1425 DoneBB = createBasicBlock(".omp.linear.pu.done");
1426 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1427 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001428 }
1429 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001430 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1431 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001432 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001433 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001434 Address OrigAddr = EmitLValue(&DRE).getAddress();
1435 CodeGenFunction::OMPPrivateScope VarScope(*this);
1436 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001437 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001438 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001439 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001440 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001441 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001442 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001443 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001444 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001445 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001446}
1447
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001448static void emitAlignedClause(CodeGenFunction &CGF,
1449 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001450 if (!CGF.HaveInsertPoint())
1451 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001452 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001453 unsigned ClauseAlignment = 0;
1454 if (auto AlignmentExpr = Clause->getAlignment()) {
1455 auto AlignmentCI =
1456 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1457 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001458 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001459 for (auto E : Clause->varlists()) {
1460 unsigned Alignment = ClauseAlignment;
1461 if (Alignment == 0) {
1462 // OpenMP [2.8.1, Description]
1463 // If no optional parameter is specified, implementation-defined default
1464 // alignments for SIMD instructions on the target platforms are assumed.
1465 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001466 CGF.getContext()
1467 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1468 E->getType()->getPointeeType()))
1469 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001470 }
1471 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1472 "alignment is not power of 2");
1473 if (Alignment != 0) {
1474 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1475 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1476 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001477 }
1478 }
1479}
1480
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001481void CodeGenFunction::EmitOMPPrivateLoopCounters(
1482 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1483 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001484 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001485 auto I = S.private_counters().begin();
1486 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001487 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1488 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001489 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001490 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001491 if (!LocalDeclMap.count(PrivateVD)) {
1492 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1493 EmitAutoVarCleanups(VarEmission);
1494 }
1495 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1496 /*RefersToEnclosingVariableOrCapture=*/false,
1497 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1498 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001499 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001500 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1501 VD->hasGlobalStorage()) {
1502 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1503 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1504 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1505 E->getType(), VK_LValue, E->getExprLoc());
1506 return EmitLValue(&DRE).getAddress();
1507 });
1508 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001509 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001510 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001511}
1512
Alexey Bataev62dbb972015-04-22 11:59:37 +00001513static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1514 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1515 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001516 if (!CGF.HaveInsertPoint())
1517 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001518 {
1519 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001520 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001521 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001522 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001523 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001524 CGF.EmitIgnoredExpr(I);
1525 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001526 }
1527 // Check that loop is executed at least one time.
1528 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1529}
1530
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001531void CodeGenFunction::EmitOMPLinearClause(
1532 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1533 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001534 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001535 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1536 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1537 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1538 for (auto *C : LoopDirective->counters()) {
1539 SIMDLCVs.insert(
1540 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1541 }
1542 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001543 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001544 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001545 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001546 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1547 auto *PrivateVD =
1548 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001549 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1550 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1551 // Emit private VarDecl with copy init.
1552 EmitVarDecl(*PrivateVD);
1553 return GetAddrOfLocalVar(PrivateVD);
1554 });
1555 assert(IsRegistered && "linear var already registered as private");
1556 // Silence the warning about unused variable.
1557 (void)IsRegistered;
1558 } else
1559 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001560 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001561 }
1562 }
1563}
1564
Alexey Bataev45bfad52015-08-21 12:19:04 +00001565static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001566 const OMPExecutableDirective &D,
1567 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001568 if (!CGF.HaveInsertPoint())
1569 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001570 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001571 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1572 /*ignoreResult=*/true);
1573 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1574 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1575 // In presence of finite 'safelen', it may be unsafe to mark all
1576 // the memory instructions parallel, because loop-carried
1577 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001578 if (!IsMonotonic)
1579 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001580 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001581 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1582 /*ignoreResult=*/true);
1583 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001584 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001585 // In presence of finite 'safelen', it may be unsafe to mark all
1586 // the memory instructions parallel, because loop-carried
1587 // dependences of 'safelen' iterations are possible.
1588 CGF.LoopStack.setParallel(false);
1589 }
1590}
1591
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001592void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1593 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001594 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001595 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001596 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001597 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001598}
1599
Alexey Bataevef549a82016-03-09 09:49:09 +00001600void CodeGenFunction::EmitOMPSimdFinal(
1601 const OMPLoopDirective &D,
1602 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001603 if (!HaveInsertPoint())
1604 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001605 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001606 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001607 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001608 for (auto F : D.finals()) {
1609 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001610 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1611 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1612 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1613 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001614 if (!DoneBB) {
1615 if (auto *Cond = CondGen(*this)) {
1616 // If the first post-update expression is found, emit conditional
1617 // block if it was requested.
1618 auto *ThenBB = createBasicBlock(".omp.final.then");
1619 DoneBB = createBasicBlock(".omp.final.done");
1620 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1621 EmitBlock(ThenBB);
1622 }
1623 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001624 Address OrigAddr = Address::invalid();
1625 if (CED)
1626 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1627 else {
1628 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1629 /*RefersToEnclosingVariableOrCapture=*/false,
1630 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1631 OrigAddr = EmitLValue(&DRE).getAddress();
1632 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001633 OMPPrivateScope VarScope(*this);
1634 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001635 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001636 (void)VarScope.Privatize();
1637 EmitIgnoredExpr(F);
1638 }
1639 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001640 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001641 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001642 if (DoneBB)
1643 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001644}
1645
Alexander Musman515ad8c2014-05-22 08:54:05 +00001646void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001647 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00001648 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001649 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001650 // for (IV in 0..LastIteration) BODY;
1651 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001652 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001653 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001654
Alexey Bataev62dbb972015-04-22 11:59:37 +00001655 // Emit: if (PreCond) - begin.
1656 // If the condition constant folds and can be elided, avoid emitting the
1657 // whole loop.
1658 bool CondConstant;
1659 llvm::BasicBlock *ContBlock = nullptr;
1660 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1661 if (!CondConstant)
1662 return;
1663 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001664 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1665 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001666 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1667 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001668 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001669 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001670 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001671
1672 // Emit the loop iteration variable.
1673 const Expr *IVExpr = S.getIterationVariable();
1674 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1675 CGF.EmitVarDecl(*IVDecl);
1676 CGF.EmitIgnoredExpr(S.getInit());
1677
1678 // Emit the iterations count variable.
1679 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001680 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001681 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1682 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1683 // Emit calculation of the iterations count.
1684 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001685 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001686
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001687 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001688
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001689 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001690 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001691 {
1692 OMPPrivateScope LoopScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001693 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1694 CGF.EmitOMPLinearClause(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001695 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001696 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001697 bool HasLastprivateClause =
1698 CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001699 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001700 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1701 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001702 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001703 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001704 CGF.EmitStopPoint(&S);
1705 },
1706 [](CodeGenFunction &) {});
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001707 CGF.EmitOMPSimdFinal(
1708 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001709 // Emit final copy of the lastprivate variables at the end of loops.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001710 if (HasLastprivateClause)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001711 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001712 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
Alexey Bataev61205072016-03-02 04:57:40 +00001713 emitPostUpdateForReductionClause(
1714 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001715 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001716 CGF.EmitOMPLinearClauseFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001717 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001718 // Emit: if (PreCond) - end.
1719 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001720 CGF.EmitBranch(ContBlock);
1721 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001722 }
1723 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00001724 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001725 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001726}
1727
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001728void CodeGenFunction::EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001729 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1730 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001731 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001732
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001733 const Expr *IVExpr = S.getIterationVariable();
1734 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1735 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1736
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001737 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1738
1739 // Start the loop with a block that tests the condition.
1740 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1741 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001742 const SourceRange &R = S.getSourceRange();
1743 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1744 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001745
1746 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001747 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001748 // UB = min(UB, GlobalUB)
1749 EmitIgnoredExpr(S.getEnsureUpperBound());
1750 // IV = LB
1751 EmitIgnoredExpr(S.getInit());
1752 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001753 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001754 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00001755 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, IL,
1756 LB, UB, ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001757 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001758
1759 // If there are any cleanups between here and the loop-exit scope,
1760 // create a block to stage a loop exit along.
1761 auto ExitBlock = LoopExit.getBlock();
1762 if (LoopScope.requiresCleanups())
1763 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1764
1765 auto LoopBody = createBasicBlock("omp.dispatch.body");
1766 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1767 if (ExitBlock != LoopExit.getBlock()) {
1768 EmitBlock(ExitBlock);
1769 EmitBranchThroughCleanup(LoopExit);
1770 }
1771 EmitBlock(LoopBody);
1772
Alexander Musman92bdaab2015-03-12 13:37:50 +00001773 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1774 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001775 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001776 EmitIgnoredExpr(S.getInit());
1777
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001778 // Create a block for the increment.
1779 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1780 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1781
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001782 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1783 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001784 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1785 LoopStack.setParallel(!IsMonotonic);
1786 else
1787 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001788
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001789 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001790 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1791 [&S, LoopExit](CodeGenFunction &CGF) {
1792 CGF.EmitOMPLoopBody(S, LoopExit);
1793 CGF.EmitStopPoint(&S);
1794 },
1795 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1796 if (Ordered) {
1797 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1798 CGF, Loc, IVSize, IVSigned);
1799 }
1800 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001801
1802 EmitBlock(Continue.getBlock());
1803 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001804 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001805 // Emit "LB = LB + Stride", "UB = UB + Stride".
1806 EmitIgnoredExpr(S.getNextLowerBound());
1807 EmitIgnoredExpr(S.getNextUpperBound());
1808 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001809
1810 EmitBranch(CondBlock);
1811 LoopStack.pop();
1812 // Emit the fall-through block.
1813 EmitBlock(LoopExit.getBlock());
1814
1815 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001816 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1817 if (!DynamicOrOrdered)
1818 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
1819 };
1820 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001821}
1822
1823void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001824 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001825 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1826 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1827 auto &RT = CGM.getOpenMPRuntime();
1828
1829 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001830 const bool DynamicOrOrdered =
1831 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001832
1833 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001834 !RT.isStaticNonchunked(ScheduleKind.Schedule,
1835 /*Chunked=*/Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001836 "static non-chunked schedule does not need outer loop");
1837
1838 // Emit outer loop.
1839 //
1840 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1841 // When schedule(dynamic,chunk_size) is specified, the iterations are
1842 // distributed to threads in the team in chunks as the threads request them.
1843 // Each thread executes a chunk of iterations, then requests another chunk,
1844 // until no chunks remain to be distributed. Each chunk contains chunk_size
1845 // iterations, except for the last chunk to be distributed, which may have
1846 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1847 //
1848 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1849 // to threads in the team in chunks as the executing threads request them.
1850 // Each thread executes a chunk of iterations, then requests another chunk,
1851 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1852 // each chunk is proportional to the number of unassigned iterations divided
1853 // by the number of threads in the team, decreasing to 1. For a chunk_size
1854 // with value k (greater than 1), the size of each chunk is determined in the
1855 // same way, with the restriction that the chunks do not contain fewer than k
1856 // iterations (except for the last chunk to be assigned, which may have fewer
1857 // than k iterations).
1858 //
1859 // When schedule(auto) is specified, the decision regarding scheduling is
1860 // delegated to the compiler and/or runtime system. The programmer gives the
1861 // implementation the freedom to choose any possible mapping of iterations to
1862 // threads in the team.
1863 //
1864 // When schedule(runtime) is specified, the decision regarding scheduling is
1865 // deferred until run time, and the schedule and chunk size are taken from the
1866 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1867 // implementation defined
1868 //
1869 // while(__kmpc_dispatch_next(&LB, &UB)) {
1870 // idx = LB;
1871 // while (idx <= UB) { BODY; ++idx;
1872 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1873 // } // inner loop
1874 // }
1875 //
1876 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1877 // When schedule(static, chunk_size) is specified, iterations are divided into
1878 // chunks of size chunk_size, and the chunks are assigned to the threads in
1879 // the team in a round-robin fashion in the order of the thread number.
1880 //
1881 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1882 // while (idx <= UB) { BODY; ++idx; } // inner loop
1883 // LB = LB + ST;
1884 // UB = UB + ST;
1885 // }
1886 //
1887
1888 const Expr *IVExpr = S.getIterationVariable();
1889 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1890 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1891
1892 if (DynamicOrOrdered) {
1893 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001894 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
1895 IVSigned, Ordered, UBVal, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001896 } else {
1897 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
1898 Ordered, IL, LB, UB, ST, Chunk);
1899 }
1900
Carlo Bertolli0ff587d2016-03-07 16:19:13 +00001901 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, Ordered, LB, UB,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001902 ST, IL, Chunk);
1903}
1904
1905void CodeGenFunction::EmitOMPDistributeOuterLoop(
1906 OpenMPDistScheduleClauseKind ScheduleKind,
1907 const OMPDistributeDirective &S, OMPPrivateScope &LoopScope,
1908 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1909
1910 auto &RT = CGM.getOpenMPRuntime();
1911
1912 // Emit outer loop.
1913 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1914 // dynamic
1915 //
1916
1917 const Expr *IVExpr = S.getIterationVariable();
1918 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1919 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1920
1921 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
1922 IVSize, IVSigned, /* Ordered = */ false,
1923 IL, LB, UB, ST, Chunk);
1924
1925 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false,
1926 S, LoopScope, /* Ordered = */ false, LB, UB, ST, IL, Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001927}
1928
Carlo Bertolli9925f152016-06-27 14:55:37 +00001929void CodeGenFunction::EmitOMPDistributeParallelForDirective(
1930 const OMPDistributeParallelForDirective &S) {
1931 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1932 CGM.getOpenMPRuntime().emitInlinedDirective(
1933 *this, OMPD_distribute_parallel_for,
1934 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1935 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev957d8562016-11-17 15:12:05 +00001936 OMPCancelStackRAII CancelRegion(CGF, OMPD_distribute_parallel_for,
1937 /*HasCancel=*/false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00001938 CGF.EmitStmt(
1939 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1940 });
1941}
1942
Kelvin Li4a39add2016-07-05 05:00:15 +00001943void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
1944 const OMPDistributeParallelForSimdDirective &S) {
1945 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1946 CGM.getOpenMPRuntime().emitInlinedDirective(
1947 *this, OMPD_distribute_parallel_for_simd,
1948 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1949 OMPLoopScope PreInitScope(CGF, S);
1950 CGF.EmitStmt(
1951 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1952 });
1953}
Kelvin Li787f3fc2016-07-06 04:45:38 +00001954
1955void CodeGenFunction::EmitOMPDistributeSimdDirective(
1956 const OMPDistributeSimdDirective &S) {
1957 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1958 CGM.getOpenMPRuntime().emitInlinedDirective(
1959 *this, OMPD_distribute_simd,
1960 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1961 OMPLoopScope PreInitScope(CGF, S);
1962 CGF.EmitStmt(
1963 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1964 });
1965}
1966
Kelvin Lia579b912016-07-14 02:54:56 +00001967void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
1968 const OMPTargetParallelForSimdDirective &S) {
1969 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1970 CGM.getOpenMPRuntime().emitInlinedDirective(
1971 *this, OMPD_target_parallel_for_simd,
1972 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1973 OMPLoopScope PreInitScope(CGF, S);
1974 CGF.EmitStmt(
1975 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1976 });
1977}
1978
Kelvin Li986330c2016-07-20 22:57:10 +00001979void CodeGenFunction::EmitOMPTargetSimdDirective(
1980 const OMPTargetSimdDirective &S) {
1981 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1982 CGM.getOpenMPRuntime().emitInlinedDirective(
1983 *this, OMPD_target_simd, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1984 OMPLoopScope PreInitScope(CGF, S);
1985 CGF.EmitStmt(
1986 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1987 });
1988}
1989
Kelvin Li02532872016-08-05 14:37:37 +00001990void CodeGenFunction::EmitOMPTeamsDistributeDirective(
1991 const OMPTeamsDistributeDirective &S) {
1992 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1993 CGM.getOpenMPRuntime().emitInlinedDirective(
1994 *this, OMPD_teams_distribute,
1995 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1996 OMPLoopScope PreInitScope(CGF, S);
1997 CGF.EmitStmt(
1998 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1999 });
2000}
2001
Kelvin Li4e325f72016-10-25 12:50:55 +00002002void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
2003 const OMPTeamsDistributeSimdDirective &S) {
2004 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2005 CGM.getOpenMPRuntime().emitInlinedDirective(
2006 *this, OMPD_teams_distribute_simd,
2007 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2008 OMPLoopScope PreInitScope(CGF, S);
2009 CGF.EmitStmt(
2010 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2011 });
2012}
2013
Kelvin Li579e41c2016-11-30 23:51:03 +00002014void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
2015 const OMPTeamsDistributeParallelForSimdDirective &S) {
2016 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2017 CGM.getOpenMPRuntime().emitInlinedDirective(
2018 *this, OMPD_teams_distribute_parallel_for_simd,
2019 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2020 OMPLoopScope PreInitScope(CGF, S);
2021 CGF.EmitStmt(
2022 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2023 });
2024}
Kelvin Li4e325f72016-10-25 12:50:55 +00002025
Kelvin Li7ade93f2016-12-09 03:24:30 +00002026void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
2027 const OMPTeamsDistributeParallelForDirective &S) {
2028 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2029 CGM.getOpenMPRuntime().emitInlinedDirective(
2030 *this, OMPD_teams_distribute_parallel_for,
2031 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2032 OMPLoopScope PreInitScope(CGF, S);
2033 CGF.EmitStmt(
2034 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2035 });
2036}
2037
Kelvin Li83c451e2016-12-25 04:52:54 +00002038void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
2039 const OMPTargetTeamsDistributeDirective &S) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002040 CGM.getOpenMPRuntime().emitInlinedDirective(
2041 *this, OMPD_target_teams_distribute,
Kelvin Li83c451e2016-12-25 04:52:54 +00002042 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002043 CGF.EmitStmt(
2044 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Kelvin Li83c451e2016-12-25 04:52:54 +00002045 });
2046}
2047
Kelvin Li80e8f562016-12-29 22:16:30 +00002048void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
2049 const OMPTargetTeamsDistributeParallelForDirective &S) {
2050 CGM.getOpenMPRuntime().emitInlinedDirective(
2051 *this, OMPD_target_teams_distribute_parallel_for,
2052 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2053 CGF.EmitStmt(
2054 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2055 });
2056}
2057
Kelvin Li1851df52017-01-03 05:23:48 +00002058void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2059 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
2060 CGM.getOpenMPRuntime().emitInlinedDirective(
2061 *this, OMPD_target_teams_distribute_parallel_for_simd,
2062 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2063 CGF.EmitStmt(
2064 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2065 });
2066}
2067
Kelvin Lida681182017-01-10 18:08:18 +00002068void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
2069 const OMPTargetTeamsDistributeSimdDirective &S) {
2070 CGM.getOpenMPRuntime().emitInlinedDirective(
2071 *this, OMPD_target_teams_distribute_simd,
2072 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2073 CGF.EmitStmt(
2074 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2075 });
2076}
2077
Alexander Musmanc6388682014-12-15 07:07:06 +00002078/// \brief Emit a helper variable and return corresponding lvalue.
2079static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
2080 const DeclRefExpr *Helper) {
2081 auto VDecl = cast<VarDecl>(Helper->getDecl());
2082 CGF.EmitVarDecl(*VDecl);
2083 return CGF.EmitLValue(Helper);
2084}
2085
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002086namespace {
2087 struct ScheduleKindModifiersTy {
2088 OpenMPScheduleClauseKind Kind;
2089 OpenMPScheduleClauseModifier M1;
2090 OpenMPScheduleClauseModifier M2;
2091 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2092 OpenMPScheduleClauseModifier M1,
2093 OpenMPScheduleClauseModifier M2)
2094 : Kind(Kind), M1(M1), M2(M2) {}
2095 };
2096} // namespace
2097
Alexey Bataev38e89532015-04-16 04:54:05 +00002098bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002099 // Emit the loop iteration variable.
2100 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2101 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2102 EmitVarDecl(*IVDecl);
2103
2104 // Emit the iterations count variable.
2105 // If it is not a variable, Sema decided to calculate iterations count on each
2106 // iteration (e.g., it is foldable into a constant).
2107 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2108 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2109 // Emit calculation of the iterations count.
2110 EmitIgnoredExpr(S.getCalcLastIteration());
2111 }
2112
2113 auto &RT = CGM.getOpenMPRuntime();
2114
Alexey Bataev38e89532015-04-16 04:54:05 +00002115 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002116 // Check pre-condition.
2117 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002118 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002119 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002120 // If the condition constant folds and can be elided, avoid emitting the
2121 // whole loop.
2122 bool CondConstant;
2123 llvm::BasicBlock *ContBlock = nullptr;
2124 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2125 if (!CondConstant)
2126 return false;
2127 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002128 auto *ThenBlock = createBasicBlock("omp.precond.then");
2129 ContBlock = createBasicBlock("omp.precond.end");
2130 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002131 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002132 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002133 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002134 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002135
Alexey Bataev8b427062016-05-25 12:36:08 +00002136 bool Ordered = false;
2137 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2138 if (OrderedClause->getNumForLoops())
2139 RT.emitDoacrossInit(*this, S);
2140 else
2141 Ordered = true;
2142 }
2143
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002144 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002145 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002146 EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002147 // Emit helper vars inits.
2148 LValue LB =
2149 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
2150 LValue UB =
2151 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
2152 LValue ST =
2153 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2154 LValue IL =
2155 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2156
Alexander Musmanc6388682014-12-15 07:07:06 +00002157 // Emit 'then' code.
2158 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002159 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002160 if (EmitOMPFirstprivateClause(S, LoopScope)) {
2161 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002162 // initialization of firstprivate variables and post-update of
2163 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002164 CGM.getOpenMPRuntime().emitBarrierCall(
2165 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2166 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002167 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002168 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002169 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002170 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002171 EmitOMPPrivateLoopCounters(S, LoopScope);
2172 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002173 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002174
2175 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002176 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002177 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002178 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002179 ScheduleKind.Schedule = C->getScheduleKind();
2180 ScheduleKind.M1 = C->getFirstScheduleModifier();
2181 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002182 if (const auto *Ch = C->getChunkSize()) {
2183 Chunk = EmitScalarExpr(Ch);
2184 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2185 S.getIterationVariable()->getType(),
2186 S.getLocStart());
2187 }
2188 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002189 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2190 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002191 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2192 // If the static schedule kind is specified or if the ordered clause is
2193 // specified, and if no monotonic modifier is specified, the effect will
2194 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002195 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002196 /* Chunked */ Chunk != nullptr) &&
2197 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002198 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2199 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002200 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2201 // When no chunk_size is specified, the iteration space is divided into
2202 // chunks that are approximately equal in size, and at most one chunk is
2203 // distributed to each thread. Note that the size of the chunks is
2204 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00002205 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
2206 IVSize, IVSigned, Ordered,
2207 IL.getAddress(), LB.getAddress(),
2208 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002209 auto LoopExit =
2210 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002211 // UB = min(UB, GlobalUB);
2212 EmitIgnoredExpr(S.getEnsureUpperBound());
2213 // IV = LB;
2214 EmitIgnoredExpr(S.getInit());
2215 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002216 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2217 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002218 [&S, LoopExit](CodeGenFunction &CGF) {
2219 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002220 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002221 },
2222 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002223 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002224 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002225 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2226 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
2227 };
2228 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002229 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002230 const bool IsMonotonic =
2231 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2232 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2233 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2234 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002235 // Emit the outer loop, which requests its work chunk [LB..UB] from
2236 // runtime and runs the inner loop to process it.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002237 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002238 LB.getAddress(), UB.getAddress(), ST.getAddress(),
2239 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002240 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002241 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2242 EmitOMPSimdFinal(S,
2243 [&](CodeGenFunction &CGF) -> llvm::Value * {
2244 return CGF.Builder.CreateIsNotNull(
2245 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2246 });
2247 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002248 EmitOMPReductionClauseFinal(
2249 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2250 ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2251 : /*Parallel only*/ OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002252 // Emit post-update of the reduction variables if IsLastIter != 0.
2253 emitPostUpdateForReductionClause(
2254 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2255 return CGF.Builder.CreateIsNotNull(
2256 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2257 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002258 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2259 if (HasLastprivateClause)
2260 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002261 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2262 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002263 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002264 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002265 return CGF.Builder.CreateIsNotNull(
2266 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2267 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002268 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002269 if (ContBlock) {
2270 EmitBranch(ContBlock);
2271 EmitBlock(ContBlock, true);
2272 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002273 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002274 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002275}
2276
2277void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002278 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002279 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2280 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002281 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002282 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
2283 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002284 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002285 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002286 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2287 S.hasCancel());
2288 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002289
2290 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002291 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002292 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2293 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002294}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002295
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002296void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002297 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002298 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2299 PrePostActionTy &) {
2300 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
2301 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002302 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002303 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002304 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2305 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002306
2307 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002308 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002309 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2310 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002311}
2312
Alexey Bataev2df54a02015-03-12 08:53:29 +00002313static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2314 const Twine &Name,
2315 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002316 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002317 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002318 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002319 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002320}
2321
Alexey Bataev3392d762016-02-16 11:18:12 +00002322void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00002323 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2324 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002325 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002326 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2327 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002328 auto &C = CGF.CGM.getContext();
2329 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2330 // Emit helper vars inits.
2331 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2332 CGF.Builder.getInt32(0));
2333 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2334 : CGF.Builder.getInt32(0);
2335 LValue UB =
2336 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2337 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2338 CGF.Builder.getInt32(1));
2339 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2340 CGF.Builder.getInt32(0));
2341 // Loop counter.
2342 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2343 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2344 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2345 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2346 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2347 // Generate condition for loop.
2348 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +00002349 OK_Ordinary, S.getLocStart(), FPOptions());
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002350 // Increment for loop counter.
2351 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2352 S.getLocStart());
2353 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2354 // Iterate through all sections and emit a switch construct:
2355 // switch (IV) {
2356 // case 0:
2357 // <SectionStmt[0]>;
2358 // break;
2359 // ...
2360 // case <NumSection> - 1:
2361 // <SectionStmt[<NumSection> - 1]>;
2362 // break;
2363 // }
2364 // .omp.sections.exit:
2365 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2366 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2367 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2368 CS == nullptr ? 1 : CS->size());
2369 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002370 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002371 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002372 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2373 CGF.EmitBlock(CaseBB);
2374 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002375 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002376 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002377 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002378 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002379 } else {
2380 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2381 CGF.EmitBlock(CaseBB);
2382 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2383 CGF.EmitStmt(Stmt);
2384 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002385 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002386 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002387 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002388
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002389 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2390 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002391 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002392 // initialization of firstprivate variables and post-update of lastprivate
2393 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002394 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2395 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2396 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002397 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002398 CGF.EmitOMPPrivateClause(S, LoopScope);
2399 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2400 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2401 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002402
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002403 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002404 OpenMPScheduleTy ScheduleKind;
2405 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002406 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002407 CGF, S.getLocStart(), ScheduleKind, /*IVSize=*/32,
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002408 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
2409 UB.getAddress(), ST.getAddress());
2410 // UB = min(UB, GlobalUB);
2411 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2412 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2413 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2414 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2415 // IV = LB;
2416 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2417 // while (idx <= UB) { BODY; ++idx; }
2418 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2419 [](CodeGenFunction &) {});
2420 // 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 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002425 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Alexey Bataev61205072016-03-02 04:57:40 +00002426 // Emit post-update of the reduction variables if IsLastIter != 0.
2427 emitPostUpdateForReductionClause(
2428 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2429 return CGF.Builder.CreateIsNotNull(
2430 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2431 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002432
2433 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2434 if (HasLastprivates)
2435 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002436 S, /*NoFinals=*/false,
2437 CGF.Builder.CreateIsNotNull(
2438 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002439 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002440
2441 bool HasCancel = false;
2442 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2443 HasCancel = OSD->hasCancel();
2444 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2445 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002446 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002447 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2448 HasCancel);
2449 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2450 // clause. Otherwise the barrier will be generated by the codegen for the
2451 // directive.
2452 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002453 // Emit implicit barrier to synchronize threads and avoid data races on
2454 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002455 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2456 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002457 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002458}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002459
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002460void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002461 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002462 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002463 EmitSections(S);
2464 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002465 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002466 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002467 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2468 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002469 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002470}
2471
2472void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002473 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002474 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002475 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002476 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002477 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2478 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002479}
2480
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002481void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002482 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002483 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002484 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002485 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002486 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002487 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002488 // Build a list of copyprivate variables along with helper expressions
2489 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002490 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002491 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002492 DestExprs.append(C->destination_exprs().begin(),
2493 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002494 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002495 AssignmentOps.append(C->assignment_ops().begin(),
2496 C->assignment_ops().end());
2497 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002498 // Emit code for 'single' region along with 'copyprivate' clauses
2499 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2500 Action.Enter(CGF);
2501 OMPPrivateScope SingleScope(CGF);
2502 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2503 CGF.EmitOMPPrivateClause(S, SingleScope);
2504 (void)SingleScope.Privatize();
2505 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2506 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002507 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002508 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002509 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2510 CopyprivateVars, DestExprs,
2511 SrcExprs, AssignmentOps);
2512 }
2513 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2514 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002515 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002516 CGM.getOpenMPRuntime().emitBarrierCall(
2517 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002518 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002519 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002520}
2521
Alexey Bataev8d690652014-12-04 07:23:53 +00002522void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002523 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2524 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002525 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002526 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002527 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002528 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002529}
2530
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002531void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002532 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2533 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002534 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002535 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002536 Expr *Hint = nullptr;
2537 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2538 Hint = HintClause->getHint();
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002539 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002540 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2541 S.getDirectiveName().getAsString(),
2542 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002543}
2544
Alexey Bataev671605e2015-04-13 05:28:11 +00002545void CodeGenFunction::EmitOMPParallelForDirective(
2546 const OMPParallelForDirective &S) {
2547 // Emit directive as a combined directive that consists of two implicit
2548 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002549 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002550 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Alexey Bataev671605e2015-04-13 05:28:11 +00002551 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev671605e2015-04-13 05:28:11 +00002552 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002553 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002554}
2555
Alexander Musmane4e893b2014-09-23 09:33:00 +00002556void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002557 const OMPParallelForSimdDirective &S) {
2558 // Emit directive as a combined directive that consists of two implicit
2559 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002560 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002561 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002562 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002563 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002564}
2565
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002566void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002567 const OMPParallelSectionsDirective &S) {
2568 // Emit directive as a combined directive that consists of two implicit
2569 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002570 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2571 CGF.EmitSections(S);
2572 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002573 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002574}
2575
Alexey Bataev7292c292016-04-25 12:22:29 +00002576void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2577 const RegionCodeGenTy &BodyGen,
2578 const TaskGenTy &TaskGen,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002579 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002580 // Emit outlined function for task construct.
2581 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002582 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002583 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002584 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002585 // Check if the task is final
2586 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2587 // If the condition constant folds and can be elided, try to avoid emitting
2588 // the condition and the dead arm of the if/else.
2589 auto *Cond = Clause->getCondition();
2590 bool CondConstant;
2591 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2592 Data.Final.setInt(CondConstant);
2593 else
2594 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2595 } else {
2596 // By default the task is not final.
2597 Data.Final.setInt(/*IntVal=*/false);
2598 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002599 // Check if the task has 'priority' clause.
2600 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002601 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002602 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002603 Data.Priority.setPointer(EmitScalarConversion(
2604 EmitScalarExpr(Prio), Prio->getType(),
2605 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2606 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002607 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002608 // The first function argument for tasks is a thread id, the second one is a
2609 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002610 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2611 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002612 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002613 auto IRef = C->varlist_begin();
2614 for (auto *IInit : C->private_copies()) {
2615 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2616 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002617 Data.PrivateVars.push_back(*IRef);
2618 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002619 }
2620 ++IRef;
2621 }
2622 }
2623 EmittedAsPrivate.clear();
2624 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002625 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002626 auto IRef = C->varlist_begin();
2627 auto IElemInitRef = C->inits().begin();
2628 for (auto *IInit : C->private_copies()) {
2629 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2630 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002631 Data.FirstprivateVars.push_back(*IRef);
2632 Data.FirstprivateCopies.push_back(IInit);
2633 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002634 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002635 ++IRef;
2636 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002637 }
2638 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002639 // Get list of lastprivate variables (for taskloops).
2640 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2641 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2642 auto IRef = C->varlist_begin();
2643 auto ID = C->destination_exprs().begin();
2644 for (auto *IInit : C->private_copies()) {
2645 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2646 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2647 Data.LastprivateVars.push_back(*IRef);
2648 Data.LastprivateCopies.push_back(IInit);
2649 }
2650 LastprivateDstsOrigs.insert(
2651 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2652 cast<DeclRefExpr>(*IRef)});
2653 ++IRef;
2654 ++ID;
2655 }
2656 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002657 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002658 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2659 for (auto *IRef : C->varlists())
2660 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00002661 auto &&CodeGen = [&Data, CS, &BodyGen, &LastprivateDstsOrigs](
Alexey Bataevf93095a2016-05-05 08:46:22 +00002662 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002663 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002664 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002665 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2666 !Data.LastprivateVars.empty()) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002667 auto *CopyFn = CGF.Builder.CreateLoad(
2668 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2669 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2670 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2671 // Map privates.
2672 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2673 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2674 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002675 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002676 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2677 Address PrivatePtr = CGF.CreateMemTemp(
2678 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2679 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2680 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002681 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002682 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002683 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2684 Address PrivatePtr =
2685 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2686 ".firstpriv.ptr.addr");
2687 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2688 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002689 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002690 for (auto *E : Data.LastprivateVars) {
2691 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2692 Address PrivatePtr =
2693 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2694 ".lastpriv.ptr.addr");
2695 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2696 CallArgs.push_back(PrivatePtr.getPointer());
2697 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002698 CGF.EmitRuntimeCall(CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002699 for (auto &&Pair : LastprivateDstsOrigs) {
2700 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2701 DeclRefExpr DRE(
2702 const_cast<VarDecl *>(OrigVD),
2703 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2704 OrigVD) != nullptr,
2705 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2706 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2707 return CGF.EmitLValue(&DRE).getAddress();
2708 });
2709 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002710 for (auto &&Pair : PrivatePtrs) {
2711 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2712 CGF.getContext().getDeclAlign(Pair.first));
2713 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2714 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002715 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002716 (void)Scope.Privatize();
2717
2718 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002719 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002720 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002721 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2722 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2723 Data.NumberOfParts);
2724 OMPLexicalScope Scope(*this, S);
2725 TaskGen(*this, OutlinedFn, Data);
2726}
2727
2728void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2729 // Emit outlined function for task construct.
2730 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2731 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002732 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002733 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002734 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2735 if (C->getNameModifier() == OMPD_unknown ||
2736 C->getNameModifier() == OMPD_task) {
2737 IfCond = C->getCondition();
2738 break;
2739 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002740 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002741
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002742 OMPTaskDataTy Data;
2743 // Check if we should emit tied or untied task.
2744 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00002745 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
2746 CGF.EmitStmt(CS->getCapturedStmt());
2747 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002748 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00002749 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002750 const OMPTaskDataTy &Data) {
2751 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
2752 SharedsTy, CapturedStruct, IfCond,
2753 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00002754 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002755 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002756}
2757
Alexey Bataev9f797f32015-02-05 05:57:51 +00002758void CodeGenFunction::EmitOMPTaskyieldDirective(
2759 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002760 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002761}
2762
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002763void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002764 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002765}
2766
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002767void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2768 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002769}
2770
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002771void CodeGenFunction::EmitOMPTaskgroupDirective(
2772 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002773 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2774 Action.Enter(CGF);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002775 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002776 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002777 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002778 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2779}
2780
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002781void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002782 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002783 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002784 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2785 FlushClause->varlist_end());
2786 }
2787 return llvm::None;
2788 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002789}
2790
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002791void CodeGenFunction::EmitOMPDistributeLoop(const OMPDistributeDirective &S) {
2792 // Emit the loop iteration variable.
2793 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2794 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2795 EmitVarDecl(*IVDecl);
2796
2797 // Emit the iterations count variable.
2798 // If it is not a variable, Sema decided to calculate iterations count on each
2799 // iteration (e.g., it is foldable into a constant).
2800 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2801 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2802 // Emit calculation of the iterations count.
2803 EmitIgnoredExpr(S.getCalcLastIteration());
2804 }
2805
2806 auto &RT = CGM.getOpenMPRuntime();
2807
Carlo Bertolli962bb802017-01-03 18:24:42 +00002808 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002809 // Check pre-condition.
2810 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002811 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002812 // Skip the entire loop if we don't meet the precondition.
2813 // If the condition constant folds and can be elided, avoid emitting the
2814 // whole loop.
2815 bool CondConstant;
2816 llvm::BasicBlock *ContBlock = nullptr;
2817 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2818 if (!CondConstant)
2819 return;
2820 } else {
2821 auto *ThenBlock = createBasicBlock("omp.precond.then");
2822 ContBlock = createBasicBlock("omp.precond.end");
2823 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
2824 getProfileCount(&S));
2825 EmitBlock(ThenBlock);
2826 incrementProfileCounter(&S);
2827 }
2828
2829 // Emit 'then' code.
2830 {
2831 // Emit helper vars inits.
2832 LValue LB =
2833 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
2834 LValue UB =
2835 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
2836 LValue ST =
2837 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2838 LValue IL =
2839 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2840
2841 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00002842 if (EmitOMPFirstprivateClause(S, LoopScope)) {
2843 // Emit implicit barrier to synchronize threads and avoid data races on
2844 // initialization of firstprivate variables and post-update of
2845 // lastprivate variables.
2846 CGM.getOpenMPRuntime().emitBarrierCall(
2847 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2848 /*ForceSimpleCall=*/true);
2849 }
2850 EmitOMPPrivateClause(S, LoopScope);
2851 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002852 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002853 (void)LoopScope.Privatize();
2854
2855 // Detect the distribute schedule kind and chunk.
2856 llvm::Value *Chunk = nullptr;
2857 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
2858 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
2859 ScheduleKind = C->getDistScheduleKind();
2860 if (const auto *Ch = C->getChunkSize()) {
2861 Chunk = EmitScalarExpr(Ch);
2862 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2863 S.getIterationVariable()->getType(),
2864 S.getLocStart());
2865 }
2866 }
2867 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2868 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2869
2870 // OpenMP [2.10.8, distribute Construct, Description]
2871 // If dist_schedule is specified, kind must be static. If specified,
2872 // iterations are divided into chunks of size chunk_size, chunks are
2873 // assigned to the teams of the league in a round-robin fashion in the
2874 // order of the team number. When no chunk_size is specified, the
2875 // iteration space is divided into chunks that are approximately equal
2876 // in size, and at most one chunk is distributed to each team of the
2877 // league. The size of the chunks is unspecified in this case.
2878 if (RT.isStaticNonchunked(ScheduleKind,
2879 /* Chunked */ Chunk != nullptr)) {
2880 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
2881 IVSize, IVSigned, /* Ordered = */ false,
2882 IL.getAddress(), LB.getAddress(),
2883 UB.getAddress(), ST.getAddress());
2884 auto LoopExit =
2885 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
2886 // UB = min(UB, GlobalUB);
2887 EmitIgnoredExpr(S.getEnsureUpperBound());
2888 // IV = LB;
2889 EmitIgnoredExpr(S.getInit());
2890 // while (idx <= UB) { BODY; ++idx; }
2891 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2892 S.getInc(),
2893 [&S, LoopExit](CodeGenFunction &CGF) {
2894 CGF.EmitOMPLoopBody(S, LoopExit);
2895 CGF.EmitStopPoint(&S);
2896 },
2897 [](CodeGenFunction &) {});
2898 EmitBlock(LoopExit.getBlock());
2899 // Tell the runtime we are done.
2900 RT.emitForStaticFinish(*this, S.getLocStart());
2901 } else {
2902 // Emit the outer loop, which requests its work chunk [LB..UB] from
2903 // runtime and runs the inner loop to process it.
2904 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope,
2905 LB.getAddress(), UB.getAddress(), ST.getAddress(),
2906 IL.getAddress(), Chunk);
2907 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00002908
2909 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2910 if (HasLastprivateClause)
2911 EmitOMPLastprivateClauseFinal(
2912 S, /*NoFinals=*/false,
2913 Builder.CreateIsNotNull(
2914 EmitLoadOfScalar(IL, S.getLocStart())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002915 }
2916
2917 // We're now done with the loop, so jump to the continuation block.
2918 if (ContBlock) {
2919 EmitBranch(ContBlock);
2920 EmitBlock(ContBlock, true);
2921 }
2922 }
2923}
2924
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002925void CodeGenFunction::EmitOMPDistributeDirective(
2926 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002927 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002928 CGF.EmitOMPDistributeLoop(S);
2929 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002930 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002931 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
2932 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002933}
2934
Alexey Bataev5f600d62015-09-29 03:48:57 +00002935static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2936 const CapturedStmt *S) {
2937 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2938 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2939 CGF.CapturedStmtInfo = &CapStmtInfo;
2940 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2941 Fn->addFnAttr(llvm::Attribute::NoInline);
2942 return Fn;
2943}
2944
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002945void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8b427062016-05-25 12:36:08 +00002946 if (!S.getAssociatedStmt()) {
2947 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
2948 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00002949 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00002950 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002951 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002952 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
2953 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00002954 if (C) {
2955 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2956 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2957 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2958 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2959 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2960 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002961 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002962 CGF.EmitStmt(
2963 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2964 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002965 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002966 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002967 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002968}
2969
Alexey Bataevb57056f2015-01-22 06:17:56 +00002970static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002971 QualType SrcType, QualType DestType,
2972 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002973 assert(CGF.hasScalarEvaluationKind(DestType) &&
2974 "DestType must have scalar evaluation kind.");
2975 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2976 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002977 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2978 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002979 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002980 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002981}
2982
2983static CodeGenFunction::ComplexPairTy
2984convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002985 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002986 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2987 "DestType must have complex evaluation kind.");
2988 CodeGenFunction::ComplexPairTy ComplexVal;
2989 if (Val.isScalar()) {
2990 // Convert the input element to the element type of the complex.
2991 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002992 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2993 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002994 ComplexVal = CodeGenFunction::ComplexPairTy(
2995 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2996 } else {
2997 assert(Val.isComplex() && "Must be a scalar or complex.");
2998 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2999 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3000 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003001 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003002 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003003 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003004 }
3005 return ComplexVal;
3006}
3007
Alexey Bataev5e018f92015-04-23 06:35:10 +00003008static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3009 LValue LVal, RValue RVal) {
3010 if (LVal.isGlobalReg()) {
3011 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3012 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00003013 CGF.EmitAtomicStore(RVal, LVal,
3014 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3015 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003016 LVal.isVolatile(), /*IsInit=*/false);
3017 }
3018}
3019
Alexey Bataev8524d152016-01-21 12:35:58 +00003020void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3021 QualType RValTy, SourceLocation Loc) {
3022 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003023 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00003024 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3025 *this, RVal, RValTy, LVal.getType(), Loc)),
3026 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003027 break;
3028 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003029 EmitStoreOfComplex(
3030 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003031 /*isInit=*/false);
3032 break;
3033 case TEK_Aggregate:
3034 llvm_unreachable("Must be a scalar or complex.");
3035 }
3036}
3037
Alexey Bataevb57056f2015-01-22 06:17:56 +00003038static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3039 const Expr *X, const Expr *V,
3040 SourceLocation Loc) {
3041 // v = x;
3042 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3043 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3044 LValue XLValue = CGF.EmitLValue(X);
3045 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003046 RValue Res = XLValue.isGlobalReg()
3047 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003048 : CGF.EmitAtomicLoad(
3049 XLValue, Loc,
3050 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3051 : llvm::AtomicOrdering::Monotonic,
3052 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003053 // OpenMP, 2.12.6, atomic Construct
3054 // Any atomic construct with a seq_cst clause forces the atomically
3055 // performed operation to include an implicit flush operation without a
3056 // list.
3057 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003058 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003059 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003060}
3061
Alexey Bataevb8329262015-02-27 06:33:30 +00003062static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3063 const Expr *X, const Expr *E,
3064 SourceLocation Loc) {
3065 // x = expr;
3066 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003067 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003068 // OpenMP, 2.12.6, atomic Construct
3069 // Any atomic construct with a seq_cst clause forces the atomically
3070 // performed operation to include an implicit flush operation without a
3071 // list.
3072 if (IsSeqCst)
3073 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3074}
3075
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003076static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3077 RValue Update,
3078 BinaryOperatorKind BO,
3079 llvm::AtomicOrdering AO,
3080 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003081 auto &Context = CGF.CGM.getContext();
3082 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003083 // expression is simple and atomic is allowed for the given type for the
3084 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003085 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003086 !Update.getScalarVal()->getType()->isIntegerTy() ||
3087 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3088 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003089 X.getAddress().getElementType())) ||
3090 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003091 !Context.getTargetInfo().hasBuiltinAtomic(
3092 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003093 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003094
3095 llvm::AtomicRMWInst::BinOp RMWOp;
3096 switch (BO) {
3097 case BO_Add:
3098 RMWOp = llvm::AtomicRMWInst::Add;
3099 break;
3100 case BO_Sub:
3101 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003102 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003103 RMWOp = llvm::AtomicRMWInst::Sub;
3104 break;
3105 case BO_And:
3106 RMWOp = llvm::AtomicRMWInst::And;
3107 break;
3108 case BO_Or:
3109 RMWOp = llvm::AtomicRMWInst::Or;
3110 break;
3111 case BO_Xor:
3112 RMWOp = llvm::AtomicRMWInst::Xor;
3113 break;
3114 case BO_LT:
3115 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3116 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3117 : llvm::AtomicRMWInst::Max)
3118 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3119 : llvm::AtomicRMWInst::UMax);
3120 break;
3121 case BO_GT:
3122 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3123 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3124 : llvm::AtomicRMWInst::Min)
3125 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3126 : llvm::AtomicRMWInst::UMin);
3127 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003128 case BO_Assign:
3129 RMWOp = llvm::AtomicRMWInst::Xchg;
3130 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003131 case BO_Mul:
3132 case BO_Div:
3133 case BO_Rem:
3134 case BO_Shl:
3135 case BO_Shr:
3136 case BO_LAnd:
3137 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003138 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003139 case BO_PtrMemD:
3140 case BO_PtrMemI:
3141 case BO_LE:
3142 case BO_GE:
3143 case BO_EQ:
3144 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003145 case BO_AddAssign:
3146 case BO_SubAssign:
3147 case BO_AndAssign:
3148 case BO_OrAssign:
3149 case BO_XorAssign:
3150 case BO_MulAssign:
3151 case BO_DivAssign:
3152 case BO_RemAssign:
3153 case BO_ShlAssign:
3154 case BO_ShrAssign:
3155 case BO_Comma:
3156 llvm_unreachable("Unsupported atomic update operation");
3157 }
3158 auto *UpdateVal = Update.getScalarVal();
3159 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3160 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003161 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003162 X.getType()->hasSignedIntegerRepresentation());
3163 }
John McCall7f416cc2015-09-08 08:05:57 +00003164 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003165 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003166}
3167
Alexey Bataev5e018f92015-04-23 06:35:10 +00003168std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003169 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3170 llvm::AtomicOrdering AO, SourceLocation Loc,
3171 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3172 // Update expressions are allowed to have the following forms:
3173 // x binop= expr; -> xrval + expr;
3174 // x++, ++x -> xrval + 1;
3175 // x--, --x -> xrval - 1;
3176 // x = x binop expr; -> xrval binop expr
3177 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003178 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3179 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003180 if (X.isGlobalReg()) {
3181 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3182 // 'xrval'.
3183 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3184 } else {
3185 // Perform compare-and-swap procedure.
3186 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003187 }
3188 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003189 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003190}
3191
3192static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3193 const Expr *X, const Expr *E,
3194 const Expr *UE, bool IsXLHSInRHSPart,
3195 SourceLocation Loc) {
3196 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3197 "Update expr in 'atomic update' must be a binary operator.");
3198 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3199 // Update expressions are allowed to have the following forms:
3200 // x binop= expr; -> xrval + expr;
3201 // x++, ++x -> xrval + 1;
3202 // x--, --x -> xrval - 1;
3203 // x = x binop expr; -> xrval binop expr
3204 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003205 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003206 LValue XLValue = CGF.EmitLValue(X);
3207 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003208 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3209 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003210 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3211 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3212 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3213 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3214 auto Gen =
3215 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3216 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3217 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3218 return CGF.EmitAnyExpr(UE);
3219 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003220 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3221 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3222 // OpenMP, 2.12.6, atomic Construct
3223 // Any atomic construct with a seq_cst clause forces the atomically
3224 // performed operation to include an implicit flush operation without a
3225 // list.
3226 if (IsSeqCst)
3227 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3228}
3229
3230static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003231 QualType SourceType, QualType ResType,
3232 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003233 switch (CGF.getEvaluationKind(ResType)) {
3234 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003235 return RValue::get(
3236 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003237 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003238 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003239 return RValue::getComplex(Res.first, Res.second);
3240 }
3241 case TEK_Aggregate:
3242 break;
3243 }
3244 llvm_unreachable("Must be a scalar or complex.");
3245}
3246
3247static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3248 bool IsPostfixUpdate, const Expr *V,
3249 const Expr *X, const Expr *E,
3250 const Expr *UE, bool IsXLHSInRHSPart,
3251 SourceLocation Loc) {
3252 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3253 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3254 RValue NewVVal;
3255 LValue VLValue = CGF.EmitLValue(V);
3256 LValue XLValue = CGF.EmitLValue(X);
3257 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003258 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3259 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003260 QualType NewVValType;
3261 if (UE) {
3262 // 'x' is updated with some additional value.
3263 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3264 "Update expr in 'atomic capture' must be a binary operator.");
3265 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3266 // Update expressions are allowed to have the following forms:
3267 // x binop= expr; -> xrval + expr;
3268 // x++, ++x -> xrval + 1;
3269 // x--, --x -> xrval - 1;
3270 // x = x binop expr; -> xrval binop expr
3271 // x = expr Op x; - > expr binop xrval;
3272 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3273 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3274 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3275 NewVValType = XRValExpr->getType();
3276 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3277 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003278 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003279 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3280 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3281 RValue Res = CGF.EmitAnyExpr(UE);
3282 NewVVal = IsPostfixUpdate ? XRValue : Res;
3283 return Res;
3284 };
3285 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3286 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3287 if (Res.first) {
3288 // 'atomicrmw' instruction was generated.
3289 if (IsPostfixUpdate) {
3290 // Use old value from 'atomicrmw'.
3291 NewVVal = Res.second;
3292 } else {
3293 // 'atomicrmw' does not provide new value, so evaluate it using old
3294 // value of 'x'.
3295 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3296 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3297 NewVVal = CGF.EmitAnyExpr(UE);
3298 }
3299 }
3300 } else {
3301 // 'x' is simply rewritten with some 'expr'.
3302 NewVValType = X->getType().getNonReferenceType();
3303 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003304 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003305 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003306 NewVVal = XRValue;
3307 return ExprRValue;
3308 };
3309 // Try to perform atomicrmw xchg, otherwise simple exchange.
3310 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3311 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3312 Loc, Gen);
3313 if (Res.first) {
3314 // 'atomicrmw' instruction was generated.
3315 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3316 }
3317 }
3318 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003319 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003320 // OpenMP, 2.12.6, atomic Construct
3321 // Any atomic construct with a seq_cst clause forces the atomically
3322 // performed operation to include an implicit flush operation without a
3323 // list.
3324 if (IsSeqCst)
3325 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3326}
3327
Alexey Bataevb57056f2015-01-22 06:17:56 +00003328static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003329 bool IsSeqCst, bool IsPostfixUpdate,
3330 const Expr *X, const Expr *V, const Expr *E,
3331 const Expr *UE, bool IsXLHSInRHSPart,
3332 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003333 switch (Kind) {
3334 case OMPC_read:
3335 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3336 break;
3337 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003338 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3339 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003340 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003341 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003342 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3343 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003344 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003345 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3346 IsXLHSInRHSPart, Loc);
3347 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003348 case OMPC_if:
3349 case OMPC_final:
3350 case OMPC_num_threads:
3351 case OMPC_private:
3352 case OMPC_firstprivate:
3353 case OMPC_lastprivate:
3354 case OMPC_reduction:
3355 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003356 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003357 case OMPC_collapse:
3358 case OMPC_default:
3359 case OMPC_seq_cst:
3360 case OMPC_shared:
3361 case OMPC_linear:
3362 case OMPC_aligned:
3363 case OMPC_copyin:
3364 case OMPC_copyprivate:
3365 case OMPC_flush:
3366 case OMPC_proc_bind:
3367 case OMPC_schedule:
3368 case OMPC_ordered:
3369 case OMPC_nowait:
3370 case OMPC_untied:
3371 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003372 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003373 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003374 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003375 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003376 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003377 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003378 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003379 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003380 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003381 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003382 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003383 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003384 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003385 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003386 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003387 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003388 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003389 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003390 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003391 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003392 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3393 }
3394}
3395
3396void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003397 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003398 OpenMPClauseKind Kind = OMPC_unknown;
3399 for (auto *C : S.clauses()) {
3400 // Find first clause (skip seq_cst clause, if it is first).
3401 if (C->getClauseKind() != OMPC_seq_cst) {
3402 Kind = C->getClauseKind();
3403 break;
3404 }
3405 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003406
3407 const auto *CS =
3408 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003409 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003410 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003411 }
3412 // Processing for statements under 'atomic capture'.
3413 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3414 for (const auto *C : Compound->body()) {
3415 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3416 enterFullExpression(EWC);
3417 }
3418 }
3419 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003420
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003421 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3422 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003423 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003424 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3425 S.getV(), S.getExpr(), S.getUpdateExpr(),
3426 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003427 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003428 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003429 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003430}
3431
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003432static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3433 const OMPExecutableDirective &S,
3434 const RegionCodeGenTy &CodeGen) {
3435 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3436 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00003437 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
3438
Samuel Antaoee8fb302016-01-06 13:42:12 +00003439 llvm::Function *Fn = nullptr;
3440 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003441
Samuel Antaobed3c462015-10-02 16:14:20 +00003442 const Expr *IfCond = nullptr;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003443 // Check for the at most one if clause associated with the target region.
3444 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3445 if (C->getNameModifier() == OMPD_unknown ||
3446 C->getNameModifier() == OMPD_target) {
3447 IfCond = C->getCondition();
3448 break;
3449 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003450 }
3451
3452 // Check if we have any device clause associated with the directive.
3453 const Expr *Device = nullptr;
3454 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3455 Device = C->getDevice();
3456 }
3457
Samuel Antaoee8fb302016-01-06 13:42:12 +00003458 // Check if we have an if clause whose conditional always evaluates to false
3459 // or if we do not have any targets specified. If so the target region is not
3460 // an offload entry point.
3461 bool IsOffloadEntry = true;
3462 if (IfCond) {
3463 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003464 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003465 IsOffloadEntry = false;
3466 }
3467 if (CGM.getLangOpts().OMPTargetTriples.empty())
3468 IsOffloadEntry = false;
3469
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003470 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003471 StringRef ParentName;
3472 // In case we have Ctors/Dtors we use the complete type variant to produce
3473 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003474 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003475 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003476 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003477 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3478 else
3479 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003480 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003481
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003482 // Emit target region as a standalone region.
3483 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3484 IsOffloadEntry, CodeGen);
3485 OMPLexicalScope Scope(CGF, S);
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003486 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3487 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003488 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003489 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003490}
3491
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003492static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3493 PrePostActionTy &Action) {
3494 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3495 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3496 CGF.EmitOMPPrivateClause(S, PrivateScope);
3497 (void)PrivateScope.Privatize();
3498
3499 Action.Enter(CGF);
3500 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3501}
3502
3503void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3504 StringRef ParentName,
3505 const OMPTargetDirective &S) {
3506 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3507 emitTargetRegion(CGF, S, Action);
3508 };
3509 llvm::Function *Fn;
3510 llvm::Constant *Addr;
3511 // Emit target region as a standalone region.
3512 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3513 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3514 assert(Fn && Addr && "Target device function emission failed.");
3515}
3516
3517void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3518 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3519 emitTargetRegion(CGF, S, Action);
3520 };
3521 emitCommonOMPTargetDirective(*this, S, CodeGen);
3522}
3523
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003524static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3525 const OMPExecutableDirective &S,
3526 OpenMPDirectiveKind InnermostKind,
3527 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003528 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
3529 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
3530 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003531
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003532 const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
3533 const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003534 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003535 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3536 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003537
Carlo Bertollic6872252016-04-04 15:55:02 +00003538 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3539 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003540 }
3541
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003542 OMPTeamsScope Scope(CGF, S);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003543 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3544 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003545 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3546 CapturedVars);
3547}
3548
3549void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00003550 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003551 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003552 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003553 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3554 CGF.EmitOMPPrivateClause(S, PrivateScope);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003555 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003556 (void)PrivateScope.Privatize();
3557 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003558 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003559 };
3560 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003561 emitPostUpdateForReductionClause(
3562 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev13314bf2014-10-09 04:18:56 +00003563}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003564
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003565static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
3566 const OMPTargetTeamsDirective &S) {
3567 auto *CS = S.getCapturedStmt(OMPD_teams);
3568 Action.Enter(CGF);
3569 auto &&CodeGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3570 // TODO: Add support for clauses.
3571 CGF.EmitStmt(CS->getCapturedStmt());
3572 };
3573 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
3574}
3575
3576void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
3577 CodeGenModule &CGM, StringRef ParentName,
3578 const OMPTargetTeamsDirective &S) {
3579 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3580 emitTargetTeamsRegion(CGF, Action, S);
3581 };
3582 llvm::Function *Fn;
3583 llvm::Constant *Addr;
3584 // Emit target region as a standalone region.
3585 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3586 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3587 assert(Fn && Addr && "Target device function emission failed.");
3588}
3589
3590void CodeGenFunction::EmitOMPTargetTeamsDirective(
3591 const OMPTargetTeamsDirective &S) {
3592 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3593 emitTargetTeamsRegion(CGF, Action, S);
3594 };
3595 emitCommonOMPTargetDirective(*this, S, CodeGen);
3596}
3597
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003598void CodeGenFunction::EmitOMPCancellationPointDirective(
3599 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00003600 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
3601 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003602}
3603
Alexey Bataev80909872015-07-02 11:25:17 +00003604void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003605 const Expr *IfCond = nullptr;
3606 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3607 if (C->getNameModifier() == OMPD_unknown ||
3608 C->getNameModifier() == OMPD_cancel) {
3609 IfCond = C->getCondition();
3610 break;
3611 }
3612 }
3613 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003614 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00003615}
3616
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003617CodeGenFunction::JumpDest
3618CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00003619 if (Kind == OMPD_parallel || Kind == OMPD_task ||
3620 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003621 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003622 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00003623 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
3624 Kind == OMPD_distribute_parallel_for ||
3625 Kind == OMPD_target_parallel_for);
3626 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003627}
Michael Wong65f367f2015-07-21 13:44:28 +00003628
Samuel Antaocc10b852016-07-28 14:23:26 +00003629void CodeGenFunction::EmitOMPUseDevicePtrClause(
3630 const OMPClause &NC, OMPPrivateScope &PrivateScope,
3631 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
3632 const auto &C = cast<OMPUseDevicePtrClause>(NC);
3633 auto OrigVarIt = C.varlist_begin();
3634 auto InitIt = C.inits().begin();
3635 for (auto PvtVarIt : C.private_copies()) {
3636 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
3637 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
3638 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
3639
3640 // In order to identify the right initializer we need to match the
3641 // declaration used by the mapping logic. In some cases we may get
3642 // OMPCapturedExprDecl that refers to the original declaration.
3643 const ValueDecl *MatchingVD = OrigVD;
3644 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
3645 // OMPCapturedExprDecl are used to privative fields of the current
3646 // structure.
3647 auto *ME = cast<MemberExpr>(OED->getInit());
3648 assert(isa<CXXThisExpr>(ME->getBase()) &&
3649 "Base should be the current struct!");
3650 MatchingVD = ME->getMemberDecl();
3651 }
3652
3653 // If we don't have information about the current list item, move on to
3654 // the next one.
3655 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
3656 if (InitAddrIt == CaptureDeviceAddrMap.end())
3657 continue;
3658
3659 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
3660 // Initialize the temporary initialization variable with the address we
3661 // get from the runtime library. We have to cast the source address
3662 // because it is always a void *. References are materialized in the
3663 // privatization scope, so the initialization here disregards the fact
3664 // the original variable is a reference.
3665 QualType AddrQTy =
3666 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
3667 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
3668 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
3669 setAddrOfLocalVar(InitVD, InitAddr);
3670
3671 // Emit private declaration, it will be initialized by the value we
3672 // declaration we just added to the local declarations map.
3673 EmitDecl(*PvtVD);
3674
3675 // The initialization variables reached its purpose in the emission
3676 // ofthe previous declaration, so we don't need it anymore.
3677 LocalDeclMap.erase(InitVD);
3678
3679 // Return the address of the private variable.
3680 return GetAddrOfLocalVar(PvtVD);
3681 });
3682 assert(IsRegistered && "firstprivate var already registered as private");
3683 // Silence the warning about unused variable.
3684 (void)IsRegistered;
3685
3686 ++OrigVarIt;
3687 ++InitIt;
3688 }
3689}
3690
Michael Wong65f367f2015-07-21 13:44:28 +00003691// Generate the instructions for '#pragma omp target data' directive.
3692void CodeGenFunction::EmitOMPTargetDataDirective(
3693 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00003694 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
3695
3696 // Create a pre/post action to signal the privatization of the device pointer.
3697 // This action can be replaced by the OpenMP runtime code generation to
3698 // deactivate privatization.
3699 bool PrivatizeDevicePointers = false;
3700 class DevicePointerPrivActionTy : public PrePostActionTy {
3701 bool &PrivatizeDevicePointers;
3702
3703 public:
3704 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
3705 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
3706 void Enter(CodeGenFunction &CGF) override {
3707 PrivatizeDevicePointers = true;
3708 }
Samuel Antaodf158d52016-04-27 22:58:19 +00003709 };
Samuel Antaocc10b852016-07-28 14:23:26 +00003710 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
3711
3712 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
3713 CodeGenFunction &CGF, PrePostActionTy &Action) {
3714 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3715 CGF.EmitStmt(
3716 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3717 };
3718
3719 // Codegen that selects wheather to generate the privatization code or not.
3720 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
3721 &InnermostCodeGen](CodeGenFunction &CGF,
3722 PrePostActionTy &Action) {
3723 RegionCodeGenTy RCG(InnermostCodeGen);
3724 PrivatizeDevicePointers = false;
3725
3726 // Call the pre-action to change the status of PrivatizeDevicePointers if
3727 // needed.
3728 Action.Enter(CGF);
3729
3730 if (PrivatizeDevicePointers) {
3731 OMPPrivateScope PrivateScope(CGF);
3732 // Emit all instances of the use_device_ptr clause.
3733 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
3734 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
3735 Info.CaptureDeviceAddrMap);
3736 (void)PrivateScope.Privatize();
3737 RCG(CGF);
3738 } else
3739 RCG(CGF);
3740 };
3741
3742 // Forward the provided action to the privatization codegen.
3743 RegionCodeGenTy PrivRCG(PrivCodeGen);
3744 PrivRCG.setAction(Action);
3745
3746 // Notwithstanding the body of the region is emitted as inlined directive,
3747 // we don't use an inline scope as changes in the references inside the
3748 // region are expected to be visible outside, so we do not privative them.
3749 OMPLexicalScope Scope(CGF, S);
3750 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
3751 PrivRCG);
3752 };
3753
3754 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00003755
3756 // If we don't have target devices, don't bother emitting the data mapping
3757 // code.
3758 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00003759 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00003760 return;
3761 }
3762
3763 // Check if we have any if clause associated with the directive.
3764 const Expr *IfCond = nullptr;
3765 if (auto *C = S.getSingleClause<OMPIfClause>())
3766 IfCond = C->getCondition();
3767
3768 // Check if we have any device clause associated with the directive.
3769 const Expr *Device = nullptr;
3770 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3771 Device = C->getDevice();
3772
Samuel Antaocc10b852016-07-28 14:23:26 +00003773 // Set the action to signal privatization of device pointers.
3774 RCG.setAction(PrivAction);
3775
3776 // Emit region code.
3777 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
3778 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00003779}
Alexey Bataev49f6e782015-12-01 04:18:41 +00003780
Samuel Antaodf67fc42016-01-19 19:15:56 +00003781void CodeGenFunction::EmitOMPTargetEnterDataDirective(
3782 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00003783 // If we don't have target devices, don't bother emitting the data mapping
3784 // code.
3785 if (CGM.getLangOpts().OMPTargetTriples.empty())
3786 return;
3787
3788 // Check if we have any if clause associated with the directive.
3789 const Expr *IfCond = nullptr;
3790 if (auto *C = S.getSingleClause<OMPIfClause>())
3791 IfCond = C->getCondition();
3792
3793 // Check if we have any device clause associated with the directive.
3794 const Expr *Device = nullptr;
3795 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3796 Device = C->getDevice();
3797
Samuel Antao8d2d7302016-05-26 18:30:22 +00003798 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003799}
3800
Samuel Antao72590762016-01-19 20:04:50 +00003801void CodeGenFunction::EmitOMPTargetExitDataDirective(
3802 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00003803 // If we don't have target devices, don't bother emitting the data mapping
3804 // code.
3805 if (CGM.getLangOpts().OMPTargetTriples.empty())
3806 return;
3807
3808 // Check if we have any if clause associated with the directive.
3809 const Expr *IfCond = nullptr;
3810 if (auto *C = S.getSingleClause<OMPIfClause>())
3811 IfCond = C->getCondition();
3812
3813 // Check if we have any device clause associated with the directive.
3814 const Expr *Device = nullptr;
3815 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3816 Device = C->getDevice();
3817
Samuel Antao8d2d7302016-05-26 18:30:22 +00003818 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00003819}
3820
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003821static void emitTargetParallelRegion(CodeGenFunction &CGF,
3822 const OMPTargetParallelDirective &S,
3823 PrePostActionTy &Action) {
3824 // Get the captured statement associated with the 'parallel' region.
3825 auto *CS = S.getCapturedStmt(OMPD_parallel);
3826 Action.Enter(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003827 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
3828 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3829 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3830 CGF.EmitOMPPrivateClause(S, PrivateScope);
3831 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3832 (void)PrivateScope.Privatize();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003833 // TODO: Add support for clauses.
3834 CGF.EmitStmt(CS->getCapturedStmt());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003835 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003836 };
3837 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003838 emitPostUpdateForReductionClause(
3839 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003840}
3841
3842void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
3843 CodeGenModule &CGM, StringRef ParentName,
3844 const OMPTargetParallelDirective &S) {
3845 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3846 emitTargetParallelRegion(CGF, S, Action);
3847 };
3848 llvm::Function *Fn;
3849 llvm::Constant *Addr;
3850 // Emit target region as a standalone region.
3851 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3852 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3853 assert(Fn && Addr && "Target device function emission failed.");
3854}
3855
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003856void CodeGenFunction::EmitOMPTargetParallelDirective(
3857 const OMPTargetParallelDirective &S) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003858 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3859 emitTargetParallelRegion(CGF, S, Action);
3860 };
3861 emitCommonOMPTargetDirective(*this, S, CodeGen);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003862}
3863
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003864void CodeGenFunction::EmitOMPTargetParallelForDirective(
3865 const OMPTargetParallelForDirective &S) {
3866 // TODO: codegen for target parallel for.
3867}
3868
Alexey Bataev7292c292016-04-25 12:22:29 +00003869/// Emit a helper variable and return corresponding lvalue.
3870static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
3871 const ImplicitParamDecl *PVD,
3872 CodeGenFunction::OMPPrivateScope &Privates) {
3873 auto *VDecl = cast<VarDecl>(Helper->getDecl());
3874 Privates.addPrivate(
3875 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
3876}
3877
3878void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
3879 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
3880 // Emit outlined function for task construct.
3881 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3882 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
3883 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3884 const Expr *IfCond = nullptr;
3885 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3886 if (C->getNameModifier() == OMPD_unknown ||
3887 C->getNameModifier() == OMPD_taskloop) {
3888 IfCond = C->getCondition();
3889 break;
3890 }
3891 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003892
3893 OMPTaskDataTy Data;
3894 // Check if taskloop must be emitted without taskgroup.
3895 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003896 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003897 Data.Tied = true;
3898 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00003899 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
3900 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003901 Data.Schedule.setInt(/*IntVal=*/false);
3902 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00003903 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
3904 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003905 Data.Schedule.setInt(/*IntVal=*/true);
3906 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00003907 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003908
3909 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
3910 // if (PreCond) {
3911 // for (IV in 0..LastIteration) BODY;
3912 // <Final counter/linear vars updates>;
3913 // }
3914 //
3915
3916 // Emit: if (PreCond) - begin.
3917 // If the condition constant folds and can be elided, avoid emitting the
3918 // whole loop.
3919 bool CondConstant;
3920 llvm::BasicBlock *ContBlock = nullptr;
3921 OMPLoopScope PreInitScope(CGF, S);
3922 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3923 if (!CondConstant)
3924 return;
3925 } else {
3926 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
3927 ContBlock = CGF.createBasicBlock("taskloop.if.end");
3928 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
3929 CGF.getProfileCount(&S));
3930 CGF.EmitBlock(ThenBlock);
3931 CGF.incrementProfileCounter(&S);
3932 }
3933
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003934 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3935 CGF.EmitOMPSimdInit(S);
3936
Alexey Bataev7292c292016-04-25 12:22:29 +00003937 OMPPrivateScope LoopScope(CGF);
3938 // Emit helper vars inits.
3939 enum { LowerBound = 5, UpperBound, Stride, LastIter };
3940 auto *I = CS->getCapturedDecl()->param_begin();
3941 auto *LBP = std::next(I, LowerBound);
3942 auto *UBP = std::next(I, UpperBound);
3943 auto *STP = std::next(I, Stride);
3944 auto *LIP = std::next(I, LastIter);
3945 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
3946 LoopScope);
3947 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
3948 LoopScope);
3949 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
3950 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
3951 LoopScope);
3952 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003953 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00003954 (void)LoopScope.Privatize();
3955 // Emit the loop iteration variable.
3956 const Expr *IVExpr = S.getIterationVariable();
3957 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
3958 CGF.EmitVarDecl(*IVDecl);
3959 CGF.EmitIgnoredExpr(S.getInit());
3960
3961 // Emit the iterations count variable.
3962 // If it is not a variable, Sema decided to calculate iterations count on
3963 // each iteration (e.g., it is foldable into a constant).
3964 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3965 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3966 // Emit calculation of the iterations count.
3967 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
3968 }
3969
3970 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
3971 S.getInc(),
3972 [&S](CodeGenFunction &CGF) {
3973 CGF.EmitOMPLoopBody(S, JumpDest());
3974 CGF.EmitStopPoint(&S);
3975 },
3976 [](CodeGenFunction &) {});
3977 // Emit: if (PreCond) - end.
3978 if (ContBlock) {
3979 CGF.EmitBranch(ContBlock);
3980 CGF.EmitBlock(ContBlock, true);
3981 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003982 // Emit final copy of the lastprivate variables if IsLastIter != 0.
3983 if (HasLastprivateClause) {
3984 CGF.EmitOMPLastprivateClauseFinal(
3985 S, isOpenMPSimdDirective(S.getDirectiveKind()),
3986 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
3987 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
3988 (*LIP)->getType(), S.getLocStart())));
3989 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003990 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003991 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
3992 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
3993 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003994 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
3995 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003996 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
3997 OutlinedFn, SharedsTy,
3998 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003999 };
4000 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4001 CodeGen);
4002 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004003 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004004}
4005
Alexey Bataev49f6e782015-12-01 04:18:41 +00004006void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004007 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00004008}
4009
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004010void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4011 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00004012 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004013}
Samuel Antao686c70c2016-05-26 17:30:50 +00004014
4015// Generate the instructions for '#pragma omp target update' directive.
4016void CodeGenFunction::EmitOMPTargetUpdateDirective(
4017 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00004018 // If we don't have target devices, don't bother emitting the data mapping
4019 // code.
4020 if (CGM.getLangOpts().OMPTargetTriples.empty())
4021 return;
4022
4023 // Check if we have any if clause associated with the directive.
4024 const Expr *IfCond = nullptr;
4025 if (auto *C = S.getSingleClause<OMPIfClause>())
4026 IfCond = C->getCondition();
4027
4028 // Check if we have any device clause associated with the directive.
4029 const Expr *Device = nullptr;
4030 if (auto *C = S.getSingleClause<OMPDeviceClause>())
4031 Device = C->getDevice();
4032
4033 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00004034}