blob: 2d14ec40cbb0f87d7b510d22bc81adcfb9e06622 [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.
Alexey Bataev4ba78a42016-04-27 07:56:03 +000029class OMPLexicalScope final : 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,
57 bool AsInlined = false)
58 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
59 InlinedShareds(CGF) {
Alexey Bataev3392d762016-02-16 11:18:12 +000060 emitPreInitStmt(CGF, S);
Alexey Bataev4ba78a42016-04-27 07:56:03 +000061 if (AsInlined) {
62 if (S.hasAssociatedStmt()) {
63 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
64 for (auto &C : CS->captures()) {
65 if (C.capturesVariable() || C.capturesVariableByCopy()) {
66 auto *VD = C.getCapturedVar();
67 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
68 isCapturedVar(CGF, VD) ||
69 (CGF.CapturedStmtInfo &&
70 InlinedShareds.isGlobalVarCaptured(VD)),
71 VD->getType().getNonReferenceType(), VK_LValue,
72 SourceLocation());
73 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
74 return CGF.EmitLValue(&DRE).getAddress();
75 });
76 }
77 }
78 (void)InlinedShareds.Privatize();
79 }
80 }
Alexey Bataev3392d762016-02-16 11:18:12 +000081 }
82};
Alexey Bataev14fa1c62016-03-29 05:34:15 +000083
Alexey Bataev5a3af132016-03-29 08:58:54 +000084/// Private scope for OpenMP loop-based directives, that supports capturing
85/// of used expression from loop statement.
86class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
87 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
88 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
89 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
90 for (const auto *I : PreInits->decls())
91 CGF.EmitVarDecl(cast<VarDecl>(*I));
92 }
93 }
94 }
95
96public:
97 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
98 : CodeGenFunction::RunCleanupsScope(CGF) {
99 emitPreInitStmt(CGF, S);
100 }
101};
102
Alexey Bataev3392d762016-02-16 11:18:12 +0000103} // namespace
104
Alexey Bataev1189bd02016-01-26 12:20:39 +0000105llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
106 auto &C = getContext();
107 llvm::Value *Size = nullptr;
108 auto SizeInChars = C.getTypeSizeInChars(Ty);
109 if (SizeInChars.isZero()) {
110 // getTypeSizeInChars() returns 0 for a VLA.
111 while (auto *VAT = C.getAsVariableArrayType(Ty)) {
112 llvm::Value *ArraySize;
113 std::tie(ArraySize, Ty) = getVLASize(VAT);
114 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
115 }
116 SizeInChars = C.getTypeSizeInChars(Ty);
117 if (SizeInChars.isZero())
118 return llvm::ConstantInt::get(SizeTy, /*V=*/0);
119 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
120 } else
121 Size = CGM.getSize(SizeInChars);
122 return Size;
123}
124
Alexey Bataev2377fe92015-09-10 08:12:02 +0000125void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000126 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000127 const RecordDecl *RD = S.getCapturedRecordDecl();
128 auto CurField = RD->field_begin();
129 auto CurCap = S.captures().begin();
130 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
131 E = S.capture_init_end();
132 I != E; ++I, ++CurField, ++CurCap) {
133 if (CurField->hasCapturedVLAType()) {
134 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +0000135 auto *Val = VLASizeMap[VAT->getSizeExpr()];
Samuel Antaobed3c462015-10-02 16:14:20 +0000136 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000137 } else if (CurCap->capturesThis())
138 CapturedVars.push_back(CXXThisValue);
Samuel Antao6d004262016-06-16 18:39:34 +0000139 else if (CurCap->capturesVariableByCopy()) {
140 llvm::Value *CV =
141 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal();
142
143 // If the field is not a pointer, we need to save the actual value
144 // and load it as a void pointer.
145 if (!CurField->getType()->isAnyPointerType()) {
146 auto &Ctx = getContext();
147 auto DstAddr = CreateMemTemp(
148 Ctx.getUIntPtrType(),
149 Twine(CurCap->getCapturedVar()->getName()) + ".casted");
150 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
151
152 auto *SrcAddrVal = EmitScalarConversion(
153 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
154 Ctx.getPointerType(CurField->getType()), SourceLocation());
155 LValue SrcLV =
156 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
157
158 // Store the value using the source type pointer.
159 EmitStoreThroughLValue(RValue::get(CV), SrcLV);
160
161 // Load the value using the destination type pointer.
162 CV = EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
163 }
164 CapturedVars.push_back(CV);
165 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000166 assert(CurCap->capturesVariable() && "Expected capture by reference.");
Alexey Bataev2377fe92015-09-10 08:12:02 +0000167 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000168 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000169 }
170}
171
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000172static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
173 StringRef Name, LValue AddrLV,
174 bool isReferenceType = false) {
175 ASTContext &Ctx = CGF.getContext();
176
177 auto *CastedPtr = CGF.EmitScalarConversion(
178 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
179 Ctx.getPointerType(DstType), SourceLocation());
180 auto TmpAddr =
181 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
182 .getAddress();
183
184 // If we are dealing with references we need to return the address of the
185 // reference instead of the reference of the value.
186 if (isReferenceType) {
187 QualType RefType = Ctx.getLValueReferenceType(DstType);
188 auto *RefVal = TmpAddr.getPointer();
189 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
190 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
Akira Hatanaka642f7992016-10-18 19:05:41 +0000191 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000192 }
193
194 return TmpAddr;
195}
196
Alexey Bataev2377fe92015-09-10 08:12:02 +0000197llvm::Function *
Samuel Antao6d004262016-06-16 18:39:34 +0000198CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000199 assert(
200 CapturedStmtInfo &&
201 "CapturedStmtInfo should be set when generating the captured function");
202 const CapturedDecl *CD = S.getCapturedDecl();
203 const RecordDecl *RD = S.getCapturedRecordDecl();
204 assert(CD->hasBody() && "missing CapturedDecl body");
205
206 // Build the argument list.
207 ASTContext &Ctx = CGM.getContext();
208 FunctionArgList Args;
209 Args.append(CD->param_begin(),
210 std::next(CD->param_begin(), CD->getContextParamPosition()));
211 auto I = S.captures().begin();
212 for (auto *FD : RD->fields()) {
213 QualType ArgType = FD->getType();
214 IdentifierInfo *II = nullptr;
215 VarDecl *CapVar = nullptr;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000216
217 // If this is a capture by copy and the type is not a pointer, the outlined
218 // function argument type should be uintptr and the value properly casted to
219 // uintptr. This is necessary given that the runtime library is only able to
220 // deal with pointers. We can pass in the same way the VLA type sizes to the
221 // outlined function.
Samuel Antao6d004262016-06-16 18:39:34 +0000222 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
223 I->capturesVariableArrayType())
224 ArgType = Ctx.getUIntPtrType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000225
226 if (I->capturesVariable() || I->capturesVariableByCopy()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000227 CapVar = I->getCapturedVar();
228 II = CapVar->getIdentifier();
229 } else if (I->capturesThis())
230 II = &getContext().Idents.get("this");
231 else {
232 assert(I->capturesVariableArrayType());
233 II = &getContext().Idents.get("vla");
234 }
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000235 if (ArgType->isVariablyModifiedType()) {
236 bool IsReference = ArgType->isLValueReferenceType();
237 ArgType =
238 getContext().getCanonicalParamType(ArgType.getNonReferenceType());
239 if (IsReference && !ArgType->isPointerType()) {
240 ArgType = getContext().getLValueReferenceType(
241 ArgType, /*SpelledAsLValue=*/false);
242 }
243 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000244 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
245 FD->getLocation(), II, ArgType));
246 ++I;
247 }
248 Args.append(
249 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
250 CD->param_end());
251
252 // Create the function declaration.
253 FunctionType::ExtInfo ExtInfo;
254 const CGFunctionInfo &FuncInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000255 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000256 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
257
258 llvm::Function *F = llvm::Function::Create(
259 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
260 CapturedStmtInfo->getHelperName(), &CGM.getModule());
261 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
262 if (CD->isNothrow())
263 F->addFnAttr(llvm::Attribute::NoUnwind);
264
265 // Generate the function.
266 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
267 CD->getBody()->getLocStart());
268 unsigned Cnt = CD->getContextParamPosition();
269 I = S.captures().begin();
270 for (auto *FD : RD->fields()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000271 // If we are capturing a pointer by copy we don't need to do anything, just
272 // use the value that we get from the arguments.
273 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
Samuel Antao403ffd42016-07-27 22:49:49 +0000274 const VarDecl *CurVD = I->getCapturedVar();
275 Address LocalAddr = GetAddrOfLocalVar(Args[Cnt]);
276 // If the variable is a reference we need to materialize it here.
277 if (CurVD->getType()->isReferenceType()) {
278 Address RefAddr = CreateMemTemp(CurVD->getType(), getPointerAlign(),
279 ".materialized_ref");
280 EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr, /*Volatile=*/false,
281 CurVD->getType());
282 LocalAddr = RefAddr;
283 }
284 setAddrOfLocalVar(CurVD, LocalAddr);
Richard Trieucc3949d2016-02-18 22:34:54 +0000285 ++Cnt;
286 ++I;
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000287 continue;
288 }
289
Alexey Bataev2377fe92015-09-10 08:12:02 +0000290 LValue ArgLVal =
291 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
292 AlignmentSource::Decl);
293 if (FD->hasCapturedVLAType()) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000294 LValue CastedArgLVal =
Samuel Antao6d004262016-06-16 18:39:34 +0000295 MakeAddrLValue(castValueFromUintptr(*this, FD->getType(),
296 Args[Cnt]->getName(), ArgLVal),
297 FD->getType(), AlignmentSource::Decl);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000298 auto *ExprArg =
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000299 EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000300 auto VAT = FD->getCapturedVLAType();
301 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
302 } else if (I->capturesVariable()) {
303 auto *Var = I->getCapturedVar();
304 QualType VarTy = Var->getType();
305 Address ArgAddr = ArgLVal.getAddress();
306 if (!VarTy->isReferenceType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000307 if (ArgLVal.getType()->isLValueReferenceType()) {
308 ArgAddr = EmitLoadOfReference(
309 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
Alexey Bataevac5eabb2016-11-07 11:16:04 +0000310 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
Alexey Bataev2f5ed342016-10-13 09:52:46 +0000311 assert(ArgLVal.getType()->isPointerType());
312 ArgAddr = EmitLoadOfPointer(
313 ArgAddr, ArgLVal.getType()->castAs<PointerType>());
314 }
Alexey Bataev2377fe92015-09-10 08:12:02 +0000315 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000316 setAddrOfLocalVar(
317 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000318 } else if (I->capturesVariableByCopy()) {
319 assert(!FD->getType()->isAnyPointerType() &&
320 "Not expecting a captured pointer.");
321 auto *Var = I->getCapturedVar();
322 QualType VarTy = Var->getType();
Samuel Antao6d004262016-06-16 18:39:34 +0000323 setAddrOfLocalVar(Var, castValueFromUintptr(*this, FD->getType(),
324 Args[Cnt]->getName(), ArgLVal,
325 VarTy->isReferenceType()));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000326 } else {
327 // If 'this' is captured, load it into CXXThisValue.
328 assert(I->capturesThis());
329 CXXThisValue =
330 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
331 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000332 ++Cnt;
333 ++I;
Alexey Bataev2377fe92015-09-10 08:12:02 +0000334 }
335
Serge Pavlov3a561452015-12-06 14:32:39 +0000336 PGO.assignRegionCounters(GlobalDecl(CD), F);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000337 CapturedStmtInfo->EmitBody(*this, CD->getBody());
338 FinishFunction(CD->getBodyRBrace());
339
340 return F;
341}
342
Alexey Bataev9959db52014-05-06 10:08:46 +0000343//===----------------------------------------------------------------------===//
344// OpenMP Directive Emission
345//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000346void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000347 Address DestAddr, Address SrcAddr, QualType OriginalType,
348 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000349 // Perform element-by-element initialization.
350 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000351
352 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000353 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000354 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
355 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
356
357 auto SrcBegin = SrcAddr.getPointer();
358 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000359 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000360 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
361 // The basic structure here is a while-do loop.
362 auto BodyBB = createBasicBlock("omp.arraycpy.body");
363 auto DoneBB = createBasicBlock("omp.arraycpy.done");
364 auto IsEmpty =
365 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
366 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000367
Alexey Bataev420d45b2015-04-14 05:11:24 +0000368 // Enter the loop body, making that address the current address.
369 auto EntryBB = Builder.GetInsertBlock();
370 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000371
372 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
373
374 llvm::PHINode *SrcElementPHI =
375 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
376 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
377 Address SrcElementCurrent =
378 Address(SrcElementPHI,
379 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
380
381 llvm::PHINode *DestElementPHI =
382 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
383 DestElementPHI->addIncoming(DestBegin, EntryBB);
384 Address DestElementCurrent =
385 Address(DestElementPHI,
386 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000387
Alexey Bataev420d45b2015-04-14 05:11:24 +0000388 // Emit copy.
389 CopyGen(DestElementCurrent, SrcElementCurrent);
390
391 // Shift the address forward by one element.
392 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000393 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000394 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000395 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000396 // Check whether we've reached the end.
397 auto Done =
398 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
399 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000400 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
401 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000402
403 // Done.
404 EmitBlock(DoneBB, /*IsFinished=*/true);
405}
406
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000407/// Check if the combiner is a call to UDR combiner and if it is so return the
408/// UDR decl used for reduction.
409static const OMPDeclareReductionDecl *
410getReductionInit(const Expr *ReductionOp) {
411 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
412 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
413 if (auto *DRE =
414 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
415 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
416 return DRD;
417 return nullptr;
418}
419
420static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
421 const OMPDeclareReductionDecl *DRD,
422 const Expr *InitOp,
423 Address Private, Address Original,
424 QualType Ty) {
425 if (DRD->getInitializer()) {
426 std::pair<llvm::Function *, llvm::Function *> Reduction =
427 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
428 auto *CE = cast<CallExpr>(InitOp);
429 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
430 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
431 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
432 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
433 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
434 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
435 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
436 [=]() -> Address { return Private; });
437 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
438 [=]() -> Address { return Original; });
439 (void)PrivateScope.Privatize();
440 RValue Func = RValue::get(Reduction.second);
441 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
442 CGF.EmitIgnoredExpr(InitOp);
443 } else {
444 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
445 auto *GV = new llvm::GlobalVariable(
446 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
447 llvm::GlobalValue::PrivateLinkage, Init, ".init");
448 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
449 RValue InitRVal;
450 switch (CGF.getEvaluationKind(Ty)) {
451 case TEK_Scalar:
452 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
453 break;
454 case TEK_Complex:
455 InitRVal =
456 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
457 break;
458 case TEK_Aggregate:
459 InitRVal = RValue::getAggregate(LV.getAddress());
460 break;
461 }
462 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
463 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
464 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
465 /*IsInitializer=*/false);
466 }
467}
468
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000469/// \brief Emit initialization of arrays of complex types.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000470/// \param DestAddr Address of the array.
471/// \param Type Type of array.
472/// \param Init Initial expression of array.
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000473/// \param SrcAddr Address of the original array.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000474static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000475 QualType Type, const Expr *Init,
476 Address SrcAddr = Address::invalid()) {
477 auto *DRD = getReductionInit(Init);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000478 // Perform element-by-element initialization.
479 QualType ElementTy;
480
481 // Drill down to the base element type on both arrays.
482 auto ArrayTy = Type->getAsArrayTypeUnsafe();
483 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
484 DestAddr =
485 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000486 if (DRD)
487 SrcAddr =
488 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000489
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000490 llvm::Value *SrcBegin = nullptr;
491 if (DRD)
492 SrcBegin = SrcAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000493 auto DestBegin = DestAddr.getPointer();
494 // Cast from pointer to array type to pointer to single element.
495 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
496 // The basic structure here is a while-do loop.
497 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
498 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
499 auto IsEmpty =
500 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
501 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
502
503 // Enter the loop body, making that address the current address.
504 auto EntryBB = CGF.Builder.GetInsertBlock();
505 CGF.EmitBlock(BodyBB);
506
507 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
508
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000509 llvm::PHINode *SrcElementPHI = nullptr;
510 Address SrcElementCurrent = Address::invalid();
511 if (DRD) {
512 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
513 "omp.arraycpy.srcElementPast");
514 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
515 SrcElementCurrent =
516 Address(SrcElementPHI,
517 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
518 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000519 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
520 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
521 DestElementPHI->addIncoming(DestBegin, EntryBB);
522 Address DestElementCurrent =
523 Address(DestElementPHI,
524 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
525
526 // Emit copy.
527 {
528 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +0000529 if (DRD && (DRD->getInitializer() || !Init)) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000530 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
531 SrcElementCurrent, ElementTy);
532 } else
533 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
534 /*IsInitializer=*/false);
535 }
536
537 if (DRD) {
538 // Shift the address forward by one element.
539 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
540 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
541 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000542 }
543
544 // Shift the address forward by one element.
545 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
546 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
547 // Check whether we've reached the end.
548 auto Done =
549 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
550 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
551 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
552
553 // Done.
554 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
555}
556
John McCall7f416cc2015-09-08 08:05:57 +0000557void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
558 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000559 const VarDecl *SrcVD, const Expr *Copy) {
560 if (OriginalType->isArrayType()) {
561 auto *BO = dyn_cast<BinaryOperator>(Copy);
562 if (BO && BO->getOpcode() == BO_Assign) {
563 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000564 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000565 } else {
566 // For arrays with complex element types perform element by element
567 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000568 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000569 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000570 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000571 // Working with the single array element, so have to remap
572 // destination and source variables to corresponding array
573 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000574 CodeGenFunction::OMPPrivateScope Remap(*this);
575 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000576 return DestElement;
577 });
578 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000579 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000580 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000581 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000582 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000583 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000584 } else {
585 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000586 CodeGenFunction::OMPPrivateScope Remap(*this);
587 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
588 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000589 (void)Remap.Privatize();
590 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000591 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000592 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000593}
594
Alexey Bataev69c62a92015-04-15 04:52:20 +0000595bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
596 OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000597 if (!HaveInsertPoint())
598 return false;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000599 bool FirstprivateIsLastprivate = false;
600 llvm::DenseSet<const VarDecl *> Lastprivates;
601 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
602 for (const auto *D : C->varlists())
603 Lastprivates.insert(
604 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
605 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000606 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000607 CGCapturedStmtInfo CapturesInfo(cast<CapturedStmt>(*D.getAssociatedStmt()));
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000608 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000609 auto IRef = C->varlist_begin();
610 auto InitsRef = C->inits().begin();
611 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000612 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000613 bool ThisFirstprivateIsLastprivate =
614 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
Alexey Bataev9afe5752016-05-24 07:40:12 +0000615 auto *CapFD = CapturesInfo.lookup(OrigVD);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000616 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev9afe5752016-05-24 07:40:12 +0000617 if (!ThisFirstprivateIsLastprivate && FD && (FD == CapFD) &&
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000618 !FD->getType()->isReferenceType()) {
619 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
620 ++IRef;
621 ++InitsRef;
622 continue;
623 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000624 FirstprivateIsLastprivate =
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000625 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000626 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000627 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
628 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
629 bool IsRegistered;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000630 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
631 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
632 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000633 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataevfeddd642016-04-22 09:05:03 +0000634 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000635 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000636 // Emit VarDecl with copy init for arrays.
637 // Get the address of the original variable captured in current
638 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000639 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000640 auto Emission = EmitAutoVarAlloca(*VD);
641 auto *Init = VD->getInit();
642 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
643 // Perform simple memcpy.
644 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000645 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000646 } else {
647 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000648 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000649 [this, VDInit, Init](Address DestElement,
650 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000651 // Clean up any temporaries needed by the initialization.
652 RunCleanupsScope InitScope(*this);
653 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000654 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000655 EmitAnyExprToMem(Init, DestElement,
656 Init->getType().getQualifiers(),
657 /*IsInitializer*/ false);
658 LocalDeclMap.erase(VDInit);
659 });
660 }
661 EmitAutoVarCleanups(Emission);
662 return Emission.getAllocatedAddress();
663 });
664 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000665 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000666 // Emit private VarDecl with copy init.
667 // Remap temp VDInit variable to the address of the original
668 // variable
669 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000670 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000671 EmitDecl(*VD);
672 LocalDeclMap.erase(VDInit);
673 return GetAddrOfLocalVar(VD);
674 });
675 }
676 assert(IsRegistered &&
677 "firstprivate var already registered as private");
678 // Silence the warning about unused variable.
679 (void)IsRegistered;
680 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000681 ++IRef;
682 ++InitsRef;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000683 }
684 }
Alexey Bataevcd8b6a22016-02-15 08:07:17 +0000685 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000686}
687
Alexey Bataev03b340a2014-10-21 03:16:40 +0000688void CodeGenFunction::EmitOMPPrivateClause(
689 const OMPExecutableDirective &D,
690 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000691 if (!HaveInsertPoint())
692 return;
Alexey Bataev50a64582015-04-22 12:24:45 +0000693 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000694 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000695 auto IRef = C->varlist_begin();
696 for (auto IInit : C->private_copies()) {
697 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000698 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
699 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
700 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000701 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000702 // Emit private VarDecl with copy init.
703 EmitDecl(*VD);
704 return GetAddrOfLocalVar(VD);
705 });
706 assert(IsRegistered && "private var already registered as private");
707 // Silence the warning about unused variable.
708 (void)IsRegistered;
709 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000710 ++IRef;
711 }
712 }
713}
714
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000715bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000716 if (!HaveInsertPoint())
717 return false;
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000718 // threadprivate_var1 = master_threadprivate_var1;
719 // operator=(threadprivate_var2, master_threadprivate_var2);
720 // ...
721 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000722 llvm::DenseSet<const VarDecl *> CopiedVars;
723 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000724 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000725 auto IRef = C->varlist_begin();
726 auto ISrcRef = C->source_exprs().begin();
727 auto IDestRef = C->destination_exprs().begin();
728 for (auto *AssignOp : C->assignment_ops()) {
729 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000730 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000731 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000732 // Get the address of the master variable. If we are emitting code with
733 // TLS support, the address is passed from the master as field in the
734 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000735 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000736 if (getLangOpts().OpenMPUseTLS &&
737 getContext().getTargetInfo().isTLSSupported()) {
738 assert(CapturedStmtInfo->lookup(VD) &&
739 "Copyin threadprivates should have been captured!");
740 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
741 VK_LValue, (*IRef)->getExprLoc());
742 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000743 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000744 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000745 MasterAddr =
746 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
747 : CGM.GetAddrOfGlobal(VD),
748 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000749 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000750 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000751 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000752 if (CopiedVars.size() == 1) {
753 // At first check if current thread is a master thread. If it is, no
754 // need to copy data.
755 CopyBegin = createBasicBlock("copyin.not.master");
756 CopyEnd = createBasicBlock("copyin.not.master.end");
757 Builder.CreateCondBr(
758 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000759 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
760 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000761 CopyBegin, CopyEnd);
762 EmitBlock(CopyBegin);
763 }
764 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
765 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000766 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000767 }
768 ++IRef;
769 ++ISrcRef;
770 ++IDestRef;
771 }
772 }
773 if (CopyEnd) {
774 // Exit out of copying procedure for non-master thread.
775 EmitBlock(CopyEnd, /*IsFinished=*/true);
776 return true;
777 }
778 return false;
779}
780
Alexey Bataev38e89532015-04-16 04:54:05 +0000781bool CodeGenFunction::EmitOMPLastprivateClauseInit(
782 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000783 if (!HaveInsertPoint())
784 return false;
Alexey Bataev38e89532015-04-16 04:54:05 +0000785 bool HasAtLeastOneLastprivate = false;
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000786 llvm::DenseSet<const VarDecl *> SIMDLCVs;
787 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
788 auto *LoopDirective = cast<OMPLoopDirective>(&D);
789 for (auto *C : LoopDirective->counters()) {
790 SIMDLCVs.insert(
791 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
792 }
793 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000794 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000795 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000796 HasAtLeastOneLastprivate = true;
Alexey Bataevf93095a2016-05-05 08:46:22 +0000797 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()))
798 break;
Alexey Bataev38e89532015-04-16 04:54:05 +0000799 auto IRef = C->varlist_begin();
800 auto IDestRef = C->destination_exprs().begin();
801 for (auto *IInit : C->private_copies()) {
802 // Keep the address of the original variable for future update at the end
803 // of the loop.
804 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000805 // Taskloops do not require additional initialization, it is done in
806 // runtime support library.
Alexey Bataev38e89532015-04-16 04:54:05 +0000807 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
808 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000809 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000810 DeclRefExpr DRE(
811 const_cast<VarDecl *>(OrigVD),
812 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
813 OrigVD) != nullptr,
814 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
815 return EmitLValue(&DRE).getAddress();
816 });
817 // Check if the variable is also a firstprivate: in this case IInit is
818 // not generated. Initialization of this variable will happen in codegen
819 // for 'firstprivate' clause.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000820 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000821 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +0000822 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
823 // Emit private VarDecl with copy init.
824 EmitDecl(*VD);
825 return GetAddrOfLocalVar(VD);
826 });
Alexey Bataevd130fd12015-05-13 10:23:02 +0000827 assert(IsRegistered &&
828 "lastprivate var already registered as private");
829 (void)IsRegistered;
830 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000831 }
Richard Trieucc3949d2016-02-18 22:34:54 +0000832 ++IRef;
833 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000834 }
835 }
836 return HasAtLeastOneLastprivate;
837}
838
839void CodeGenFunction::EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000840 const OMPExecutableDirective &D, bool NoFinals,
841 llvm::Value *IsLastIterCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000842 if (!HaveInsertPoint())
843 return;
Alexey Bataev38e89532015-04-16 04:54:05 +0000844 // Emit following code:
845 // if (<IsLastIterCond>) {
846 // orig_var1 = private_orig_var1;
847 // ...
848 // orig_varn = private_orig_varn;
849 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000850 llvm::BasicBlock *ThenBB = nullptr;
851 llvm::BasicBlock *DoneBB = nullptr;
852 if (IsLastIterCond) {
853 ThenBB = createBasicBlock(".omp.lastprivate.then");
854 DoneBB = createBasicBlock(".omp.lastprivate.done");
855 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
856 EmitBlock(ThenBB);
857 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000858 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
859 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000860 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000861 auto IC = LoopDirective->counters().begin();
862 for (auto F : LoopDirective->finals()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000863 auto *D =
864 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
865 if (NoFinals)
866 AlreadyEmittedVars.insert(D);
867 else
868 LoopCountersAndUpdates[D] = F;
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000869 ++IC;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000870 }
871 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000872 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
873 auto IRef = C->varlist_begin();
874 auto ISrcRef = C->source_exprs().begin();
875 auto IDestRef = C->destination_exprs().begin();
876 for (auto *AssignOp : C->assignment_ops()) {
877 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
878 QualType Type = PrivateVD->getType();
879 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
880 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
881 // If lastprivate variable is a loop control variable for loop-based
882 // directive, update its value before copyin back to original
883 // variable.
Alexey Bataev5dff95c2016-04-22 03:56:56 +0000884 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
885 EmitIgnoredExpr(FinalExpr);
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000886 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
887 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
888 // Get the address of the original variable.
889 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
890 // Get the address of the private variable.
891 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
892 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
893 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000894 Address(Builder.CreateLoad(PrivateAddr),
895 getNaturalTypeAlignment(RefTy->getPointeeType()));
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000896 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000897 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000898 ++IRef;
899 ++ISrcRef;
900 ++IDestRef;
Alexey Bataev38e89532015-04-16 04:54:05 +0000901 }
Alexey Bataev005248a2016-02-25 05:25:57 +0000902 if (auto *PostUpdate = C->getPostUpdateExpr())
903 EmitIgnoredExpr(PostUpdate);
Alexey Bataev38e89532015-04-16 04:54:05 +0000904 }
Alexey Bataev8ffcc942016-02-18 13:48:15 +0000905 if (IsLastIterCond)
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000906 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev38e89532015-04-16 04:54:05 +0000907}
908
Alexey Bataev31300ed2016-02-04 11:27:03 +0000909static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
910 LValue BaseLV, llvm::Value *Addr) {
911 Address Tmp = Address::invalid();
912 Address TopTmp = Address::invalid();
913 Address MostTopTmp = Address::invalid();
914 BaseTy = BaseTy.getNonReferenceType();
915 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
916 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
917 Tmp = CGF.CreateMemTemp(BaseTy);
918 if (TopTmp.isValid())
919 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
920 else
921 MostTopTmp = Tmp;
922 TopTmp = Tmp;
923 BaseTy = BaseTy->getPointeeType();
924 }
925 llvm::Type *Ty = BaseLV.getPointer()->getType();
926 if (Tmp.isValid())
927 Ty = Tmp.getElementType();
928 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
929 if (Tmp.isValid()) {
930 CGF.Builder.CreateStore(Addr, Tmp);
931 return MostTopTmp;
932 }
933 return Address(Addr, BaseLV.getAlignment());
934}
935
936static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
937 LValue BaseLV) {
938 BaseTy = BaseTy.getNonReferenceType();
939 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
940 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
941 if (auto *PtrTy = BaseTy->getAs<PointerType>())
942 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
943 else {
944 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
945 BaseTy->castAs<ReferenceType>());
946 }
947 BaseTy = BaseTy->getPointeeType();
948 }
949 return CGF.MakeAddrLValue(
950 Address(
951 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
952 BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()),
953 BaseLV.getAlignment()),
954 BaseLV.getType(), BaseLV.getAlignmentSource());
955}
956
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000957void CodeGenFunction::EmitOMPReductionClauseInit(
958 const OMPExecutableDirective &D,
959 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000960 if (!HaveInsertPoint())
961 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000962 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000963 auto ILHS = C->lhs_exprs().begin();
964 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000965 auto IPriv = C->privates().begin();
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000966 auto IRed = C->reduction_ops().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000967 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000968 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000969 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
970 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000971 auto *DRD = getReductionInit(*IRed);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000972 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
973 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
974 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
975 Base = TempOASE->getBase()->IgnoreParenImpCasts();
976 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
977 Base = TempASE->getBase()->IgnoreParenImpCasts();
978 auto *DE = cast<DeclRefExpr>(Base);
979 auto *OrigVD = cast<VarDecl>(DE->getDecl());
980 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
981 auto OASELValueUB =
982 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
983 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +0000984 LValue BaseLValue =
985 loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(),
986 OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000987 // Store the address of the original variable associated with the LHS
988 // implicit variable.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +0000989 PrivateScope.addPrivate(LHSVD, [OASELValueLB]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000990 return OASELValueLB.getAddress();
991 });
992 // Emit reduction copy.
993 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +0000994 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB,
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000995 OASELValueUB, OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000996 // Emit VarDecl with copy init for arrays.
997 // Get the address of the original variable captured in current
998 // captured region.
999 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
1000 OASELValueLB.getPointer());
1001 Size = Builder.CreateNUWAdd(
1002 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
1003 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1004 *this, cast<OpaqueValueExpr>(
1005 getContext()
1006 .getAsVariableArrayType(PrivateVD->getType())
1007 ->getSizeExpr()),
1008 RValue::get(Size));
1009 EmitVariablyModifiedType(PrivateVD->getType());
1010 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1011 auto Addr = Emission.getAllocatedAddress();
1012 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001013 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
1014 DRD ? *IRed : Init,
1015 OASELValueLB.getAddress());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001016 EmitAutoVarCleanups(Emission);
1017 // Emit private VarDecl with reduction init.
1018 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
1019 OASELValueLB.getPointer());
1020 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +00001021 return castToBase(*this, OrigVD->getType(),
1022 OASELValueLB.getType(), OriginalBaseLValue,
1023 Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001024 });
1025 assert(IsRegistered && "private var already registered as private");
1026 // Silence the warning about unused variable.
1027 (void)IsRegistered;
1028 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1029 return GetAddrOfLocalVar(PrivateVD);
1030 });
1031 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
1032 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1033 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1034 Base = TempASE->getBase()->IgnoreParenImpCasts();
1035 auto *DE = cast<DeclRefExpr>(Base);
1036 auto *OrigVD = cast<VarDecl>(DE->getDecl());
1037 auto ASELValue = EmitLValue(ASE);
1038 auto OriginalBaseLValue = EmitLValue(DE);
Alexey Bataev31300ed2016-02-04 11:27:03 +00001039 LValue BaseLValue = loadToBegin(
1040 *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001041 // Store the address of the original variable associated with the LHS
1042 // implicit variable.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00001043 PrivateScope.addPrivate(
1044 LHSVD, [ASELValue]() -> Address { return ASELValue.getAddress(); });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001045 // Emit reduction copy.
1046 bool IsRegistered = PrivateScope.addPrivate(
Alexey Bataev31300ed2016-02-04 11:27:03 +00001047 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001048 OriginalBaseLValue, DRD, IRed]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001049 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001050 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1051 auto Addr = Emission.getAllocatedAddress();
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +00001052 if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001053 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
1054 ASELValue.getAddress(),
1055 ASELValue.getType());
1056 } else
1057 EmitAutoVarInit(Emission);
1058 EmitAutoVarCleanups(Emission);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001059 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
1060 ASELValue.getPointer());
1061 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
Alexey Bataev31300ed2016-02-04 11:27:03 +00001062 return castToBase(*this, OrigVD->getType(), ASELValue.getType(),
1063 OriginalBaseLValue, Ptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001064 });
1065 assert(IsRegistered && "private var already registered as private");
1066 // Silence the warning about unused variable.
1067 (void)IsRegistered;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001068 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1069 return Builder.CreateElementBitCast(
1070 GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
1071 "rhs.begin");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001072 });
1073 } else {
1074 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
Alexey Bataev1189bd02016-01-26 12:20:39 +00001075 QualType Type = PrivateVD->getType();
1076 if (getContext().getAsArrayType(Type)) {
1077 // Store the address of the original variable associated with the LHS
1078 // implicit variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001079 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1080 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1081 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataev1189bd02016-01-26 12:20:39 +00001082 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001083 PrivateScope.addPrivate(LHSVD, [this, &OriginalAddr,
Alexey Bataev1189bd02016-01-26 12:20:39 +00001084 LHSVD]() -> Address {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001085 OriginalAddr = Builder.CreateElementBitCast(
1086 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1087 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001088 });
1089 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
1090 if (Type->isVariablyModifiedType()) {
1091 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1092 *this, cast<OpaqueValueExpr>(
1093 getContext()
1094 .getAsVariableArrayType(PrivateVD->getType())
1095 ->getSizeExpr()),
1096 RValue::get(
1097 getTypeSize(OrigVD->getType().getNonReferenceType())));
1098 EmitVariablyModifiedType(Type);
1099 }
1100 auto Emission = EmitAutoVarAlloca(*PrivateVD);
1101 auto Addr = Emission.getAllocatedAddress();
1102 auto *Init = PrivateVD->getInit();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001103 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
1104 DRD ? *IRed : Init, OriginalAddr);
Alexey Bataev1189bd02016-01-26 12:20:39 +00001105 EmitAutoVarCleanups(Emission);
1106 return Emission.getAllocatedAddress();
1107 });
1108 assert(IsRegistered && "private var already registered as private");
1109 // Silence the warning about unused variable.
1110 (void)IsRegistered;
1111 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1112 return Builder.CreateElementBitCast(
1113 GetAddrOfLocalVar(PrivateVD),
1114 ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
1115 });
1116 } else {
1117 // Store the address of the original variable associated with the LHS
1118 // implicit variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001119 Address OriginalAddr = Address::invalid();
1120 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef,
1121 &OriginalAddr]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001122 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1123 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1124 IRef->getType(), VK_LValue, IRef->getExprLoc());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001125 OriginalAddr = EmitLValue(&DRE).getAddress();
1126 return OriginalAddr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001127 });
1128 // Emit reduction copy.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001129 bool IsRegistered = PrivateScope.addPrivate(
1130 OrigVD, [this, PrivateVD, OriginalAddr, DRD, IRed]() -> Address {
Alexey Bataev1189bd02016-01-26 12:20:39 +00001131 // Emit private VarDecl with reduction init.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001132 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1133 auto Addr = Emission.getAllocatedAddress();
Alexey Bataev8fbae8cf2016-04-27 11:38:05 +00001134 if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001135 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
1136 OriginalAddr,
1137 PrivateVD->getType());
1138 } else
1139 EmitAutoVarInit(Emission);
1140 EmitAutoVarCleanups(Emission);
1141 return Addr;
Alexey Bataev1189bd02016-01-26 12:20:39 +00001142 });
1143 assert(IsRegistered && "private var already registered as private");
1144 // Silence the warning about unused variable.
1145 (void)IsRegistered;
1146 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1147 return GetAddrOfLocalVar(PrivateVD);
1148 });
1149 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001150 }
Richard Trieucc3949d2016-02-18 22:34:54 +00001151 ++ILHS;
1152 ++IRHS;
1153 ++IPriv;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001154 ++IRed;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001155 }
1156 }
1157}
1158
1159void CodeGenFunction::EmitOMPReductionClauseFinal(
1160 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001161 if (!HaveInsertPoint())
1162 return;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001163 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001164 llvm::SmallVector<const Expr *, 8> LHSExprs;
1165 llvm::SmallVector<const Expr *, 8> RHSExprs;
1166 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001167 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001168 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001169 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001170 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001171 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1172 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1173 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1174 }
1175 if (HasAtLeastOneReduction) {
1176 // Emit nowait reduction if nowait clause is present or directive is a
1177 // parallel directive (it always has implicit barrier).
1178 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001179 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001180 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001181 isOpenMPParallelDirective(D.getDirectiveKind()) ||
1182 D.getDirectiveKind() == OMPD_simd,
1183 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001184 }
1185}
1186
Alexey Bataev61205072016-03-02 04:57:40 +00001187static void emitPostUpdateForReductionClause(
1188 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1189 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1190 if (!CGF.HaveInsertPoint())
1191 return;
1192 llvm::BasicBlock *DoneBB = nullptr;
1193 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1194 if (auto *PostUpdate = C->getPostUpdateExpr()) {
1195 if (!DoneBB) {
1196 if (auto *Cond = CondGen(CGF)) {
1197 // If the first post-update expression is found, emit conditional
1198 // block if it was requested.
1199 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1200 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1201 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1202 CGF.EmitBlock(ThenBB);
1203 }
1204 }
1205 CGF.EmitIgnoredExpr(PostUpdate);
1206 }
1207 }
1208 if (DoneBB)
1209 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1210}
1211
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001212static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
1213 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001214 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001215 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +00001216 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001217 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
1218 emitParallelOrTeamsOutlinedFunction(S,
1219 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001220 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001221 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001222 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1223 /*IgnoreResultAssign*/ true);
1224 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1225 CGF, NumThreads, NumThreadsClause->getLocStart());
1226 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001227 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001228 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +00001229 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1230 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1231 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001232 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001233 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1234 if (C->getNameModifier() == OMPD_unknown ||
1235 C->getNameModifier() == OMPD_parallel) {
1236 IfCond = C->getCondition();
1237 break;
1238 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001239 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001240
1241 OMPLexicalScope Scope(CGF, S);
1242 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
1243 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev1d677132015-04-22 13:57:31 +00001244 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001245 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001246}
1247
1248void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001249 // Emit parallel region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001250 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001251 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001252 bool Copyins = CGF.EmitOMPCopyinClause(S);
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001253 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1254 if (Copyins) {
Alexey Bataev69c62a92015-04-15 04:52:20 +00001255 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00001256 // propagation master's thread values of threadprivate variables to local
1257 // instances of that variables of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001258 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1259 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1260 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001261 }
1262 CGF.EmitOMPPrivateClause(S, PrivateScope);
1263 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1264 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001265 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001266 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001267 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001268 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev61205072016-03-02 04:57:40 +00001269 emitPostUpdateForReductionClause(
1270 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev9959db52014-05-06 10:08:46 +00001271}
Alexander Musman515ad8c2014-05-22 08:54:05 +00001272
Alexey Bataev0f34da12015-07-02 04:17:07 +00001273void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1274 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001275 RunCleanupsScope BodyScope(*this);
1276 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001277 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00001278 EmitIgnoredExpr(I);
1279 }
Alexander Musman3276a272015-03-21 10:12:56 +00001280 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001281 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001282 for (auto *U : C->updates())
Alexander Musman3276a272015-03-21 10:12:56 +00001283 EmitIgnoredExpr(U);
Alexander Musman3276a272015-03-21 10:12:56 +00001284 }
1285
Alexander Musmana5f070a2014-10-01 06:03:56 +00001286 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +00001287 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +00001288 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001289 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001290 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001291 // The end (updates/cleanups).
1292 EmitBlock(Continue.getBlock());
1293 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +00001294}
1295
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001296void CodeGenFunction::EmitOMPInnerLoop(
1297 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1298 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001299 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1300 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +00001301 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001302
1303 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +00001304 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001305 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001306 const SourceRange &R = S.getSourceRange();
1307 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1308 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001309
1310 // If there are any cleanups between here and the loop-exit scope,
1311 // create a block to stage a loop exit along.
1312 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +00001313 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +00001314 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001315
Alexander Musmand196ef22014-10-07 08:57:09 +00001316 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001317
Alexey Bataev2df54a02015-03-12 08:53:29 +00001318 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +00001319 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +00001320 if (ExitBlock != LoopExit.getBlock()) {
1321 EmitBlock(ExitBlock);
1322 EmitBranchThroughCleanup(LoopExit);
1323 }
1324
1325 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +00001326 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001327
1328 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +00001329 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +00001330 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1331
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001332 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001333
1334 // Emit "IV = IV + 1" and a back-edge to the condition block.
1335 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001336 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001337 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001338 BreakContinueStack.pop_back();
1339 EmitBranch(CondBlock);
1340 LoopStack.pop();
1341 // Emit the fall-through block.
1342 EmitBlock(LoopExit.getBlock());
1343}
1344
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001345void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001346 if (!HaveInsertPoint())
1347 return;
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001348 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001349 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001350 for (auto *Init : C->inits()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001351 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataevef549a82016-03-09 09:49:09 +00001352 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1353 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1354 auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1355 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1356 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1357 VD->getInit()->getType(), VK_LValue,
1358 VD->getInit()->getExprLoc());
1359 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1360 VD->getType()),
1361 /*capturedByInit=*/false);
1362 EmitAutoVarCleanups(Emission);
1363 } else
1364 EmitVarDecl(*VD);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001365 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001366 // Emit the linear steps for the linear clauses.
1367 // If a step is not constant, it is pre-calculated before the loop.
1368 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1369 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001370 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001371 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001372 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001373 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001374 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001375}
1376
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001377void CodeGenFunction::EmitOMPLinearClauseFinal(
1378 const OMPLoopDirective &D,
Alexey Bataevef549a82016-03-09 09:49:09 +00001379 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001380 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001381 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001382 llvm::BasicBlock *DoneBB = nullptr;
Alexander Musman3276a272015-03-21 10:12:56 +00001383 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001384 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00001385 auto IC = C->varlist_begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001386 for (auto *F : C->finals()) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001387 if (!DoneBB) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001388 if (auto *Cond = CondGen(*this)) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001389 // If the first post-update expression is found, emit conditional
1390 // block if it was requested.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001391 auto *ThenBB = createBasicBlock(".omp.linear.pu");
1392 DoneBB = createBasicBlock(".omp.linear.pu.done");
1393 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1394 EmitBlock(ThenBB);
Alexey Bataevef549a82016-03-09 09:49:09 +00001395 }
1396 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001397 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1398 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001399 CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +00001400 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001401 Address OrigAddr = EmitLValue(&DRE).getAddress();
1402 CodeGenFunction::OMPPrivateScope VarScope(*this);
1403 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +00001404 (void)VarScope.Privatize();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001405 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001406 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +00001407 }
Alexey Bataev78849fb2016-03-09 09:49:00 +00001408 if (auto *PostUpdate = C->getPostUpdateExpr())
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001409 EmitIgnoredExpr(PostUpdate);
Alexander Musman3276a272015-03-21 10:12:56 +00001410 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001411 if (DoneBB)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001412 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00001413}
1414
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001415static void emitAlignedClause(CodeGenFunction &CGF,
1416 const OMPExecutableDirective &D) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001417 if (!CGF.HaveInsertPoint())
1418 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001419 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001420 unsigned ClauseAlignment = 0;
1421 if (auto AlignmentExpr = Clause->getAlignment()) {
1422 auto AlignmentCI =
1423 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1424 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +00001425 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001426 for (auto E : Clause->varlists()) {
1427 unsigned Alignment = ClauseAlignment;
1428 if (Alignment == 0) {
1429 // OpenMP [2.8.1, Description]
1430 // If no optional parameter is specified, implementation-defined default
1431 // alignments for SIMD instructions on the target platforms are assumed.
1432 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +00001433 CGF.getContext()
1434 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1435 E->getType()->getPointeeType()))
1436 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001437 }
1438 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1439 "alignment is not power of 2");
1440 if (Alignment != 0) {
1441 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1442 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1443 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001444 }
1445 }
1446}
1447
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001448void CodeGenFunction::EmitOMPPrivateLoopCounters(
1449 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1450 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001451 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001452 auto I = S.private_counters().begin();
1453 for (auto *E : S.counters()) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001454 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1455 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001456 (void)LoopScope.addPrivate(VD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001457 // Emit var without initialization.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001458 if (!LocalDeclMap.count(PrivateVD)) {
1459 auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1460 EmitAutoVarCleanups(VarEmission);
1461 }
1462 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1463 /*RefersToEnclosingVariableOrCapture=*/false,
1464 (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1465 return EmitLValue(&DRE).getAddress();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001466 });
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001467 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1468 VD->hasGlobalStorage()) {
1469 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1470 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1471 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1472 E->getType(), VK_LValue, E->getExprLoc());
1473 return EmitLValue(&DRE).getAddress();
1474 });
1475 }
Alexey Bataeva8899172015-08-06 12:30:57 +00001476 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001477 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001478}
1479
Alexey Bataev62dbb972015-04-22 11:59:37 +00001480static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1481 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1482 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001483 if (!CGF.HaveInsertPoint())
1484 return;
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001485 {
1486 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001487 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001488 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001489 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001490 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001491 CGF.EmitIgnoredExpr(I);
1492 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001493 }
1494 // Check that loop is executed at least one time.
1495 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1496}
1497
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001498void CodeGenFunction::EmitOMPLinearClause(
1499 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1500 if (!HaveInsertPoint())
Alexey Bataev8ef31412015-12-18 07:58:25 +00001501 return;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001502 llvm::DenseSet<const VarDecl *> SIMDLCVs;
1503 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1504 auto *LoopDirective = cast<OMPLoopDirective>(&D);
1505 for (auto *C : LoopDirective->counters()) {
1506 SIMDLCVs.insert(
1507 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1508 }
1509 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001510 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001511 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001512 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001513 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1514 auto *PrivateVD =
1515 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001516 if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1517 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1518 // Emit private VarDecl with copy init.
1519 EmitVarDecl(*PrivateVD);
1520 return GetAddrOfLocalVar(PrivateVD);
1521 });
1522 assert(IsRegistered && "linear var already registered as private");
1523 // Silence the warning about unused variable.
1524 (void)IsRegistered;
1525 } else
1526 EmitVarDecl(*PrivateVD);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001527 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001528 }
1529 }
1530}
1531
Alexey Bataev45bfad52015-08-21 12:19:04 +00001532static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001533 const OMPExecutableDirective &D,
1534 bool IsMonotonic) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001535 if (!CGF.HaveInsertPoint())
1536 return;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001537 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001538 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1539 /*ignoreResult=*/true);
1540 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1541 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1542 // In presence of finite 'safelen', it may be unsafe to mark all
1543 // the memory instructions parallel, because loop-carried
1544 // dependences of 'safelen' iterations are possible.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001545 if (!IsMonotonic)
1546 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001547 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001548 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1549 /*ignoreResult=*/true);
1550 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001551 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001552 // In presence of finite 'safelen', it may be unsafe to mark all
1553 // the memory instructions parallel, because loop-carried
1554 // dependences of 'safelen' iterations are possible.
1555 CGF.LoopStack.setParallel(false);
1556 }
1557}
1558
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001559void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1560 bool IsMonotonic) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001561 // Walk clauses and process safelen/lastprivate.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001562 LoopStack.setParallel(!IsMonotonic);
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001563 LoopStack.setVectorizeEnable(true);
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001564 emitSimdlenSafelenClause(*this, D, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001565}
1566
Alexey Bataevef549a82016-03-09 09:49:09 +00001567void CodeGenFunction::EmitOMPSimdFinal(
1568 const OMPLoopDirective &D,
1569 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001570 if (!HaveInsertPoint())
1571 return;
Alexey Bataevef549a82016-03-09 09:49:09 +00001572 llvm::BasicBlock *DoneBB = nullptr;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001573 auto IC = D.counters().begin();
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001574 auto IPC = D.private_counters().begin();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001575 for (auto F : D.finals()) {
1576 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001577 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1578 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1579 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1580 OrigVD->hasGlobalStorage() || CED) {
Alexey Bataevef549a82016-03-09 09:49:09 +00001581 if (!DoneBB) {
1582 if (auto *Cond = CondGen(*this)) {
1583 // If the first post-update expression is found, emit conditional
1584 // block if it was requested.
1585 auto *ThenBB = createBasicBlock(".omp.final.then");
1586 DoneBB = createBasicBlock(".omp.final.done");
1587 Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1588 EmitBlock(ThenBB);
1589 }
1590 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001591 Address OrigAddr = Address::invalid();
1592 if (CED)
1593 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1594 else {
1595 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1596 /*RefersToEnclosingVariableOrCapture=*/false,
1597 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1598 OrigAddr = EmitLValue(&DRE).getAddress();
1599 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001600 OMPPrivateScope VarScope(*this);
1601 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001602 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001603 (void)VarScope.Privatize();
1604 EmitIgnoredExpr(F);
1605 }
1606 ++IC;
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001607 ++IPC;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001608 }
Alexey Bataevef549a82016-03-09 09:49:09 +00001609 if (DoneBB)
1610 EmitBlock(DoneBB, /*IsFinished=*/true);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001611}
1612
Alexander Musman515ad8c2014-05-22 08:54:05 +00001613void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001614 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00001615 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001616 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001617 // for (IV in 0..LastIteration) BODY;
1618 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001619 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001620 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001621
Alexey Bataev62dbb972015-04-22 11:59:37 +00001622 // Emit: if (PreCond) - begin.
1623 // If the condition constant folds and can be elided, avoid emitting the
1624 // whole loop.
1625 bool CondConstant;
1626 llvm::BasicBlock *ContBlock = nullptr;
1627 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1628 if (!CondConstant)
1629 return;
1630 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001631 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1632 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001633 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1634 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001635 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001636 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001637 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001638
1639 // Emit the loop iteration variable.
1640 const Expr *IVExpr = S.getIterationVariable();
1641 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1642 CGF.EmitVarDecl(*IVDecl);
1643 CGF.EmitIgnoredExpr(S.getInit());
1644
1645 // Emit the iterations count variable.
1646 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001647 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001648 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1649 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1650 // Emit calculation of the iterations count.
1651 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001652 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001653
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001654 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001655
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001656 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001657 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001658 {
1659 OMPPrivateScope LoopScope(CGF);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001660 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1661 CGF.EmitOMPLinearClause(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001662 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001663 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001664 bool HasLastprivateClause =
1665 CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001666 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001667 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1668 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001669 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001670 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001671 CGF.EmitStopPoint(&S);
1672 },
1673 [](CodeGenFunction &) {});
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001674 CGF.EmitOMPSimdFinal(
1675 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001676 // Emit final copy of the lastprivate variables at the end of loops.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001677 if (HasLastprivateClause)
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001678 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001679 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00001680 emitPostUpdateForReductionClause(
1681 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001682 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001683 CGF.EmitOMPLinearClauseFinal(
Alexey Bataevef549a82016-03-09 09:49:09 +00001684 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
Alexey Bataev62dbb972015-04-22 11:59:37 +00001685 // Emit: if (PreCond) - end.
1686 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001687 CGF.EmitBranch(ContBlock);
1688 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001689 }
1690 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00001691 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001692 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001693}
1694
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001695void CodeGenFunction::EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001696 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1697 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001698 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001699
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001700 const Expr *IVExpr = S.getIterationVariable();
1701 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1702 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1703
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001704 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1705
1706 // Start the loop with a block that tests the condition.
1707 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1708 EmitBlock(CondBlock);
Amara Emerson652795d2016-11-10 14:44:30 +00001709 const SourceRange &R = S.getSourceRange();
1710 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1711 SourceLocToDebugLoc(R.getEnd()));
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001712
1713 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001714 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001715 // UB = min(UB, GlobalUB)
1716 EmitIgnoredExpr(S.getEnsureUpperBound());
1717 // IV = LB
1718 EmitIgnoredExpr(S.getInit());
1719 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001720 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001721 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00001722 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, IL,
1723 LB, UB, ST);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001724 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001725
1726 // If there are any cleanups between here and the loop-exit scope,
1727 // create a block to stage a loop exit along.
1728 auto ExitBlock = LoopExit.getBlock();
1729 if (LoopScope.requiresCleanups())
1730 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1731
1732 auto LoopBody = createBasicBlock("omp.dispatch.body");
1733 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1734 if (ExitBlock != LoopExit.getBlock()) {
1735 EmitBlock(ExitBlock);
1736 EmitBranchThroughCleanup(LoopExit);
1737 }
1738 EmitBlock(LoopBody);
1739
Alexander Musman92bdaab2015-03-12 13:37:50 +00001740 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1741 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001742 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001743 EmitIgnoredExpr(S.getInit());
1744
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001745 // Create a block for the increment.
1746 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1747 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1748
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001749 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1750 // with dynamic/guided scheduling and without ordered clause.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00001751 if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1752 LoopStack.setParallel(!IsMonotonic);
1753 else
1754 EmitOMPSimdInit(S, IsMonotonic);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001755
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001756 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001757 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1758 [&S, LoopExit](CodeGenFunction &CGF) {
1759 CGF.EmitOMPLoopBody(S, LoopExit);
1760 CGF.EmitStopPoint(&S);
1761 },
1762 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1763 if (Ordered) {
1764 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1765 CGF, Loc, IVSize, IVSigned);
1766 }
1767 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001768
1769 EmitBlock(Continue.getBlock());
1770 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001771 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001772 // Emit "LB = LB + Stride", "UB = UB + Stride".
1773 EmitIgnoredExpr(S.getNextLowerBound());
1774 EmitIgnoredExpr(S.getNextUpperBound());
1775 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001776
1777 EmitBranch(CondBlock);
1778 LoopStack.pop();
1779 // Emit the fall-through block.
1780 EmitBlock(LoopExit.getBlock());
1781
1782 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00001783 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1784 if (!DynamicOrOrdered)
1785 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
1786 };
1787 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001788}
1789
1790void CodeGenFunction::EmitOMPForOuterLoop(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001791 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001792 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1793 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1794 auto &RT = CGM.getOpenMPRuntime();
1795
1796 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001797 const bool DynamicOrOrdered =
1798 Ordered || RT.isDynamic(ScheduleKind.Schedule);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001799
1800 assert((Ordered ||
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001801 !RT.isStaticNonchunked(ScheduleKind.Schedule,
1802 /*Chunked=*/Chunk != nullptr)) &&
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001803 "static non-chunked schedule does not need outer loop");
1804
1805 // Emit outer loop.
1806 //
1807 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1808 // When schedule(dynamic,chunk_size) is specified, the iterations are
1809 // distributed to threads in the team in chunks as the threads request them.
1810 // Each thread executes a chunk of iterations, then requests another chunk,
1811 // until no chunks remain to be distributed. Each chunk contains chunk_size
1812 // iterations, except for the last chunk to be distributed, which may have
1813 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1814 //
1815 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1816 // to threads in the team in chunks as the executing threads request them.
1817 // Each thread executes a chunk of iterations, then requests another chunk,
1818 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1819 // each chunk is proportional to the number of unassigned iterations divided
1820 // by the number of threads in the team, decreasing to 1. For a chunk_size
1821 // with value k (greater than 1), the size of each chunk is determined in the
1822 // same way, with the restriction that the chunks do not contain fewer than k
1823 // iterations (except for the last chunk to be assigned, which may have fewer
1824 // than k iterations).
1825 //
1826 // When schedule(auto) is specified, the decision regarding scheduling is
1827 // delegated to the compiler and/or runtime system. The programmer gives the
1828 // implementation the freedom to choose any possible mapping of iterations to
1829 // threads in the team.
1830 //
1831 // When schedule(runtime) is specified, the decision regarding scheduling is
1832 // deferred until run time, and the schedule and chunk size are taken from the
1833 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1834 // implementation defined
1835 //
1836 // while(__kmpc_dispatch_next(&LB, &UB)) {
1837 // idx = LB;
1838 // while (idx <= UB) { BODY; ++idx;
1839 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1840 // } // inner loop
1841 // }
1842 //
1843 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1844 // When schedule(static, chunk_size) is specified, iterations are divided into
1845 // chunks of size chunk_size, and the chunks are assigned to the threads in
1846 // the team in a round-robin fashion in the order of the thread number.
1847 //
1848 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1849 // while (idx <= UB) { BODY; ++idx; } // inner loop
1850 // LB = LB + ST;
1851 // UB = UB + ST;
1852 // }
1853 //
1854
1855 const Expr *IVExpr = S.getIterationVariable();
1856 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1857 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1858
1859 if (DynamicOrOrdered) {
1860 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
Alexey Bataev9ebd7422016-05-10 09:57:36 +00001861 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
1862 IVSigned, Ordered, UBVal, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001863 } else {
1864 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
1865 Ordered, IL, LB, UB, ST, Chunk);
1866 }
1867
Carlo Bertolli0ff587d2016-03-07 16:19:13 +00001868 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, Ordered, LB, UB,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00001869 ST, IL, Chunk);
1870}
1871
1872void CodeGenFunction::EmitOMPDistributeOuterLoop(
1873 OpenMPDistScheduleClauseKind ScheduleKind,
1874 const OMPDistributeDirective &S, OMPPrivateScope &LoopScope,
1875 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1876
1877 auto &RT = CGM.getOpenMPRuntime();
1878
1879 // Emit outer loop.
1880 // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1881 // dynamic
1882 //
1883
1884 const Expr *IVExpr = S.getIterationVariable();
1885 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1886 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1887
1888 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
1889 IVSize, IVSigned, /* Ordered = */ false,
1890 IL, LB, UB, ST, Chunk);
1891
1892 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false,
1893 S, LoopScope, /* Ordered = */ false, LB, UB, ST, IL, Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001894}
1895
Carlo Bertolli9925f152016-06-27 14:55:37 +00001896void CodeGenFunction::EmitOMPDistributeParallelForDirective(
1897 const OMPDistributeParallelForDirective &S) {
1898 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1899 CGM.getOpenMPRuntime().emitInlinedDirective(
1900 *this, OMPD_distribute_parallel_for,
1901 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1902 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev957d8562016-11-17 15:12:05 +00001903 OMPCancelStackRAII CancelRegion(CGF, OMPD_distribute_parallel_for,
1904 /*HasCancel=*/false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00001905 CGF.EmitStmt(
1906 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1907 });
1908}
1909
Kelvin Li4a39add2016-07-05 05:00:15 +00001910void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
1911 const OMPDistributeParallelForSimdDirective &S) {
1912 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1913 CGM.getOpenMPRuntime().emitInlinedDirective(
1914 *this, OMPD_distribute_parallel_for_simd,
1915 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1916 OMPLoopScope PreInitScope(CGF, S);
1917 CGF.EmitStmt(
1918 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1919 });
1920}
Kelvin Li787f3fc2016-07-06 04:45:38 +00001921
1922void CodeGenFunction::EmitOMPDistributeSimdDirective(
1923 const OMPDistributeSimdDirective &S) {
1924 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1925 CGM.getOpenMPRuntime().emitInlinedDirective(
1926 *this, OMPD_distribute_simd,
1927 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1928 OMPLoopScope PreInitScope(CGF, S);
1929 CGF.EmitStmt(
1930 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1931 });
1932}
1933
Kelvin Lia579b912016-07-14 02:54:56 +00001934void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
1935 const OMPTargetParallelForSimdDirective &S) {
1936 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1937 CGM.getOpenMPRuntime().emitInlinedDirective(
1938 *this, OMPD_target_parallel_for_simd,
1939 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1940 OMPLoopScope PreInitScope(CGF, S);
1941 CGF.EmitStmt(
1942 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1943 });
1944}
1945
Kelvin Li986330c2016-07-20 22:57:10 +00001946void CodeGenFunction::EmitOMPTargetSimdDirective(
1947 const OMPTargetSimdDirective &S) {
1948 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1949 CGM.getOpenMPRuntime().emitInlinedDirective(
1950 *this, OMPD_target_simd, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1951 OMPLoopScope PreInitScope(CGF, S);
1952 CGF.EmitStmt(
1953 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1954 });
1955}
1956
Kelvin Li02532872016-08-05 14:37:37 +00001957void CodeGenFunction::EmitOMPTeamsDistributeDirective(
1958 const OMPTeamsDistributeDirective &S) {
1959 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1960 CGM.getOpenMPRuntime().emitInlinedDirective(
1961 *this, OMPD_teams_distribute,
1962 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1963 OMPLoopScope PreInitScope(CGF, S);
1964 CGF.EmitStmt(
1965 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1966 });
1967}
1968
Kelvin Li4e325f72016-10-25 12:50:55 +00001969void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
1970 const OMPTeamsDistributeSimdDirective &S) {
1971 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1972 CGM.getOpenMPRuntime().emitInlinedDirective(
1973 *this, OMPD_teams_distribute_simd,
1974 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1975 OMPLoopScope PreInitScope(CGF, S);
1976 CGF.EmitStmt(
1977 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1978 });
1979}
1980
Kelvin Li579e41c2016-11-30 23:51:03 +00001981void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
1982 const OMPTeamsDistributeParallelForSimdDirective &S) {
1983 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1984 CGM.getOpenMPRuntime().emitInlinedDirective(
1985 *this, OMPD_teams_distribute_parallel_for_simd,
1986 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1987 OMPLoopScope PreInitScope(CGF, S);
1988 CGF.EmitStmt(
1989 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1990 });
1991}
Kelvin Li4e325f72016-10-25 12:50:55 +00001992
Kelvin Li7ade93f2016-12-09 03:24:30 +00001993void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
1994 const OMPTeamsDistributeParallelForDirective &S) {
1995 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1996 CGM.getOpenMPRuntime().emitInlinedDirective(
1997 *this, OMPD_teams_distribute_parallel_for,
1998 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1999 OMPLoopScope PreInitScope(CGF, S);
2000 CGF.EmitStmt(
2001 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2002 });
2003}
2004
Kelvin Libf594a52016-12-17 05:48:59 +00002005void CodeGenFunction::EmitOMPTargetTeamsDirective(
2006 const OMPTargetTeamsDirective &S) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002007 CGM.getOpenMPRuntime().emitInlinedDirective(
2008 *this, OMPD_target_teams, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2009 CGF.EmitStmt(
2010 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Kelvin Libf594a52016-12-17 05:48:59 +00002011 });
2012}
2013
Kelvin Li83c451e2016-12-25 04:52:54 +00002014void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
2015 const OMPTargetTeamsDistributeDirective &S) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002016 CGM.getOpenMPRuntime().emitInlinedDirective(
2017 *this, OMPD_target_teams_distribute,
Kelvin Li83c451e2016-12-25 04:52:54 +00002018 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Kelvin Li26fd21a2016-12-28 17:57:07 +00002019 CGF.EmitStmt(
2020 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Kelvin Li83c451e2016-12-25 04:52:54 +00002021 });
2022}
2023
Kelvin Li80e8f562016-12-29 22:16:30 +00002024void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
2025 const OMPTargetTeamsDistributeParallelForDirective &S) {
2026 CGM.getOpenMPRuntime().emitInlinedDirective(
2027 *this, OMPD_target_teams_distribute_parallel_for,
2028 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2029 CGF.EmitStmt(
2030 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2031 });
2032}
2033
Kelvin Li1851df52017-01-03 05:23:48 +00002034void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2035 const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
2036 CGM.getOpenMPRuntime().emitInlinedDirective(
2037 *this, OMPD_target_teams_distribute_parallel_for_simd,
2038 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2039 CGF.EmitStmt(
2040 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2041 });
2042}
2043
Kelvin Lida681182017-01-10 18:08:18 +00002044void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
2045 const OMPTargetTeamsDistributeSimdDirective &S) {
2046 CGM.getOpenMPRuntime().emitInlinedDirective(
2047 *this, OMPD_target_teams_distribute_simd,
2048 [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2049 CGF.EmitStmt(
2050 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2051 });
2052}
2053
Alexander Musmanc6388682014-12-15 07:07:06 +00002054/// \brief Emit a helper variable and return corresponding lvalue.
2055static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
2056 const DeclRefExpr *Helper) {
2057 auto VDecl = cast<VarDecl>(Helper->getDecl());
2058 CGF.EmitVarDecl(*VDecl);
2059 return CGF.EmitLValue(Helper);
2060}
2061
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002062namespace {
2063 struct ScheduleKindModifiersTy {
2064 OpenMPScheduleClauseKind Kind;
2065 OpenMPScheduleClauseModifier M1;
2066 OpenMPScheduleClauseModifier M2;
2067 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2068 OpenMPScheduleClauseModifier M1,
2069 OpenMPScheduleClauseModifier M2)
2070 : Kind(Kind), M1(M1), M2(M2) {}
2071 };
2072} // namespace
2073
Alexey Bataev38e89532015-04-16 04:54:05 +00002074bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002075 // Emit the loop iteration variable.
2076 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2077 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2078 EmitVarDecl(*IVDecl);
2079
2080 // Emit the iterations count variable.
2081 // If it is not a variable, Sema decided to calculate iterations count on each
2082 // iteration (e.g., it is foldable into a constant).
2083 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2084 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2085 // Emit calculation of the iterations count.
2086 EmitIgnoredExpr(S.getCalcLastIteration());
2087 }
2088
2089 auto &RT = CGM.getOpenMPRuntime();
2090
Alexey Bataev38e89532015-04-16 04:54:05 +00002091 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002092 // Check pre-condition.
2093 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002094 OMPLoopScope PreInitScope(*this, S);
Alexander Musmanc6388682014-12-15 07:07:06 +00002095 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002096 // If the condition constant folds and can be elided, avoid emitting the
2097 // whole loop.
2098 bool CondConstant;
2099 llvm::BasicBlock *ContBlock = nullptr;
2100 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2101 if (!CondConstant)
2102 return false;
2103 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002104 auto *ThenBlock = createBasicBlock("omp.precond.then");
2105 ContBlock = createBasicBlock("omp.precond.end");
2106 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00002107 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00002108 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00002109 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00002110 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002111
Alexey Bataev8b427062016-05-25 12:36:08 +00002112 bool Ordered = false;
2113 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2114 if (OrderedClause->getNumForLoops())
2115 RT.emitDoacrossInit(*this, S);
2116 else
2117 Ordered = true;
2118 }
2119
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002120 llvm::DenseSet<const Expr *> EmittedFinals;
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00002121 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002122 EmitOMPLinearClauseInit(S);
Alexey Bataevef549a82016-03-09 09:49:09 +00002123 // Emit helper vars inits.
2124 LValue LB =
2125 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
2126 LValue UB =
2127 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
2128 LValue ST =
2129 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2130 LValue IL =
2131 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2132
Alexander Musmanc6388682014-12-15 07:07:06 +00002133 // Emit 'then' code.
2134 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002135 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002136 if (EmitOMPFirstprivateClause(S, LoopScope)) {
2137 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002138 // initialization of firstprivate variables and post-update of
2139 // lastprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00002140 CGM.getOpenMPRuntime().emitBarrierCall(
2141 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2142 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00002143 }
Alexey Bataev50a64582015-04-22 12:24:45 +00002144 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00002145 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002146 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002147 EmitOMPPrivateLoopCounters(S, LoopScope);
2148 EmitOMPLinearClause(S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00002149 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00002150
2151 // Detect the loop schedule kind and chunk.
Alexey Bataev3392d762016-02-16 11:18:12 +00002152 llvm::Value *Chunk = nullptr;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002153 OpenMPScheduleTy ScheduleKind;
Alexey Bataev3392d762016-02-16 11:18:12 +00002154 if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002155 ScheduleKind.Schedule = C->getScheduleKind();
2156 ScheduleKind.M1 = C->getFirstScheduleModifier();
2157 ScheduleKind.M2 = C->getSecondScheduleModifier();
Alexey Bataev3392d762016-02-16 11:18:12 +00002158 if (const auto *Ch = C->getChunkSize()) {
2159 Chunk = EmitScalarExpr(Ch);
2160 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2161 S.getIterationVariable()->getType(),
2162 S.getLocStart());
2163 }
2164 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002165 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2166 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002167 // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2168 // If the static schedule kind is specified or if the ordered clause is
2169 // specified, and if no monotonic modifier is specified, the effect will
2170 // be as if the monotonic modifier was specified.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002171 if (RT.isStaticNonchunked(ScheduleKind.Schedule,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002172 /* Chunked */ Chunk != nullptr) &&
2173 !Ordered) {
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002174 if (isOpenMPSimdDirective(S.getDirectiveKind()))
2175 EmitOMPSimdInit(S, /*IsMonotonic=*/true);
Alexander Musmanc6388682014-12-15 07:07:06 +00002176 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2177 // When no chunk_size is specified, the iteration space is divided into
2178 // chunks that are approximately equal in size, and at most one chunk is
2179 // distributed to each thread. Note that the size of the chunks is
2180 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00002181 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
2182 IVSize, IVSigned, Ordered,
2183 IL.getAddress(), LB.getAddress(),
2184 UB.getAddress(), ST.getAddress());
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002185 auto LoopExit =
2186 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00002187 // UB = min(UB, GlobalUB);
2188 EmitIgnoredExpr(S.getEnsureUpperBound());
2189 // IV = LB;
2190 EmitIgnoredExpr(S.getInit());
2191 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00002192 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2193 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00002194 [&S, LoopExit](CodeGenFunction &CGF) {
2195 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002196 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002197 },
2198 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00002199 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00002200 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002201 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2202 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
2203 };
2204 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002205 } else {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002206 const bool IsMonotonic =
2207 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2208 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2209 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2210 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002211 // Emit the outer loop, which requests its work chunk [LB..UB] from
2212 // runtime and runs the inner loop to process it.
Alexey Bataeva6f2a142015-12-31 06:52:34 +00002213 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002214 LB.getAddress(), UB.getAddress(), ST.getAddress(),
2215 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002216 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002217 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2218 EmitOMPSimdFinal(S,
2219 [&](CodeGenFunction &CGF) -> llvm::Value * {
2220 return CGF.Builder.CreateIsNotNull(
2221 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2222 });
2223 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00002224 EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00002225 // Emit post-update of the reduction variables if IsLastIter != 0.
2226 emitPostUpdateForReductionClause(
2227 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2228 return CGF.Builder.CreateIsNotNull(
2229 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2230 });
Alexey Bataev38e89532015-04-16 04:54:05 +00002231 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2232 if (HasLastprivateClause)
2233 EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002234 S, isOpenMPSimdDirective(S.getDirectiveKind()),
2235 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00002236 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002237 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
Alexey Bataevef549a82016-03-09 09:49:09 +00002238 return CGF.Builder.CreateIsNotNull(
2239 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2240 });
Alexander Musmanc6388682014-12-15 07:07:06 +00002241 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002242 if (ContBlock) {
2243 EmitBranch(ContBlock);
2244 EmitBlock(ContBlock, true);
2245 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002246 }
Alexey Bataev38e89532015-04-16 04:54:05 +00002247 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00002248}
2249
2250void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002251 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002252 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2253 PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002254 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002255 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
2256 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002257 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002258 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002259 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2260 S.hasCancel());
2261 }
Alexander Musmanc6388682014-12-15 07:07:06 +00002262
2263 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002264 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002265 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2266 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00002267}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002268
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002269void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002270 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002271 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2272 PrePostActionTy &) {
2273 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
2274 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002275 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002276 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002277 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2278 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002279
2280 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002281 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00002282 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2283 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00002284}
2285
Alexey Bataev2df54a02015-03-12 08:53:29 +00002286static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2287 const Twine &Name,
2288 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00002289 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002290 if (Init)
Akira Hatanaka642f7992016-10-18 19:05:41 +00002291 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002292 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002293}
2294
Alexey Bataev3392d762016-02-16 11:18:12 +00002295void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00002296 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2297 auto *CS = dyn_cast<CompoundStmt>(Stmt);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002298 bool HasLastprivates = false;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002299 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2300 PrePostActionTy &) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002301 auto &C = CGF.CGM.getContext();
2302 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2303 // Emit helper vars inits.
2304 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2305 CGF.Builder.getInt32(0));
2306 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2307 : CGF.Builder.getInt32(0);
2308 LValue UB =
2309 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2310 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2311 CGF.Builder.getInt32(1));
2312 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2313 CGF.Builder.getInt32(0));
2314 // Loop counter.
2315 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2316 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2317 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2318 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2319 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2320 // Generate condition for loop.
2321 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
2322 OK_Ordinary, S.getLocStart(),
2323 /*fpContractable=*/false);
2324 // Increment for loop counter.
2325 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2326 S.getLocStart());
2327 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2328 // Iterate through all sections and emit a switch construct:
2329 // switch (IV) {
2330 // case 0:
2331 // <SectionStmt[0]>;
2332 // break;
2333 // ...
2334 // case <NumSection> - 1:
2335 // <SectionStmt[<NumSection> - 1]>;
2336 // break;
2337 // }
2338 // .omp.sections.exit:
2339 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2340 auto *SwitchStmt = CGF.Builder.CreateSwitch(
2341 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2342 CS == nullptr ? 1 : CS->size());
2343 if (CS) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002344 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00002345 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002346 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2347 CGF.EmitBlock(CaseBB);
2348 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002349 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002350 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00002351 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002352 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002353 } else {
2354 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2355 CGF.EmitBlock(CaseBB);
2356 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2357 CGF.EmitStmt(Stmt);
2358 CGF.EmitBranch(ExitBB);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002359 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002360 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Alexey Bataev2df54a02015-03-12 08:53:29 +00002361 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002362
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002363 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2364 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002365 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002366 // initialization of firstprivate variables and post-update of lastprivate
2367 // variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002368 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2369 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2370 /*ForceSimpleCall=*/true);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00002371 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002372 CGF.EmitOMPPrivateClause(S, LoopScope);
2373 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2374 CGF.EmitOMPReductionClauseInit(S, LoopScope);
2375 (void)LoopScope.Privatize();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002376
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002377 // Emit static non-chunked loop.
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002378 OpenMPScheduleTy ScheduleKind;
2379 ScheduleKind.Schedule = OMPC_SCHEDULE_static;
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002380 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002381 CGF, S.getLocStart(), ScheduleKind, /*IVSize=*/32,
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002382 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
2383 UB.getAddress(), ST.getAddress());
2384 // UB = min(UB, GlobalUB);
2385 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2386 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2387 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2388 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2389 // IV = LB;
2390 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2391 // while (idx <= UB) { BODY; ++idx; }
2392 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2393 [](CodeGenFunction &) {});
2394 // Tell the runtime we are done.
Alexey Bataev957d8562016-11-17 15:12:05 +00002395 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2396 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
2397 };
2398 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002399 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev61205072016-03-02 04:57:40 +00002400 // Emit post-update of the reduction variables if IsLastIter != 0.
2401 emitPostUpdateForReductionClause(
2402 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2403 return CGF.Builder.CreateIsNotNull(
2404 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2405 });
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002406
2407 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2408 if (HasLastprivates)
2409 CGF.EmitOMPLastprivateClauseFinal(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002410 S, /*NoFinals=*/false,
2411 CGF.Builder.CreateIsNotNull(
2412 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002413 };
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002414
2415 bool HasCancel = false;
2416 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2417 HasCancel = OSD->hasCancel();
2418 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2419 HasCancel = OPSD->hasCancel();
Alexey Bataev957d8562016-11-17 15:12:05 +00002420 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002421 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2422 HasCancel);
2423 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2424 // clause. Otherwise the barrier will be generated by the codegen for the
2425 // directive.
2426 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002427 // Emit implicit barrier to synchronize threads and avoid data races on
2428 // initialization of firstprivate variables.
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002429 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2430 OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00002431 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002432}
Alexey Bataev2df54a02015-03-12 08:53:29 +00002433
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002434void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002435 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002436 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002437 EmitSections(S);
2438 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002439 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002440 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002441 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2442 OMPD_sections);
Alexey Bataevf2685682015-03-30 04:30:22 +00002443 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00002444}
2445
2446void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002447 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002448 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002449 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002450 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002451 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2452 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002453}
2454
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002455void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002456 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00002457 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002458 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002459 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002460 // Check if there are any 'copyprivate' clauses associated with this
Alexey Bataevcd8b6a22016-02-15 08:07:17 +00002461 // 'single' construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00002462 // Build a list of copyprivate variables along with helper expressions
2463 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002464 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002465 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00002466 DestExprs.append(C->destination_exprs().begin(),
2467 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002468 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002469 AssignmentOps.append(C->assignment_ops().begin(),
2470 C->assignment_ops().end());
2471 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002472 // Emit code for 'single' region along with 'copyprivate' clauses
2473 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2474 Action.Enter(CGF);
2475 OMPPrivateScope SingleScope(CGF);
2476 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2477 CGF.EmitOMPPrivateClause(S, SingleScope);
2478 (void)SingleScope.Privatize();
2479 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2480 };
Alexey Bataev3392d762016-02-16 11:18:12 +00002481 {
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002482 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00002483 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2484 CopyprivateVars, DestExprs,
2485 SrcExprs, AssignmentOps);
2486 }
2487 // Emit an implicit barrier at the end (to avoid data race on firstprivate
2488 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Alexey Bataev417089f2016-02-17 13:19:37 +00002489 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
Alexey Bataev5521d782015-04-24 04:21:15 +00002490 CGM.getOpenMPRuntime().emitBarrierCall(
2491 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002492 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00002493 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002494}
2495
Alexey Bataev8d690652014-12-04 07:23:53 +00002496void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002497 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2498 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002499 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002500 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002501 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002502 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00002503}
2504
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002505void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002506 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2507 Action.Enter(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002508 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002509 };
Alexey Bataevfc57d162015-12-15 10:55:09 +00002510 Expr *Hint = nullptr;
2511 if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2512 Hint = HintClause->getHint();
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002513 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002514 CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2515 S.getDirectiveName().getAsString(),
2516 CodeGen, S.getLocStart(), Hint);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002517}
2518
Alexey Bataev671605e2015-04-13 05:28:11 +00002519void CodeGenFunction::EmitOMPParallelForDirective(
2520 const OMPParallelForDirective &S) {
2521 // Emit directive as a combined directive that consists of two implicit
2522 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002523 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev957d8562016-11-17 15:12:05 +00002524 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
Alexey Bataev671605e2015-04-13 05:28:11 +00002525 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev671605e2015-04-13 05:28:11 +00002526 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002527 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002528}
2529
Alexander Musmane4e893b2014-09-23 09:33:00 +00002530void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002531 const OMPParallelForSimdDirective &S) {
2532 // Emit directive as a combined directive that consists of two implicit
2533 // directives: 'parallel' with 'for' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002534 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002535 CGF.EmitOMPWorksharingLoop(S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00002536 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002537 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002538}
2539
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002540void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00002541 const OMPParallelSectionsDirective &S) {
2542 // Emit directive as a combined directive that consists of two implicit
2543 // directives: 'parallel' with 'sections' directive.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002544 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2545 CGF.EmitSections(S);
2546 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002547 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002548}
2549
Alexey Bataev7292c292016-04-25 12:22:29 +00002550void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2551 const RegionCodeGenTy &BodyGen,
2552 const TaskGenTy &TaskGen,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002553 OMPTaskDataTy &Data) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002554 // Emit outlined function for task construct.
2555 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002556 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002557 auto *PartId = std::next(I);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002558 auto *TaskT = std::next(I, 4);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002559 // Check if the task is final
2560 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2561 // If the condition constant folds and can be elided, try to avoid emitting
2562 // the condition and the dead arm of the if/else.
2563 auto *Cond = Clause->getCondition();
2564 bool CondConstant;
2565 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2566 Data.Final.setInt(CondConstant);
2567 else
2568 Data.Final.setPointer(EvaluateExprAsBool(Cond));
2569 } else {
2570 // By default the task is not final.
2571 Data.Final.setInt(/*IntVal=*/false);
2572 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002573 // Check if the task has 'priority' clause.
2574 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002575 auto *Prio = Clause->getPriority();
Alexey Bataev5140e742016-07-19 04:21:09 +00002576 Data.Priority.setInt(/*IntVal=*/true);
Alexey Bataevad537bb2016-05-30 09:06:50 +00002577 Data.Priority.setPointer(EmitScalarConversion(
2578 EmitScalarExpr(Prio), Prio->getType(),
2579 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2580 Prio->getExprLoc()));
Alexey Bataev1e1e2862016-05-10 12:21:02 +00002581 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002582 // The first function argument for tasks is a thread id, the second one is a
2583 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002584 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2585 // Get list of private variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002586 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002587 auto IRef = C->varlist_begin();
2588 for (auto *IInit : C->private_copies()) {
2589 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2590 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002591 Data.PrivateVars.push_back(*IRef);
2592 Data.PrivateCopies.push_back(IInit);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002593 }
2594 ++IRef;
2595 }
2596 }
2597 EmittedAsPrivate.clear();
2598 // Get list of firstprivate variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002599 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002600 auto IRef = C->varlist_begin();
2601 auto IElemInitRef = C->inits().begin();
2602 for (auto *IInit : C->private_copies()) {
2603 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2604 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
Alexey Bataev7292c292016-04-25 12:22:29 +00002605 Data.FirstprivateVars.push_back(*IRef);
2606 Data.FirstprivateCopies.push_back(IInit);
2607 Data.FirstprivateInits.push_back(*IElemInitRef);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002608 }
Richard Trieucc3949d2016-02-18 22:34:54 +00002609 ++IRef;
2610 ++IElemInitRef;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002611 }
2612 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002613 // Get list of lastprivate variables (for taskloops).
2614 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2615 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2616 auto IRef = C->varlist_begin();
2617 auto ID = C->destination_exprs().begin();
2618 for (auto *IInit : C->private_copies()) {
2619 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2620 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2621 Data.LastprivateVars.push_back(*IRef);
2622 Data.LastprivateCopies.push_back(IInit);
2623 }
2624 LastprivateDstsOrigs.insert(
2625 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2626 cast<DeclRefExpr>(*IRef)});
2627 ++IRef;
2628 ++ID;
2629 }
2630 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002631 // Build list of dependences.
Alexey Bataev7292c292016-04-25 12:22:29 +00002632 for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2633 for (auto *IRef : C->varlists())
2634 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00002635 auto &&CodeGen = [&Data, CS, &BodyGen, &LastprivateDstsOrigs](
Alexey Bataevf93095a2016-05-05 08:46:22 +00002636 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002637 // Set proper addresses for generated private copies.
Alexey Bataev7292c292016-04-25 12:22:29 +00002638 OMPPrivateScope Scope(CGF);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002639 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2640 !Data.LastprivateVars.empty()) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002641 auto *CopyFn = CGF.Builder.CreateLoad(
2642 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2643 auto *PrivatesPtr = CGF.Builder.CreateLoad(
2644 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2645 // Map privates.
2646 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2647 llvm::SmallVector<llvm::Value *, 16> CallArgs;
2648 CallArgs.push_back(PrivatesPtr);
Alexey Bataev7292c292016-04-25 12:22:29 +00002649 for (auto *E : Data.PrivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002650 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2651 Address PrivatePtr = CGF.CreateMemTemp(
2652 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2653 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2654 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002655 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002656 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00002657 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2658 Address PrivatePtr =
2659 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2660 ".firstpriv.ptr.addr");
2661 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2662 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002663 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00002664 for (auto *E : Data.LastprivateVars) {
2665 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2666 Address PrivatePtr =
2667 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2668 ".lastpriv.ptr.addr");
2669 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2670 CallArgs.push_back(PrivatePtr.getPointer());
2671 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002672 CGF.EmitRuntimeCall(CopyFn, CallArgs);
Alexey Bataevf93095a2016-05-05 08:46:22 +00002673 for (auto &&Pair : LastprivateDstsOrigs) {
2674 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2675 DeclRefExpr DRE(
2676 const_cast<VarDecl *>(OrigVD),
2677 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2678 OrigVD) != nullptr,
2679 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2680 Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2681 return CGF.EmitLValue(&DRE).getAddress();
2682 });
2683 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002684 for (auto &&Pair : PrivatePtrs) {
2685 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2686 CGF.getContext().getDeclAlign(Pair.first));
2687 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2688 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002689 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00002690 (void)Scope.Privatize();
2691
2692 Action.Enter(CGF);
Alexey Bataev7292c292016-04-25 12:22:29 +00002693 BodyGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002694 };
Alexey Bataev7292c292016-04-25 12:22:29 +00002695 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2696 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2697 Data.NumberOfParts);
2698 OMPLexicalScope Scope(*this, S);
2699 TaskGen(*this, OutlinedFn, Data);
2700}
2701
2702void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
2703 // Emit outlined function for task construct.
2704 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2705 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002706 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00002707 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00002708 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2709 if (C->getNameModifier() == OMPD_unknown ||
2710 C->getNameModifier() == OMPD_task) {
2711 IfCond = C->getCondition();
2712 break;
2713 }
Alexey Bataev1d677132015-04-22 13:57:31 +00002714 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002715
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002716 OMPTaskDataTy Data;
2717 // Check if we should emit tied or untied task.
2718 Data.Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00002719 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
2720 CGF.EmitStmt(CS->getCapturedStmt());
2721 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002722 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
Alexey Bataev7292c292016-04-25 12:22:29 +00002723 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002724 const OMPTaskDataTy &Data) {
2725 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
2726 SharedsTy, CapturedStruct, IfCond,
2727 Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00002728 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00002729 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002730}
2731
Alexey Bataev9f797f32015-02-05 05:57:51 +00002732void CodeGenFunction::EmitOMPTaskyieldDirective(
2733 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002734 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00002735}
2736
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002737void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00002738 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002739}
2740
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002741void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2742 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00002743}
2744
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002745void CodeGenFunction::EmitOMPTaskgroupDirective(
2746 const OMPTaskgroupDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002747 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2748 Action.Enter(CGF);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002749 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002750 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002751 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002752 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2753}
2754
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002755void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002756 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002757 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002758 return llvm::makeArrayRef(FlushClause->varlist_begin(),
2759 FlushClause->varlist_end());
2760 }
2761 return llvm::None;
2762 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002763}
2764
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002765void CodeGenFunction::EmitOMPDistributeLoop(const OMPDistributeDirective &S) {
2766 // Emit the loop iteration variable.
2767 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2768 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2769 EmitVarDecl(*IVDecl);
2770
2771 // Emit the iterations count variable.
2772 // If it is not a variable, Sema decided to calculate iterations count on each
2773 // iteration (e.g., it is foldable into a constant).
2774 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2775 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2776 // Emit calculation of the iterations count.
2777 EmitIgnoredExpr(S.getCalcLastIteration());
2778 }
2779
2780 auto &RT = CGM.getOpenMPRuntime();
2781
Carlo Bertolli962bb802017-01-03 18:24:42 +00002782 bool HasLastprivateClause = false;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002783 // Check pre-condition.
2784 {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002785 OMPLoopScope PreInitScope(*this, S);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002786 // Skip the entire loop if we don't meet the precondition.
2787 // If the condition constant folds and can be elided, avoid emitting the
2788 // whole loop.
2789 bool CondConstant;
2790 llvm::BasicBlock *ContBlock = nullptr;
2791 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2792 if (!CondConstant)
2793 return;
2794 } else {
2795 auto *ThenBlock = createBasicBlock("omp.precond.then");
2796 ContBlock = createBasicBlock("omp.precond.end");
2797 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
2798 getProfileCount(&S));
2799 EmitBlock(ThenBlock);
2800 incrementProfileCounter(&S);
2801 }
2802
2803 // Emit 'then' code.
2804 {
2805 // Emit helper vars inits.
2806 LValue LB =
2807 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
2808 LValue UB =
2809 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
2810 LValue ST =
2811 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2812 LValue IL =
2813 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2814
2815 OMPPrivateScope LoopScope(*this);
Carlo Bertolli962bb802017-01-03 18:24:42 +00002816 if (EmitOMPFirstprivateClause(S, LoopScope)) {
2817 // Emit implicit barrier to synchronize threads and avoid data races on
2818 // initialization of firstprivate variables and post-update of
2819 // lastprivate variables.
2820 CGM.getOpenMPRuntime().emitBarrierCall(
2821 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2822 /*ForceSimpleCall=*/true);
2823 }
2824 EmitOMPPrivateClause(S, LoopScope);
2825 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002826 EmitOMPPrivateLoopCounters(S, LoopScope);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002827 (void)LoopScope.Privatize();
2828
2829 // Detect the distribute schedule kind and chunk.
2830 llvm::Value *Chunk = nullptr;
2831 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
2832 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
2833 ScheduleKind = C->getDistScheduleKind();
2834 if (const auto *Ch = C->getChunkSize()) {
2835 Chunk = EmitScalarExpr(Ch);
2836 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2837 S.getIterationVariable()->getType(),
2838 S.getLocStart());
2839 }
2840 }
2841 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2842 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2843
2844 // OpenMP [2.10.8, distribute Construct, Description]
2845 // If dist_schedule is specified, kind must be static. If specified,
2846 // iterations are divided into chunks of size chunk_size, chunks are
2847 // assigned to the teams of the league in a round-robin fashion in the
2848 // order of the team number. When no chunk_size is specified, the
2849 // iteration space is divided into chunks that are approximately equal
2850 // in size, and at most one chunk is distributed to each team of the
2851 // league. The size of the chunks is unspecified in this case.
2852 if (RT.isStaticNonchunked(ScheduleKind,
2853 /* Chunked */ Chunk != nullptr)) {
2854 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
2855 IVSize, IVSigned, /* Ordered = */ false,
2856 IL.getAddress(), LB.getAddress(),
2857 UB.getAddress(), ST.getAddress());
2858 auto LoopExit =
2859 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
2860 // UB = min(UB, GlobalUB);
2861 EmitIgnoredExpr(S.getEnsureUpperBound());
2862 // IV = LB;
2863 EmitIgnoredExpr(S.getInit());
2864 // while (idx <= UB) { BODY; ++idx; }
2865 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2866 S.getInc(),
2867 [&S, LoopExit](CodeGenFunction &CGF) {
2868 CGF.EmitOMPLoopBody(S, LoopExit);
2869 CGF.EmitStopPoint(&S);
2870 },
2871 [](CodeGenFunction &) {});
2872 EmitBlock(LoopExit.getBlock());
2873 // Tell the runtime we are done.
2874 RT.emitForStaticFinish(*this, S.getLocStart());
2875 } else {
2876 // Emit the outer loop, which requests its work chunk [LB..UB] from
2877 // runtime and runs the inner loop to process it.
2878 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope,
2879 LB.getAddress(), UB.getAddress(), ST.getAddress(),
2880 IL.getAddress(), Chunk);
2881 }
Carlo Bertolli962bb802017-01-03 18:24:42 +00002882
2883 // Emit final copy of the lastprivate variables if IsLastIter != 0.
2884 if (HasLastprivateClause)
2885 EmitOMPLastprivateClauseFinal(
2886 S, /*NoFinals=*/false,
2887 Builder.CreateIsNotNull(
2888 EmitLoadOfScalar(IL, S.getLocStart())));
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002889 }
2890
2891 // We're now done with the loop, so jump to the continuation block.
2892 if (ContBlock) {
2893 EmitBranch(ContBlock);
2894 EmitBlock(ContBlock, true);
2895 }
2896 }
2897}
2898
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002899void CodeGenFunction::EmitOMPDistributeDirective(
2900 const OMPDistributeDirective &S) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002901 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002902 CGF.EmitOMPDistributeLoop(S);
2903 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002904 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002905 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
2906 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002907}
2908
Alexey Bataev5f600d62015-09-29 03:48:57 +00002909static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2910 const CapturedStmt *S) {
2911 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2912 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2913 CGF.CapturedStmtInfo = &CapStmtInfo;
2914 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2915 Fn->addFnAttr(llvm::Attribute::NoInline);
2916 return Fn;
2917}
2918
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002919void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
Alexey Bataev8b427062016-05-25 12:36:08 +00002920 if (!S.getAssociatedStmt()) {
2921 for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
2922 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
Alexey Bataev8ef31412015-12-18 07:58:25 +00002923 return;
Alexey Bataev8b427062016-05-25 12:36:08 +00002924 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002925 auto *C = S.getSingleClause<OMPSIMDClause>();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002926 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
2927 PrePostActionTy &Action) {
Alexey Bataev5f600d62015-09-29 03:48:57 +00002928 if (C) {
2929 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2930 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2931 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2932 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2933 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2934 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002935 Action.Enter(CGF);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002936 CGF.EmitStmt(
2937 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2938 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002939 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00002940 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev5f600d62015-09-29 03:48:57 +00002941 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002942}
2943
Alexey Bataevb57056f2015-01-22 06:17:56 +00002944static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002945 QualType SrcType, QualType DestType,
2946 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002947 assert(CGF.hasScalarEvaluationKind(DestType) &&
2948 "DestType must have scalar evaluation kind.");
2949 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2950 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002951 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2952 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002953 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002954 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002955}
2956
2957static CodeGenFunction::ComplexPairTy
2958convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002959 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002960 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2961 "DestType must have complex evaluation kind.");
2962 CodeGenFunction::ComplexPairTy ComplexVal;
2963 if (Val.isScalar()) {
2964 // Convert the input element to the element type of the complex.
2965 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002966 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2967 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002968 ComplexVal = CodeGenFunction::ComplexPairTy(
2969 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2970 } else {
2971 assert(Val.isComplex() && "Must be a scalar or complex.");
2972 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2973 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2974 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002975 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002976 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002977 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002978 }
2979 return ComplexVal;
2980}
2981
Alexey Bataev5e018f92015-04-23 06:35:10 +00002982static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
2983 LValue LVal, RValue RVal) {
2984 if (LVal.isGlobalReg()) {
2985 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
2986 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00002987 CGF.EmitAtomicStore(RVal, LVal,
2988 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
2989 : llvm::AtomicOrdering::Monotonic,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002990 LVal.isVolatile(), /*IsInit=*/false);
2991 }
2992}
2993
Alexey Bataev8524d152016-01-21 12:35:58 +00002994void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
2995 QualType RValTy, SourceLocation Loc) {
2996 switch (getEvaluationKind(LVal.getType())) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002997 case TEK_Scalar:
Alexey Bataev8524d152016-01-21 12:35:58 +00002998 EmitStoreThroughLValue(RValue::get(convertToScalarValue(
2999 *this, RVal, RValTy, LVal.getType(), Loc)),
3000 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003001 break;
3002 case TEK_Complex:
Alexey Bataev8524d152016-01-21 12:35:58 +00003003 EmitStoreOfComplex(
3004 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003005 /*isInit=*/false);
3006 break;
3007 case TEK_Aggregate:
3008 llvm_unreachable("Must be a scalar or complex.");
3009 }
3010}
3011
Alexey Bataevb57056f2015-01-22 06:17:56 +00003012static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3013 const Expr *X, const Expr *V,
3014 SourceLocation Loc) {
3015 // v = x;
3016 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3017 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3018 LValue XLValue = CGF.EmitLValue(X);
3019 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00003020 RValue Res = XLValue.isGlobalReg()
3021 ? CGF.EmitLoadOfLValue(XLValue, Loc)
JF Bastien92f4ef12016-04-06 17:26:42 +00003022 : CGF.EmitAtomicLoad(
3023 XLValue, Loc,
3024 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3025 : llvm::AtomicOrdering::Monotonic,
3026 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00003027 // OpenMP, 2.12.6, atomic Construct
3028 // Any atomic construct with a seq_cst clause forces the atomically
3029 // performed operation to include an implicit flush operation without a
3030 // list.
3031 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003032 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev8524d152016-01-21 12:35:58 +00003033 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00003034}
3035
Alexey Bataevb8329262015-02-27 06:33:30 +00003036static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3037 const Expr *X, const Expr *E,
3038 SourceLocation Loc) {
3039 // x = expr;
3040 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00003041 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00003042 // OpenMP, 2.12.6, atomic Construct
3043 // Any atomic construct with a seq_cst clause forces the atomically
3044 // performed operation to include an implicit flush operation without a
3045 // list.
3046 if (IsSeqCst)
3047 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3048}
3049
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003050static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3051 RValue Update,
3052 BinaryOperatorKind BO,
3053 llvm::AtomicOrdering AO,
3054 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003055 auto &Context = CGF.CGM.getContext();
3056 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00003057 // expression is simple and atomic is allowed for the given type for the
3058 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003059 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00003060 !Update.getScalarVal()->getType()->isIntegerTy() ||
3061 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3062 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00003063 X.getAddress().getElementType())) ||
3064 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003065 !Context.getTargetInfo().hasBuiltinAtomic(
3066 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00003067 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003068
3069 llvm::AtomicRMWInst::BinOp RMWOp;
3070 switch (BO) {
3071 case BO_Add:
3072 RMWOp = llvm::AtomicRMWInst::Add;
3073 break;
3074 case BO_Sub:
3075 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00003076 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003077 RMWOp = llvm::AtomicRMWInst::Sub;
3078 break;
3079 case BO_And:
3080 RMWOp = llvm::AtomicRMWInst::And;
3081 break;
3082 case BO_Or:
3083 RMWOp = llvm::AtomicRMWInst::Or;
3084 break;
3085 case BO_Xor:
3086 RMWOp = llvm::AtomicRMWInst::Xor;
3087 break;
3088 case BO_LT:
3089 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3090 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3091 : llvm::AtomicRMWInst::Max)
3092 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3093 : llvm::AtomicRMWInst::UMax);
3094 break;
3095 case BO_GT:
3096 RMWOp = X.getType()->hasSignedIntegerRepresentation()
3097 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3098 : llvm::AtomicRMWInst::Min)
3099 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3100 : llvm::AtomicRMWInst::UMin);
3101 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003102 case BO_Assign:
3103 RMWOp = llvm::AtomicRMWInst::Xchg;
3104 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003105 case BO_Mul:
3106 case BO_Div:
3107 case BO_Rem:
3108 case BO_Shl:
3109 case BO_Shr:
3110 case BO_LAnd:
3111 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003112 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003113 case BO_PtrMemD:
3114 case BO_PtrMemI:
3115 case BO_LE:
3116 case BO_GE:
3117 case BO_EQ:
3118 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003119 case BO_AddAssign:
3120 case BO_SubAssign:
3121 case BO_AndAssign:
3122 case BO_OrAssign:
3123 case BO_XorAssign:
3124 case BO_MulAssign:
3125 case BO_DivAssign:
3126 case BO_RemAssign:
3127 case BO_ShlAssign:
3128 case BO_ShrAssign:
3129 case BO_Comma:
3130 llvm_unreachable("Unsupported atomic update operation");
3131 }
3132 auto *UpdateVal = Update.getScalarVal();
3133 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3134 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00003135 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003136 X.getType()->hasSignedIntegerRepresentation());
3137 }
John McCall7f416cc2015-09-08 08:05:57 +00003138 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003139 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003140}
3141
Alexey Bataev5e018f92015-04-23 06:35:10 +00003142std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003143 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3144 llvm::AtomicOrdering AO, SourceLocation Loc,
3145 const llvm::function_ref<RValue(RValue)> &CommonGen) {
3146 // Update expressions are allowed to have the following forms:
3147 // x binop= expr; -> xrval + expr;
3148 // x++, ++x -> xrval + 1;
3149 // x--, --x -> xrval - 1;
3150 // x = x binop expr; -> xrval binop expr
3151 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003152 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3153 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003154 if (X.isGlobalReg()) {
3155 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3156 // 'xrval'.
3157 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3158 } else {
3159 // Perform compare-and-swap procedure.
3160 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003161 }
3162 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003163 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003164}
3165
3166static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3167 const Expr *X, const Expr *E,
3168 const Expr *UE, bool IsXLHSInRHSPart,
3169 SourceLocation Loc) {
3170 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3171 "Update expr in 'atomic update' must be a binary operator.");
3172 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3173 // Update expressions are allowed to have the following forms:
3174 // x binop= expr; -> xrval + expr;
3175 // x++, ++x -> xrval + 1;
3176 // x--, --x -> xrval - 1;
3177 // x = x binop expr; -> xrval binop expr
3178 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003179 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00003180 LValue XLValue = CGF.EmitLValue(X);
3181 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003182 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3183 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003184 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3185 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3186 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3187 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3188 auto Gen =
3189 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3190 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3191 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3192 return CGF.EmitAnyExpr(UE);
3193 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00003194 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3195 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3196 // OpenMP, 2.12.6, atomic Construct
3197 // Any atomic construct with a seq_cst clause forces the atomically
3198 // performed operation to include an implicit flush operation without a
3199 // list.
3200 if (IsSeqCst)
3201 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3202}
3203
3204static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003205 QualType SourceType, QualType ResType,
3206 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003207 switch (CGF.getEvaluationKind(ResType)) {
3208 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003209 return RValue::get(
3210 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00003211 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003212 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003213 return RValue::getComplex(Res.first, Res.second);
3214 }
3215 case TEK_Aggregate:
3216 break;
3217 }
3218 llvm_unreachable("Must be a scalar or complex.");
3219}
3220
3221static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3222 bool IsPostfixUpdate, const Expr *V,
3223 const Expr *X, const Expr *E,
3224 const Expr *UE, bool IsXLHSInRHSPart,
3225 SourceLocation Loc) {
3226 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3227 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3228 RValue NewVVal;
3229 LValue VLValue = CGF.EmitLValue(V);
3230 LValue XLValue = CGF.EmitLValue(X);
3231 RValue ExprRValue = CGF.EmitAnyExpr(E);
JF Bastien92f4ef12016-04-06 17:26:42 +00003232 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3233 : llvm::AtomicOrdering::Monotonic;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003234 QualType NewVValType;
3235 if (UE) {
3236 // 'x' is updated with some additional value.
3237 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3238 "Update expr in 'atomic capture' must be a binary operator.");
3239 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3240 // Update expressions are allowed to have the following forms:
3241 // x binop= expr; -> xrval + expr;
3242 // x++, ++x -> xrval + 1;
3243 // x--, --x -> xrval - 1;
3244 // x = x binop expr; -> xrval binop expr
3245 // x = expr Op x; - > expr binop xrval;
3246 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3247 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3248 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3249 NewVValType = XRValExpr->getType();
3250 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3251 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003252 IsPostfixUpdate](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003253 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3254 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3255 RValue Res = CGF.EmitAnyExpr(UE);
3256 NewVVal = IsPostfixUpdate ? XRValue : Res;
3257 return Res;
3258 };
3259 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3260 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3261 if (Res.first) {
3262 // 'atomicrmw' instruction was generated.
3263 if (IsPostfixUpdate) {
3264 // Use old value from 'atomicrmw'.
3265 NewVVal = Res.second;
3266 } else {
3267 // 'atomicrmw' does not provide new value, so evaluate it using old
3268 // value of 'x'.
3269 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3270 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3271 NewVVal = CGF.EmitAnyExpr(UE);
3272 }
3273 }
3274 } else {
3275 // 'x' is simply rewritten with some 'expr'.
3276 NewVValType = X->getType().getNonReferenceType();
3277 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003278 X->getType().getNonReferenceType(), Loc);
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00003279 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
Alexey Bataev5e018f92015-04-23 06:35:10 +00003280 NewVVal = XRValue;
3281 return ExprRValue;
3282 };
3283 // Try to perform atomicrmw xchg, otherwise simple exchange.
3284 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3285 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3286 Loc, Gen);
3287 if (Res.first) {
3288 // 'atomicrmw' instruction was generated.
3289 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3290 }
3291 }
3292 // Emit post-update store to 'v' of old/new 'x' value.
Alexey Bataev8524d152016-01-21 12:35:58 +00003293 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00003294 // OpenMP, 2.12.6, atomic Construct
3295 // Any atomic construct with a seq_cst clause forces the atomically
3296 // performed operation to include an implicit flush operation without a
3297 // list.
3298 if (IsSeqCst)
3299 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3300}
3301
Alexey Bataevb57056f2015-01-22 06:17:56 +00003302static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00003303 bool IsSeqCst, bool IsPostfixUpdate,
3304 const Expr *X, const Expr *V, const Expr *E,
3305 const Expr *UE, bool IsXLHSInRHSPart,
3306 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00003307 switch (Kind) {
3308 case OMPC_read:
3309 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3310 break;
3311 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00003312 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3313 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003314 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003315 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00003316 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3317 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003318 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00003319 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3320 IsXLHSInRHSPart, Loc);
3321 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00003322 case OMPC_if:
3323 case OMPC_final:
3324 case OMPC_num_threads:
3325 case OMPC_private:
3326 case OMPC_firstprivate:
3327 case OMPC_lastprivate:
3328 case OMPC_reduction:
3329 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00003330 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003331 case OMPC_collapse:
3332 case OMPC_default:
3333 case OMPC_seq_cst:
3334 case OMPC_shared:
3335 case OMPC_linear:
3336 case OMPC_aligned:
3337 case OMPC_copyin:
3338 case OMPC_copyprivate:
3339 case OMPC_flush:
3340 case OMPC_proc_bind:
3341 case OMPC_schedule:
3342 case OMPC_ordered:
3343 case OMPC_nowait:
3344 case OMPC_untied:
3345 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00003346 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003347 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00003348 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00003349 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003350 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00003351 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00003352 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00003353 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00003354 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00003355 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00003356 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00003357 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00003358 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00003359 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00003360 case OMPC_defaultmap:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003361 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00003362 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00003363 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00003364 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00003365 case OMPC_is_device_ptr:
Alexey Bataevb57056f2015-01-22 06:17:56 +00003366 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3367 }
3368}
3369
3370void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003371 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00003372 OpenMPClauseKind Kind = OMPC_unknown;
3373 for (auto *C : S.clauses()) {
3374 // Find first clause (skip seq_cst clause, if it is first).
3375 if (C->getClauseKind() != OMPC_seq_cst) {
3376 Kind = C->getClauseKind();
3377 break;
3378 }
3379 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003380
3381 const auto *CS =
3382 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003383 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00003384 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003385 }
3386 // Processing for statements under 'atomic capture'.
3387 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3388 for (const auto *C : Compound->body()) {
3389 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3390 enterFullExpression(EWC);
3391 }
3392 }
3393 }
Alexey Bataev10fec572015-03-11 04:48:56 +00003394
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003395 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3396 PrePostActionTy &) {
Alexey Bataev33c56402015-12-14 09:26:19 +00003397 CGF.EmitStopPoint(CS);
Alexey Bataev5e018f92015-04-23 06:35:10 +00003398 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3399 S.getV(), S.getExpr(), S.getUpdateExpr(),
3400 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003401 };
Alexey Bataev4ba78a42016-04-27 07:56:03 +00003402 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003403 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00003404}
3405
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003406static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3407 const OMPExecutableDirective &S,
3408 const RegionCodeGenTy &CodeGen) {
3409 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3410 CodeGenModule &CGM = CGF.CGM;
Samuel Antaobed3c462015-10-02 16:14:20 +00003411 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
3412
3413 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003414 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
Samuel Antaobed3c462015-10-02 16:14:20 +00003415
Samuel Antaoee8fb302016-01-06 13:42:12 +00003416 llvm::Function *Fn = nullptr;
3417 llvm::Constant *FnID = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00003418
3419 // Check if we have any if clause associated with the directive.
3420 const Expr *IfCond = nullptr;
3421
3422 if (auto *C = S.getSingleClause<OMPIfClause>()) {
3423 IfCond = C->getCondition();
3424 }
3425
3426 // Check if we have any device clause associated with the directive.
3427 const Expr *Device = nullptr;
3428 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3429 Device = C->getDevice();
3430 }
3431
Samuel Antaoee8fb302016-01-06 13:42:12 +00003432 // Check if we have an if clause whose conditional always evaluates to false
3433 // or if we do not have any targets specified. If so the target region is not
3434 // an offload entry point.
3435 bool IsOffloadEntry = true;
3436 if (IfCond) {
3437 bool Val;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003438 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
Samuel Antaoee8fb302016-01-06 13:42:12 +00003439 IsOffloadEntry = false;
3440 }
3441 if (CGM.getLangOpts().OMPTargetTriples.empty())
3442 IsOffloadEntry = false;
3443
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003444 assert(CGF.CurFuncDecl && "No parent declaration for target region!");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003445 StringRef ParentName;
3446 // In case we have Ctors/Dtors we use the complete type variant to produce
3447 // the mangling of the device outlined kernel.
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003448 if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003449 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003450 else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
Samuel Antaoee8fb302016-01-06 13:42:12 +00003451 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3452 else
3453 ParentName =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003454 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003455
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003456 // Emit target region as a standalone region.
3457 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3458 IsOffloadEntry, CodeGen);
3459 OMPLexicalScope Scope(CGF, S);
3460 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
Samuel Antaobed3c462015-10-02 16:14:20 +00003461 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003462}
3463
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00003464static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3465 PrePostActionTy &Action) {
3466 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3467 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3468 CGF.EmitOMPPrivateClause(S, PrivateScope);
3469 (void)PrivateScope.Privatize();
3470
3471 Action.Enter(CGF);
3472 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3473}
3474
3475void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3476 StringRef ParentName,
3477 const OMPTargetDirective &S) {
3478 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3479 emitTargetRegion(CGF, S, Action);
3480 };
3481 llvm::Function *Fn;
3482 llvm::Constant *Addr;
3483 // Emit target region as a standalone region.
3484 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3485 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3486 assert(Fn && Addr && "Target device function emission failed.");
3487}
3488
3489void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3490 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3491 emitTargetRegion(CGF, S, Action);
3492 };
3493 emitCommonOMPTargetDirective(*this, S, CodeGen);
3494}
3495
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003496static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3497 const OMPExecutableDirective &S,
3498 OpenMPDirectiveKind InnermostKind,
3499 const RegionCodeGenTy &CodeGen) {
3500 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003501 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().
3502 emitParallelOrTeamsOutlinedFunction(S,
3503 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Samuel Antaob68e2db2016-03-03 16:20:23 +00003504
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003505 const OMPTeamsDirective &TD = *dyn_cast<OMPTeamsDirective>(&S);
3506 const OMPNumTeamsClause *NT = TD.getSingleClause<OMPNumTeamsClause>();
3507 const OMPThreadLimitClause *TL = TD.getSingleClause<OMPThreadLimitClause>();
3508 if (NT || TL) {
Carlo Bertollic6872252016-04-04 15:55:02 +00003509 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3510 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003511
Carlo Bertollic6872252016-04-04 15:55:02 +00003512 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3513 S.getLocStart());
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003514 }
3515
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003516 OMPLexicalScope Scope(CGF, S);
3517 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3518 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003519 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3520 CapturedVars);
3521}
3522
3523void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
Kelvin Li51336dd2016-12-15 17:55:32 +00003524 // Emit teams region as a standalone region.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003525 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003526 OMPPrivateScope PrivateScope(CGF);
Carlo Bertolli6ad7b5a2016-03-03 22:09:40 +00003527 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3528 CGF.EmitOMPPrivateClause(S, PrivateScope);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00003529 (void)PrivateScope.Privatize();
3530 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3531 };
3532 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003533}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003534
3535void CodeGenFunction::EmitOMPCancellationPointDirective(
3536 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00003537 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
3538 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003539}
3540
Alexey Bataev80909872015-07-02 11:25:17 +00003541void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003542 const Expr *IfCond = nullptr;
3543 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3544 if (C->getNameModifier() == OMPD_unknown ||
3545 C->getNameModifier() == OMPD_cancel) {
3546 IfCond = C->getCondition();
3547 break;
3548 }
3549 }
3550 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003551 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00003552}
3553
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003554CodeGenFunction::JumpDest
3555CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
Alexey Bataev957d8562016-11-17 15:12:05 +00003556 if (Kind == OMPD_parallel || Kind == OMPD_task ||
3557 Kind == OMPD_target_parallel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003558 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003559 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
Alexey Bataev957d8562016-11-17 15:12:05 +00003560 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
3561 Kind == OMPD_distribute_parallel_for ||
3562 Kind == OMPD_target_parallel_for);
3563 return OMPCancelStack.getExitBlock();
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003564}
Michael Wong65f367f2015-07-21 13:44:28 +00003565
Samuel Antaocc10b852016-07-28 14:23:26 +00003566void CodeGenFunction::EmitOMPUseDevicePtrClause(
3567 const OMPClause &NC, OMPPrivateScope &PrivateScope,
3568 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
3569 const auto &C = cast<OMPUseDevicePtrClause>(NC);
3570 auto OrigVarIt = C.varlist_begin();
3571 auto InitIt = C.inits().begin();
3572 for (auto PvtVarIt : C.private_copies()) {
3573 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
3574 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
3575 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
3576
3577 // In order to identify the right initializer we need to match the
3578 // declaration used by the mapping logic. In some cases we may get
3579 // OMPCapturedExprDecl that refers to the original declaration.
3580 const ValueDecl *MatchingVD = OrigVD;
3581 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
3582 // OMPCapturedExprDecl are used to privative fields of the current
3583 // structure.
3584 auto *ME = cast<MemberExpr>(OED->getInit());
3585 assert(isa<CXXThisExpr>(ME->getBase()) &&
3586 "Base should be the current struct!");
3587 MatchingVD = ME->getMemberDecl();
3588 }
3589
3590 // If we don't have information about the current list item, move on to
3591 // the next one.
3592 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
3593 if (InitAddrIt == CaptureDeviceAddrMap.end())
3594 continue;
3595
3596 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
3597 // Initialize the temporary initialization variable with the address we
3598 // get from the runtime library. We have to cast the source address
3599 // because it is always a void *. References are materialized in the
3600 // privatization scope, so the initialization here disregards the fact
3601 // the original variable is a reference.
3602 QualType AddrQTy =
3603 getContext().getPointerType(OrigVD->getType().getNonReferenceType());
3604 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
3605 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
3606 setAddrOfLocalVar(InitVD, InitAddr);
3607
3608 // Emit private declaration, it will be initialized by the value we
3609 // declaration we just added to the local declarations map.
3610 EmitDecl(*PvtVD);
3611
3612 // The initialization variables reached its purpose in the emission
3613 // ofthe previous declaration, so we don't need it anymore.
3614 LocalDeclMap.erase(InitVD);
3615
3616 // Return the address of the private variable.
3617 return GetAddrOfLocalVar(PvtVD);
3618 });
3619 assert(IsRegistered && "firstprivate var already registered as private");
3620 // Silence the warning about unused variable.
3621 (void)IsRegistered;
3622
3623 ++OrigVarIt;
3624 ++InitIt;
3625 }
3626}
3627
Michael Wong65f367f2015-07-21 13:44:28 +00003628// Generate the instructions for '#pragma omp target data' directive.
3629void CodeGenFunction::EmitOMPTargetDataDirective(
3630 const OMPTargetDataDirective &S) {
Samuel Antaocc10b852016-07-28 14:23:26 +00003631 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
3632
3633 // Create a pre/post action to signal the privatization of the device pointer.
3634 // This action can be replaced by the OpenMP runtime code generation to
3635 // deactivate privatization.
3636 bool PrivatizeDevicePointers = false;
3637 class DevicePointerPrivActionTy : public PrePostActionTy {
3638 bool &PrivatizeDevicePointers;
3639
3640 public:
3641 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
3642 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
3643 void Enter(CodeGenFunction &CGF) override {
3644 PrivatizeDevicePointers = true;
3645 }
Samuel Antaodf158d52016-04-27 22:58:19 +00003646 };
Samuel Antaocc10b852016-07-28 14:23:26 +00003647 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
3648
3649 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
3650 CodeGenFunction &CGF, PrePostActionTy &Action) {
3651 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3652 CGF.EmitStmt(
3653 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3654 };
3655
3656 // Codegen that selects wheather to generate the privatization code or not.
3657 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
3658 &InnermostCodeGen](CodeGenFunction &CGF,
3659 PrePostActionTy &Action) {
3660 RegionCodeGenTy RCG(InnermostCodeGen);
3661 PrivatizeDevicePointers = false;
3662
3663 // Call the pre-action to change the status of PrivatizeDevicePointers if
3664 // needed.
3665 Action.Enter(CGF);
3666
3667 if (PrivatizeDevicePointers) {
3668 OMPPrivateScope PrivateScope(CGF);
3669 // Emit all instances of the use_device_ptr clause.
3670 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
3671 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
3672 Info.CaptureDeviceAddrMap);
3673 (void)PrivateScope.Privatize();
3674 RCG(CGF);
3675 } else
3676 RCG(CGF);
3677 };
3678
3679 // Forward the provided action to the privatization codegen.
3680 RegionCodeGenTy PrivRCG(PrivCodeGen);
3681 PrivRCG.setAction(Action);
3682
3683 // Notwithstanding the body of the region is emitted as inlined directive,
3684 // we don't use an inline scope as changes in the references inside the
3685 // region are expected to be visible outside, so we do not privative them.
3686 OMPLexicalScope Scope(CGF, S);
3687 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
3688 PrivRCG);
3689 };
3690
3691 RegionCodeGenTy RCG(CodeGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00003692
3693 // If we don't have target devices, don't bother emitting the data mapping
3694 // code.
3695 if (CGM.getLangOpts().OMPTargetTriples.empty()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00003696 RCG(*this);
Samuel Antaodf158d52016-04-27 22:58:19 +00003697 return;
3698 }
3699
3700 // Check if we have any if clause associated with the directive.
3701 const Expr *IfCond = nullptr;
3702 if (auto *C = S.getSingleClause<OMPIfClause>())
3703 IfCond = C->getCondition();
3704
3705 // Check if we have any device clause associated with the directive.
3706 const Expr *Device = nullptr;
3707 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3708 Device = C->getDevice();
3709
Samuel Antaocc10b852016-07-28 14:23:26 +00003710 // Set the action to signal privatization of device pointers.
3711 RCG.setAction(PrivAction);
3712
3713 // Emit region code.
3714 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
3715 Info);
Michael Wong65f367f2015-07-21 13:44:28 +00003716}
Alexey Bataev49f6e782015-12-01 04:18:41 +00003717
Samuel Antaodf67fc42016-01-19 19:15:56 +00003718void CodeGenFunction::EmitOMPTargetEnterDataDirective(
3719 const OMPTargetEnterDataDirective &S) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00003720 // If we don't have target devices, don't bother emitting the data mapping
3721 // code.
3722 if (CGM.getLangOpts().OMPTargetTriples.empty())
3723 return;
3724
3725 // Check if we have any if clause associated with the directive.
3726 const Expr *IfCond = nullptr;
3727 if (auto *C = S.getSingleClause<OMPIfClause>())
3728 IfCond = C->getCondition();
3729
3730 // Check if we have any device clause associated with the directive.
3731 const Expr *Device = nullptr;
3732 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3733 Device = C->getDevice();
3734
Samuel Antao8d2d7302016-05-26 18:30:22 +00003735 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003736}
3737
Samuel Antao72590762016-01-19 20:04:50 +00003738void CodeGenFunction::EmitOMPTargetExitDataDirective(
3739 const OMPTargetExitDataDirective &S) {
Samuel Antao8dd66282016-04-27 23:14:30 +00003740 // If we don't have target devices, don't bother emitting the data mapping
3741 // code.
3742 if (CGM.getLangOpts().OMPTargetTriples.empty())
3743 return;
3744
3745 // Check if we have any if clause associated with the directive.
3746 const Expr *IfCond = nullptr;
3747 if (auto *C = S.getSingleClause<OMPIfClause>())
3748 IfCond = C->getCondition();
3749
3750 // Check if we have any device clause associated with the directive.
3751 const Expr *Device = nullptr;
3752 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3753 Device = C->getDevice();
3754
Samuel Antao8d2d7302016-05-26 18:30:22 +00003755 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao72590762016-01-19 20:04:50 +00003756}
3757
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003758void CodeGenFunction::EmitOMPTargetParallelDirective(
3759 const OMPTargetParallelDirective &S) {
3760 // TODO: codegen for target parallel.
3761}
3762
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003763void CodeGenFunction::EmitOMPTargetParallelForDirective(
3764 const OMPTargetParallelForDirective &S) {
3765 // TODO: codegen for target parallel for.
3766}
3767
Alexey Bataev7292c292016-04-25 12:22:29 +00003768/// Emit a helper variable and return corresponding lvalue.
3769static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
3770 const ImplicitParamDecl *PVD,
3771 CodeGenFunction::OMPPrivateScope &Privates) {
3772 auto *VDecl = cast<VarDecl>(Helper->getDecl());
3773 Privates.addPrivate(
3774 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
3775}
3776
3777void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
3778 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
3779 // Emit outlined function for task construct.
3780 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3781 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
3782 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3783 const Expr *IfCond = nullptr;
3784 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3785 if (C->getNameModifier() == OMPD_unknown ||
3786 C->getNameModifier() == OMPD_taskloop) {
3787 IfCond = C->getCondition();
3788 break;
3789 }
3790 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003791
3792 OMPTaskDataTy Data;
3793 // Check if taskloop must be emitted without taskgroup.
3794 Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
Alexey Bataev7292c292016-04-25 12:22:29 +00003795 // TODO: Check if we should emit tied or untied task.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003796 Data.Tied = true;
3797 // Set scheduling for taskloop
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00003798 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
3799 // grainsize clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003800 Data.Schedule.setInt(/*IntVal=*/false);
3801 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00003802 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
3803 // num_tasks clause
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003804 Data.Schedule.setInt(/*IntVal=*/true);
3805 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00003806 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003807
3808 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
3809 // if (PreCond) {
3810 // for (IV in 0..LastIteration) BODY;
3811 // <Final counter/linear vars updates>;
3812 // }
3813 //
3814
3815 // Emit: if (PreCond) - begin.
3816 // If the condition constant folds and can be elided, avoid emitting the
3817 // whole loop.
3818 bool CondConstant;
3819 llvm::BasicBlock *ContBlock = nullptr;
3820 OMPLoopScope PreInitScope(CGF, S);
3821 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3822 if (!CondConstant)
3823 return;
3824 } else {
3825 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
3826 ContBlock = CGF.createBasicBlock("taskloop.if.end");
3827 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
3828 CGF.getProfileCount(&S));
3829 CGF.EmitBlock(ThenBlock);
3830 CGF.incrementProfileCounter(&S);
3831 }
3832
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003833 if (isOpenMPSimdDirective(S.getDirectiveKind()))
3834 CGF.EmitOMPSimdInit(S);
3835
Alexey Bataev7292c292016-04-25 12:22:29 +00003836 OMPPrivateScope LoopScope(CGF);
3837 // Emit helper vars inits.
3838 enum { LowerBound = 5, UpperBound, Stride, LastIter };
3839 auto *I = CS->getCapturedDecl()->param_begin();
3840 auto *LBP = std::next(I, LowerBound);
3841 auto *UBP = std::next(I, UpperBound);
3842 auto *STP = std::next(I, Stride);
3843 auto *LIP = std::next(I, LastIter);
3844 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
3845 LoopScope);
3846 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
3847 LoopScope);
3848 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
3849 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
3850 LoopScope);
3851 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003852 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7292c292016-04-25 12:22:29 +00003853 (void)LoopScope.Privatize();
3854 // Emit the loop iteration variable.
3855 const Expr *IVExpr = S.getIterationVariable();
3856 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
3857 CGF.EmitVarDecl(*IVDecl);
3858 CGF.EmitIgnoredExpr(S.getInit());
3859
3860 // Emit the iterations count variable.
3861 // If it is not a variable, Sema decided to calculate iterations count on
3862 // each iteration (e.g., it is foldable into a constant).
3863 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3864 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3865 // Emit calculation of the iterations count.
3866 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
3867 }
3868
3869 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
3870 S.getInc(),
3871 [&S](CodeGenFunction &CGF) {
3872 CGF.EmitOMPLoopBody(S, JumpDest());
3873 CGF.EmitStopPoint(&S);
3874 },
3875 [](CodeGenFunction &) {});
3876 // Emit: if (PreCond) - end.
3877 if (ContBlock) {
3878 CGF.EmitBranch(ContBlock);
3879 CGF.EmitBlock(ContBlock, true);
3880 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003881 // Emit final copy of the lastprivate variables if IsLastIter != 0.
3882 if (HasLastprivateClause) {
3883 CGF.EmitOMPLastprivateClauseFinal(
3884 S, isOpenMPSimdDirective(S.getDirectiveKind()),
3885 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
3886 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
3887 (*LIP)->getType(), S.getLocStart())));
3888 }
Alexey Bataev7292c292016-04-25 12:22:29 +00003889 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003890 auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
3891 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
3892 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003893 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
3894 OMPLoopScope PreInitScope(CGF, S);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003895 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
3896 OutlinedFn, SharedsTy,
3897 CapturedStruct, IfCond, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003898 };
3899 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
3900 CodeGen);
3901 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003902 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00003903}
3904
Alexey Bataev49f6e782015-12-01 04:18:41 +00003905void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003906 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003907}
3908
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003909void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
3910 const OMPTaskLoopSimdDirective &S) {
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003911 EmitOMPTaskLoopBasedDirective(S);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003912}
Samuel Antao686c70c2016-05-26 17:30:50 +00003913
3914// Generate the instructions for '#pragma omp target update' directive.
3915void CodeGenFunction::EmitOMPTargetUpdateDirective(
3916 const OMPTargetUpdateDirective &S) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00003917 // If we don't have target devices, don't bother emitting the data mapping
3918 // code.
3919 if (CGM.getLangOpts().OMPTargetTriples.empty())
3920 return;
3921
3922 // Check if we have any if clause associated with the directive.
3923 const Expr *IfCond = nullptr;
3924 if (auto *C = S.getSingleClause<OMPIfClause>())
3925 IfCond = C->getCondition();
3926
3927 // Check if we have any device clause associated with the directive.
3928 const Expr *Device = nullptr;
3929 if (auto *C = S.getSingleClause<OMPDeviceClause>())
3930 Device = C->getDevice();
3931
3932 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
Samuel Antao686c70c2016-05-26 17:30:50 +00003933}