blob: 1a70a551290f9a2c53433bb698de3d267746f3c7 [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
14#include "CGOpenMPRuntime.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000017#include "TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000018#include "clang/AST/Stmt.h"
19#include "clang/AST/StmtOpenMP.h"
20using namespace clang;
21using namespace CodeGen;
22
Alexey Bataev2377fe92015-09-10 08:12:02 +000023void CodeGenFunction::GenerateOpenMPCapturedVars(
Samuel Antaobed3c462015-10-02 16:14:20 +000024 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars,
25 bool UseOnlyReferences) {
Alexey Bataev2377fe92015-09-10 08:12:02 +000026 const RecordDecl *RD = S.getCapturedRecordDecl();
27 auto CurField = RD->field_begin();
28 auto CurCap = S.captures().begin();
29 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
30 E = S.capture_init_end();
31 I != E; ++I, ++CurField, ++CurCap) {
32 if (CurField->hasCapturedVLAType()) {
33 auto VAT = CurField->getCapturedVLAType();
Samuel Antaobed3c462015-10-02 16:14:20 +000034 auto *Val = VLASizeMap[VAT->getSizeExpr()];
35 // If we need to use only references, create a temporary location for the
36 // size of the VAT.
37 if (UseOnlyReferences) {
38 LValue LV =
39 MakeAddrLValue(CreateMemTemp(CurField->getType(), "__vla_size_ref"),
40 CurField->getType());
41 EmitStoreThroughLValue(RValue::get(Val), LV);
42 Val = LV.getAddress().getPointer();
43 }
44 CapturedVars.push_back(Val);
Alexey Bataev2377fe92015-09-10 08:12:02 +000045 } else if (CurCap->capturesThis())
46 CapturedVars.push_back(CXXThisValue);
47 else
48 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
49 }
50}
51
52llvm::Function *
Samuel Antaobed3c462015-10-02 16:14:20 +000053CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S,
54 bool UseOnlyReferences) {
Alexey Bataev2377fe92015-09-10 08:12:02 +000055 assert(
56 CapturedStmtInfo &&
57 "CapturedStmtInfo should be set when generating the captured function");
58 const CapturedDecl *CD = S.getCapturedDecl();
59 const RecordDecl *RD = S.getCapturedRecordDecl();
60 assert(CD->hasBody() && "missing CapturedDecl body");
61
62 // Build the argument list.
63 ASTContext &Ctx = CGM.getContext();
64 FunctionArgList Args;
65 Args.append(CD->param_begin(),
66 std::next(CD->param_begin(), CD->getContextParamPosition()));
67 auto I = S.captures().begin();
68 for (auto *FD : RD->fields()) {
69 QualType ArgType = FD->getType();
70 IdentifierInfo *II = nullptr;
71 VarDecl *CapVar = nullptr;
72 if (I->capturesVariable()) {
73 CapVar = I->getCapturedVar();
74 II = CapVar->getIdentifier();
75 } else if (I->capturesThis())
76 II = &getContext().Idents.get("this");
77 else {
78 assert(I->capturesVariableArrayType());
79 II = &getContext().Idents.get("vla");
Samuel Antaobed3c462015-10-02 16:14:20 +000080 if (UseOnlyReferences)
81 ArgType = getContext().getLValueReferenceType(
82 ArgType, /*SpelledAsLValue=*/false);
Alexey Bataev2377fe92015-09-10 08:12:02 +000083 }
84 if (ArgType->isVariablyModifiedType())
85 ArgType = getContext().getVariableArrayDecayedType(ArgType);
86 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
87 FD->getLocation(), II, ArgType));
88 ++I;
89 }
90 Args.append(
91 std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
92 CD->param_end());
93
94 // Create the function declaration.
95 FunctionType::ExtInfo ExtInfo;
96 const CGFunctionInfo &FuncInfo =
97 CGM.getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, Args, ExtInfo,
98 /*IsVariadic=*/false);
99 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
100
101 llvm::Function *F = llvm::Function::Create(
102 FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
103 CapturedStmtInfo->getHelperName(), &CGM.getModule());
104 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
105 if (CD->isNothrow())
106 F->addFnAttr(llvm::Attribute::NoUnwind);
107
108 // Generate the function.
109 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
110 CD->getBody()->getLocStart());
111 unsigned Cnt = CD->getContextParamPosition();
112 I = S.captures().begin();
113 for (auto *FD : RD->fields()) {
114 LValue ArgLVal =
115 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
116 AlignmentSource::Decl);
117 if (FD->hasCapturedVLAType()) {
Samuel Antaobed3c462015-10-02 16:14:20 +0000118 if (UseOnlyReferences)
119 ArgLVal = EmitLoadOfReferenceLValue(
120 ArgLVal.getAddress(), ArgLVal.getType()->castAs<ReferenceType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000121 auto *ExprArg =
122 EmitLoadOfLValue(ArgLVal, SourceLocation()).getScalarVal();
123 auto VAT = FD->getCapturedVLAType();
124 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
125 } else if (I->capturesVariable()) {
126 auto *Var = I->getCapturedVar();
127 QualType VarTy = Var->getType();
128 Address ArgAddr = ArgLVal.getAddress();
129 if (!VarTy->isReferenceType()) {
130 ArgAddr = EmitLoadOfReference(
131 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
132 }
Alexey Bataevc71a4092015-09-11 10:29:41 +0000133 setAddrOfLocalVar(
134 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
Alexey Bataev2377fe92015-09-10 08:12:02 +0000135 } else {
136 // If 'this' is captured, load it into CXXThisValue.
137 assert(I->capturesThis());
138 CXXThisValue =
139 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
140 }
141 ++Cnt, ++I;
142 }
143
144 PGO.assignRegionCounters(CD, F);
145 CapturedStmtInfo->EmitBody(*this, CD->getBody());
146 FinishFunction(CD->getBodyRBrace());
147
148 return F;
149}
150
Alexey Bataev9959db52014-05-06 10:08:46 +0000151//===----------------------------------------------------------------------===//
152// OpenMP Directive Emission
153//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +0000154void CodeGenFunction::EmitOMPAggregateAssign(
John McCall7f416cc2015-09-08 08:05:57 +0000155 Address DestAddr, Address SrcAddr, QualType OriginalType,
156 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000157 // Perform element-by-element initialization.
158 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +0000159
160 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000161 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +0000162 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
163 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
164
165 auto SrcBegin = SrcAddr.getPointer();
166 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +0000167 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +0000168 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
169 // The basic structure here is a while-do loop.
170 auto BodyBB = createBasicBlock("omp.arraycpy.body");
171 auto DoneBB = createBasicBlock("omp.arraycpy.done");
172 auto IsEmpty =
173 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
174 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000175
Alexey Bataev420d45b2015-04-14 05:11:24 +0000176 // Enter the loop body, making that address the current address.
177 auto EntryBB = Builder.GetInsertBlock();
178 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000179
180 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
181
182 llvm::PHINode *SrcElementPHI =
183 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
184 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
185 Address SrcElementCurrent =
186 Address(SrcElementPHI,
187 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
188
189 llvm::PHINode *DestElementPHI =
190 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
191 DestElementPHI->addIncoming(DestBegin, EntryBB);
192 Address DestElementCurrent =
193 Address(DestElementPHI,
194 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000195
Alexey Bataev420d45b2015-04-14 05:11:24 +0000196 // Emit copy.
197 CopyGen(DestElementCurrent, SrcElementCurrent);
198
199 // Shift the address forward by one element.
200 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000201 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000202 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +0000203 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +0000204 // Check whether we've reached the end.
205 auto Done =
206 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
207 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +0000208 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
209 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +0000210
211 // Done.
212 EmitBlock(DoneBB, /*IsFinished=*/true);
213}
214
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000215/// \brief Emit initialization of arrays of complex types.
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000216/// \param DestAddr Address of the array.
217/// \param Type Type of array.
218/// \param Init Initial expression of array.
219static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
220 QualType Type, const Expr *Init) {
221 // Perform element-by-element initialization.
222 QualType ElementTy;
223
224 // Drill down to the base element type on both arrays.
225 auto ArrayTy = Type->getAsArrayTypeUnsafe();
226 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
227 DestAddr =
228 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
229
230 auto DestBegin = DestAddr.getPointer();
231 // Cast from pointer to array type to pointer to single element.
232 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
233 // The basic structure here is a while-do loop.
234 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
235 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
236 auto IsEmpty =
237 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
238 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
239
240 // Enter the loop body, making that address the current address.
241 auto EntryBB = CGF.Builder.GetInsertBlock();
242 CGF.EmitBlock(BodyBB);
243
244 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
245
246 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
247 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
248 DestElementPHI->addIncoming(DestBegin, EntryBB);
249 Address DestElementCurrent =
250 Address(DestElementPHI,
251 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
252
253 // Emit copy.
254 {
255 CodeGenFunction::RunCleanupsScope InitScope(CGF);
256 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
257 /*IsInitializer=*/false);
258 }
259
260 // Shift the address forward by one element.
261 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
262 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
263 // Check whether we've reached the end.
264 auto Done =
265 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
266 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
267 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
268
269 // Done.
270 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
271}
272
John McCall7f416cc2015-09-08 08:05:57 +0000273void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
274 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +0000275 const VarDecl *SrcVD, const Expr *Copy) {
276 if (OriginalType->isArrayType()) {
277 auto *BO = dyn_cast<BinaryOperator>(Copy);
278 if (BO && BO->getOpcode() == BO_Assign) {
279 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +0000280 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000281 } else {
282 // For arrays with complex element types perform element by element
283 // copying.
John McCall7f416cc2015-09-08 08:05:57 +0000284 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +0000285 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000286 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000287 // Working with the single array element, so have to remap
288 // destination and source variables to corresponding array
289 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000290 CodeGenFunction::OMPPrivateScope Remap(*this);
291 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000292 return DestElement;
293 });
294 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000295 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000296 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000297 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000298 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000299 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000300 } else {
301 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000302 CodeGenFunction::OMPPrivateScope Remap(*this);
303 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
304 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000305 (void)Remap.Privatize();
306 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000307 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000308 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000309}
310
Alexey Bataev69c62a92015-04-15 04:52:20 +0000311bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
312 OMPPrivateScope &PrivateScope) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000313 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000314 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000315 auto IRef = C->varlist_begin();
316 auto InitsRef = C->inits().begin();
317 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000318 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000319 if (EmittedAsFirstprivate.count(OrigVD) == 0) {
320 EmittedAsFirstprivate.insert(OrigVD);
321 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
322 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
323 bool IsRegistered;
324 DeclRefExpr DRE(
325 const_cast<VarDecl *>(OrigVD),
326 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
327 OrigVD) != nullptr,
328 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000329 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000330 QualType Type = OrigVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000331 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000332 // Emit VarDecl with copy init for arrays.
333 // Get the address of the original variable captured in current
334 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000335 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000336 auto Emission = EmitAutoVarAlloca(*VD);
337 auto *Init = VD->getInit();
338 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
339 // Perform simple memcpy.
340 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000341 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000342 } else {
343 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000344 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000345 [this, VDInit, Init](Address DestElement,
346 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000347 // Clean up any temporaries needed by the initialization.
348 RunCleanupsScope InitScope(*this);
349 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000350 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000351 EmitAnyExprToMem(Init, DestElement,
352 Init->getType().getQualifiers(),
353 /*IsInitializer*/ false);
354 LocalDeclMap.erase(VDInit);
355 });
356 }
357 EmitAutoVarCleanups(Emission);
358 return Emission.getAllocatedAddress();
359 });
360 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000361 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000362 // Emit private VarDecl with copy init.
363 // Remap temp VDInit variable to the address of the original
364 // variable
365 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000366 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000367 EmitDecl(*VD);
368 LocalDeclMap.erase(VDInit);
369 return GetAddrOfLocalVar(VD);
370 });
371 }
372 assert(IsRegistered &&
373 "firstprivate var already registered as private");
374 // Silence the warning about unused variable.
375 (void)IsRegistered;
376 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000377 ++IRef, ++InitsRef;
378 }
379 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000380 return !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000381}
382
Alexey Bataev03b340a2014-10-21 03:16:40 +0000383void CodeGenFunction::EmitOMPPrivateClause(
384 const OMPExecutableDirective &D,
385 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev50a64582015-04-22 12:24:45 +0000386 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000387 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000388 auto IRef = C->varlist_begin();
389 for (auto IInit : C->private_copies()) {
390 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000391 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
392 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
393 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000394 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000395 // Emit private VarDecl with copy init.
396 EmitDecl(*VD);
397 return GetAddrOfLocalVar(VD);
398 });
399 assert(IsRegistered && "private var already registered as private");
400 // Silence the warning about unused variable.
401 (void)IsRegistered;
402 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000403 ++IRef;
404 }
405 }
406}
407
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000408bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
409 // threadprivate_var1 = master_threadprivate_var1;
410 // operator=(threadprivate_var2, master_threadprivate_var2);
411 // ...
412 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000413 llvm::DenseSet<const VarDecl *> CopiedVars;
414 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000415 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000416 auto IRef = C->varlist_begin();
417 auto ISrcRef = C->source_exprs().begin();
418 auto IDestRef = C->destination_exprs().begin();
419 for (auto *AssignOp : C->assignment_ops()) {
420 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000421 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000422 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000423
424 // Get the address of the master variable. If we are emitting code with
425 // TLS support, the address is passed from the master as field in the
426 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000427 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000428 if (getLangOpts().OpenMPUseTLS &&
429 getContext().getTargetInfo().isTLSSupported()) {
430 assert(CapturedStmtInfo->lookup(VD) &&
431 "Copyin threadprivates should have been captured!");
432 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
433 VK_LValue, (*IRef)->getExprLoc());
434 MasterAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev2377fe92015-09-10 08:12:02 +0000435 LocalDeclMap.erase(VD);
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000436 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000437 MasterAddr =
438 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
439 : CGM.GetAddrOfGlobal(VD),
440 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000441 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000442 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000443 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000444 if (CopiedVars.size() == 1) {
445 // At first check if current thread is a master thread. If it is, no
446 // need to copy data.
447 CopyBegin = createBasicBlock("copyin.not.master");
448 CopyEnd = createBasicBlock("copyin.not.master.end");
449 Builder.CreateCondBr(
450 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000451 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
452 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000453 CopyBegin, CopyEnd);
454 EmitBlock(CopyBegin);
455 }
456 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
457 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000458 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000459 }
460 ++IRef;
461 ++ISrcRef;
462 ++IDestRef;
463 }
464 }
465 if (CopyEnd) {
466 // Exit out of copying procedure for non-master thread.
467 EmitBlock(CopyEnd, /*IsFinished=*/true);
468 return true;
469 }
470 return false;
471}
472
Alexey Bataev38e89532015-04-16 04:54:05 +0000473bool CodeGenFunction::EmitOMPLastprivateClauseInit(
474 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000475 bool HasAtLeastOneLastprivate = false;
476 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000477 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000478 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000479 auto IRef = C->varlist_begin();
480 auto IDestRef = C->destination_exprs().begin();
481 for (auto *IInit : C->private_copies()) {
482 // Keep the address of the original variable for future update at the end
483 // of the loop.
484 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
485 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
486 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000487 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000488 DeclRefExpr DRE(
489 const_cast<VarDecl *>(OrigVD),
490 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
491 OrigVD) != nullptr,
492 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
493 return EmitLValue(&DRE).getAddress();
494 });
495 // Check if the variable is also a firstprivate: in this case IInit is
496 // not generated. Initialization of this variable will happen in codegen
497 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000498 if (IInit) {
499 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
500 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000501 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000502 // Emit private VarDecl with copy init.
503 EmitDecl(*VD);
504 return GetAddrOfLocalVar(VD);
505 });
506 assert(IsRegistered &&
507 "lastprivate var already registered as private");
508 (void)IsRegistered;
509 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000510 }
511 ++IRef, ++IDestRef;
512 }
513 }
514 return HasAtLeastOneLastprivate;
515}
516
517void CodeGenFunction::EmitOMPLastprivateClauseFinal(
518 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
519 // Emit following code:
520 // if (<IsLastIterCond>) {
521 // orig_var1 = private_orig_var1;
522 // ...
523 // orig_varn = private_orig_varn;
524 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000525 llvm::BasicBlock *ThenBB = nullptr;
526 llvm::BasicBlock *DoneBB = nullptr;
527 if (IsLastIterCond) {
528 ThenBB = createBasicBlock(".omp.lastprivate.then");
529 DoneBB = createBasicBlock(".omp.lastprivate.done");
530 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
531 EmitBlock(ThenBB);
532 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000533 llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
534 const Expr *LastIterVal = nullptr;
535 const Expr *IVExpr = nullptr;
536 const Expr *IncExpr = nullptr;
537 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000538 if (isOpenMPWorksharingDirective(D.getDirectiveKind())) {
539 LastIterVal = cast<VarDecl>(cast<DeclRefExpr>(
540 LoopDirective->getUpperBoundVariable())
541 ->getDecl())
542 ->getAnyInitializer();
543 IVExpr = LoopDirective->getIterationVariable();
544 IncExpr = LoopDirective->getInc();
545 auto IUpdate = LoopDirective->updates().begin();
546 for (auto *E : LoopDirective->counters()) {
547 auto *D = cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
548 LoopCountersAndUpdates[D] = *IUpdate;
549 ++IUpdate;
550 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000551 }
552 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000553 {
Alexey Bataev38e89532015-04-16 04:54:05 +0000554 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000555 bool FirstLCV = true;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000556 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000557 auto IRef = C->varlist_begin();
558 auto ISrcRef = C->source_exprs().begin();
559 auto IDestRef = C->destination_exprs().begin();
560 for (auto *AssignOp : C->assignment_ops()) {
561 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000562 QualType Type = PrivateVD->getType();
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000563 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
564 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
565 // If lastprivate variable is a loop control variable for loop-based
566 // directive, update its value before copyin back to original
567 // variable.
568 if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD)) {
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000569 if (FirstLCV && LastIterVal) {
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000570 EmitAnyExprToMem(LastIterVal, EmitLValue(IVExpr).getAddress(),
571 IVExpr->getType().getQualifiers(),
572 /*IsInitializer=*/false);
573 EmitIgnoredExpr(IncExpr);
574 FirstLCV = false;
575 }
576 EmitIgnoredExpr(UpExpr);
577 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000578 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
579 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
580 // Get the address of the original variable.
John McCall7f416cc2015-09-08 08:05:57 +0000581 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
Alexey Bataev38e89532015-04-16 04:54:05 +0000582 // Get the address of the private variable.
John McCall7f416cc2015-09-08 08:05:57 +0000583 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
584 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
Alexey Bataevcaacd532015-09-04 11:26:21 +0000585 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000586 Address(Builder.CreateLoad(PrivateAddr),
587 getNaturalTypeAlignment(RefTy->getPointeeType()));
588 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000589 }
590 ++IRef;
591 ++ISrcRef;
592 ++IDestRef;
593 }
594 }
595 }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000596 if (IsLastIterCond) {
597 EmitBlock(DoneBB, /*IsFinished=*/true);
598 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000599}
600
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000601void CodeGenFunction::EmitOMPReductionClauseInit(
602 const OMPExecutableDirective &D,
603 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000604 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000605 auto ILHS = C->lhs_exprs().begin();
606 auto IRHS = C->rhs_exprs().begin();
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000607 auto IPriv = C->privates().begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000608 for (auto IRef : C->varlists()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000609 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000610 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
611 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
612 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
613 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
614 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
615 Base = TempOASE->getBase()->IgnoreParenImpCasts();
616 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
617 Base = TempASE->getBase()->IgnoreParenImpCasts();
618 auto *DE = cast<DeclRefExpr>(Base);
619 auto *OrigVD = cast<VarDecl>(DE->getDecl());
620 auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
621 auto OASELValueUB =
622 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
623 auto OriginalBaseLValue = EmitLValue(DE);
624 auto BaseLValue = OriginalBaseLValue;
625 auto *Zero = Builder.getInt64(/*C=*/0);
626 llvm::SmallVector<llvm::Value *, 4> Indexes;
627 Indexes.push_back(Zero);
628 auto *ItemTy =
629 OASELValueLB.getPointer()->getType()->getPointerElementType();
630 auto *Ty = BaseLValue.getPointer()->getType()->getPointerElementType();
631 while (Ty != ItemTy) {
632 Indexes.push_back(Zero);
633 Ty = Ty->getPointerElementType();
634 }
635 BaseLValue = MakeAddrLValue(
636 Address(Builder.CreateInBoundsGEP(BaseLValue.getPointer(), Indexes),
637 OASELValueLB.getAlignment()),
638 OASELValueLB.getType(), OASELValueLB.getAlignmentSource());
639 // Store the address of the original variable associated with the LHS
640 // implicit variable.
641 PrivateScope.addPrivate(LHSVD, [this, OASELValueLB]() -> Address {
642 return OASELValueLB.getAddress();
643 });
644 // Emit reduction copy.
645 bool IsRegistered = PrivateScope.addPrivate(
646 OrigVD, [this, PrivateVD, BaseLValue, OASELValueLB, OASELValueUB,
647 OriginalBaseLValue]() -> Address {
648 // Emit VarDecl with copy init for arrays.
649 // Get the address of the original variable captured in current
650 // captured region.
651 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
652 OASELValueLB.getPointer());
653 Size = Builder.CreateNUWAdd(
654 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
655 CodeGenFunction::OpaqueValueMapping OpaqueMap(
656 *this, cast<OpaqueValueExpr>(
657 getContext()
658 .getAsVariableArrayType(PrivateVD->getType())
659 ->getSizeExpr()),
660 RValue::get(Size));
661 EmitVariablyModifiedType(PrivateVD->getType());
662 auto Emission = EmitAutoVarAlloca(*PrivateVD);
663 auto Addr = Emission.getAllocatedAddress();
664 auto *Init = PrivateVD->getInit();
665 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
666 EmitAutoVarCleanups(Emission);
667 // Emit private VarDecl with reduction init.
668 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
669 OASELValueLB.getPointer());
670 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
671 Ptr = Builder.CreatePointerBitCastOrAddrSpaceCast(
672 Ptr, OriginalBaseLValue.getPointer()->getType());
673 return Address(Ptr, OriginalBaseLValue.getAlignment());
674 });
675 assert(IsRegistered && "private var already registered as private");
676 // Silence the warning about unused variable.
677 (void)IsRegistered;
678 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
679 return GetAddrOfLocalVar(PrivateVD);
680 });
681 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
682 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
683 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
684 Base = TempASE->getBase()->IgnoreParenImpCasts();
685 auto *DE = cast<DeclRefExpr>(Base);
686 auto *OrigVD = cast<VarDecl>(DE->getDecl());
687 auto ASELValue = EmitLValue(ASE);
688 auto OriginalBaseLValue = EmitLValue(DE);
689 auto BaseLValue = OriginalBaseLValue;
690 auto *Zero = Builder.getInt64(/*C=*/0);
691 llvm::SmallVector<llvm::Value *, 4> Indexes;
692 Indexes.push_back(Zero);
693 auto *ItemTy =
694 ASELValue.getPointer()->getType()->getPointerElementType();
695 auto *Ty = BaseLValue.getPointer()->getType()->getPointerElementType();
696 while (Ty != ItemTy) {
697 Indexes.push_back(Zero);
698 Ty = Ty->getPointerElementType();
699 }
700 BaseLValue = MakeAddrLValue(
701 Address(Builder.CreateInBoundsGEP(BaseLValue.getPointer(), Indexes),
702 ASELValue.getAlignment()),
703 ASELValue.getType(), ASELValue.getAlignmentSource());
704 // Store the address of the original variable associated with the LHS
705 // implicit variable.
706 PrivateScope.addPrivate(LHSVD, [this, ASELValue]() -> Address {
707 return ASELValue.getAddress();
708 });
709 // Emit reduction copy.
710 bool IsRegistered = PrivateScope.addPrivate(
711 OrigVD, [this, PrivateVD, BaseLValue, ASELValue,
712 OriginalBaseLValue]() -> Address {
713 // Emit private VarDecl with reduction init.
714 EmitDecl(*PrivateVD);
715 auto Addr = GetAddrOfLocalVar(PrivateVD);
716 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
717 ASELValue.getPointer());
718 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
719 Ptr = Builder.CreatePointerBitCastOrAddrSpaceCast(
720 Ptr, OriginalBaseLValue.getPointer()->getType());
721 return Address(Ptr, OriginalBaseLValue.getAlignment());
722 });
723 assert(IsRegistered && "private var already registered as private");
724 // Silence the warning about unused variable.
725 (void)IsRegistered;
726 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
727 return GetAddrOfLocalVar(PrivateVD);
728 });
729 } else {
730 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
731 // Store the address of the original variable associated with the LHS
732 // implicit variable.
733 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> Address {
734 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
735 CapturedStmtInfo->lookup(OrigVD) != nullptr,
736 IRef->getType(), VK_LValue, IRef->getExprLoc());
737 return EmitLValue(&DRE).getAddress();
738 });
739 // Emit reduction copy.
740 bool IsRegistered =
741 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> Address {
742 // Emit private VarDecl with reduction init.
743 EmitDecl(*PrivateVD);
744 return GetAddrOfLocalVar(PrivateVD);
745 });
746 assert(IsRegistered && "private var already registered as private");
747 // Silence the warning about unused variable.
748 (void)IsRegistered;
749 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
750 return GetAddrOfLocalVar(PrivateVD);
751 });
752 }
753 ++ILHS, ++IRHS, ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000754 }
755 }
756}
757
758void CodeGenFunction::EmitOMPReductionClauseFinal(
759 const OMPExecutableDirective &D) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000760 llvm::SmallVector<const Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000761 llvm::SmallVector<const Expr *, 8> LHSExprs;
762 llvm::SmallVector<const Expr *, 8> RHSExprs;
763 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000764 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000765 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000766 HasAtLeastOneReduction = true;
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000767 Privates.append(C->privates().begin(), C->privates().end());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000768 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
769 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
770 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
771 }
772 if (HasAtLeastOneReduction) {
773 // Emit nowait reduction if nowait clause is present or directive is a
774 // parallel directive (it always has implicit barrier).
775 CGM.getOpenMPRuntime().emitReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +0000776 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000777 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000778 isOpenMPParallelDirective(D.getDirectiveKind()) ||
779 D.getDirectiveKind() == OMPD_simd,
780 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000781 }
782}
783
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000784static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
785 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000786 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000787 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000788 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev2377fe92015-09-10 08:12:02 +0000789 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
790 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000791 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000792 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000793 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +0000794 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +0000795 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
796 /*IgnoreResultAssign*/ true);
797 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
798 CGF, NumThreads, NumThreadsClause->getLocStart());
799 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000800 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev7f210c62015-06-18 13:40:03 +0000801 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +0000802 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
803 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
804 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000805 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +0000806 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
807 if (C->getNameModifier() == OMPD_unknown ||
808 C->getNameModifier() == OMPD_parallel) {
809 IfCond = C->getCondition();
810 break;
811 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000812 }
813 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +0000814 CapturedVars, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000815}
816
817void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
818 LexicalScope Scope(*this, S.getSourceRange());
819 // Emit parallel region as a standalone region.
820 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
821 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000822 bool Copyins = CGF.EmitOMPCopyinClause(S);
823 bool Firstprivates = CGF.EmitOMPFirstprivateClause(S, PrivateScope);
824 if (Copyins || Firstprivates) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000825 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000826 // initialization of firstprivate variables or propagation master's thread
827 // values of threadprivate variables to local instances of that variables
828 // of all other implicit threads.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000829 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
830 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
831 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000832 }
833 CGF.EmitOMPPrivateClause(S, PrivateScope);
834 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
835 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000836 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000837 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000838 // Emit implicit barrier at the end of the 'parallel' directive.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000839 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
840 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
841 /*ForceSimpleCall=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000842 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000843 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +0000844}
Alexander Musman515ad8c2014-05-22 08:54:05 +0000845
Alexey Bataev0f34da12015-07-02 04:17:07 +0000846void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
847 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +0000848 RunCleanupsScope BodyScope(*this);
849 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000850 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +0000851 EmitIgnoredExpr(I);
852 }
Alexander Musman3276a272015-03-21 10:12:56 +0000853 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000854 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexander Musman3276a272015-03-21 10:12:56 +0000855 for (auto U : C->updates()) {
856 EmitIgnoredExpr(U);
857 }
858 }
859
Alexander Musmana5f070a2014-10-01 06:03:56 +0000860 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +0000861 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +0000862 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000863 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000864 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000865 // The end (updates/cleanups).
866 EmitBlock(Continue.getBlock());
867 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +0000868 // TODO: Update lastprivates if the SeparateIter flag is true.
869 // This will be implemented in a follow-up OMPLastprivateClause patch, but
870 // result should be still correct without it, as we do not make these
871 // variables private yet.
Alexander Musmana5f070a2014-10-01 06:03:56 +0000872}
873
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000874void CodeGenFunction::EmitOMPInnerLoop(
875 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
876 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000877 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
878 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +0000879 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000880
881 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +0000882 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000883 EmitBlock(CondBlock);
884 LoopStack.push(CondBlock);
885
886 // If there are any cleanups between here and the loop-exit scope,
887 // create a block to stage a loop exit along.
888 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +0000889 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +0000890 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000891
Alexander Musmand196ef22014-10-07 08:57:09 +0000892 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000893
Alexey Bataev2df54a02015-03-12 08:53:29 +0000894 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +0000895 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000896 if (ExitBlock != LoopExit.getBlock()) {
897 EmitBlock(ExitBlock);
898 EmitBranchThroughCleanup(LoopExit);
899 }
900
901 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +0000902 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000903
904 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +0000905 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000906 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
907
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000908 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000909
910 // Emit "IV = IV + 1" and a back-edge to the condition block.
911 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +0000912 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000913 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000914 BreakContinueStack.pop_back();
915 EmitBranch(CondBlock);
916 LoopStack.pop();
917 // Emit the fall-through block.
918 EmitBlock(LoopExit.getBlock());
919}
920
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000921void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000922 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000923 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000924 for (auto Init : C->inits()) {
925 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000926 auto *OrigVD = cast<VarDecl>(
927 cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())->getDecl());
928 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
929 CapturedStmtInfo->lookup(OrigVD) != nullptr,
930 VD->getInit()->getType(), VK_LValue,
931 VD->getInit()->getExprLoc());
932 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
933 EmitExprAsInit(&DRE, VD,
John McCall7f416cc2015-09-08 08:05:57 +0000934 MakeAddrLValue(Emission.getAllocatedAddress(), VD->getType()),
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000935 /*capturedByInit=*/false);
936 EmitAutoVarCleanups(Emission);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000937 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000938 // Emit the linear steps for the linear clauses.
939 // If a step is not constant, it is pre-calculated before the loop.
940 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
941 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000942 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000943 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000944 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000945 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000946 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000947}
948
949static void emitLinearClauseFinal(CodeGenFunction &CGF,
950 const OMPLoopDirective &D) {
Alexander Musman3276a272015-03-21 10:12:56 +0000951 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000952 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000953 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +0000954 for (auto F : C->finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000955 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
956 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000957 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +0000958 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000959 Address OrigAddr = CGF.EmitLValue(&DRE).getAddress();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000960 CodeGenFunction::OMPPrivateScope VarScope(CGF);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000961 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +0000962 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +0000963 (void)VarScope.Privatize();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000964 CGF.EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000965 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +0000966 }
967 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000968}
969
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000970static void emitAlignedClause(CodeGenFunction &CGF,
971 const OMPExecutableDirective &D) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000972 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000973 unsigned ClauseAlignment = 0;
974 if (auto AlignmentExpr = Clause->getAlignment()) {
975 auto AlignmentCI =
976 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
977 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +0000978 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000979 for (auto E : Clause->varlists()) {
980 unsigned Alignment = ClauseAlignment;
981 if (Alignment == 0) {
982 // OpenMP [2.8.1, Description]
983 // If no optional parameter is specified, implementation-defined default
984 // alignments for SIMD instructions on the target platforms are assumed.
985 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +0000986 CGF.getContext()
987 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
988 E->getType()->getPointeeType()))
989 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000990 }
991 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
992 "alignment is not power of 2");
993 if (Alignment != 0) {
994 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
995 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
996 }
Alexander Musman09184fe2014-09-30 05:29:28 +0000997 }
998 }
999}
1000
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001001static void emitPrivateLoopCounters(CodeGenFunction &CGF,
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001002 CodeGenFunction::OMPPrivateScope &LoopScope,
Alexey Bataeva8899172015-08-06 12:30:57 +00001003 ArrayRef<Expr *> Counters,
1004 ArrayRef<Expr *> PrivateCounters) {
1005 auto I = PrivateCounters.begin();
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001006 for (auto *E : Counters) {
Alexey Bataeva8899172015-08-06 12:30:57 +00001007 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1008 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001009 Address Addr = Address::invalid();
1010 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001011 // Emit var without initialization.
Alexey Bataeva8899172015-08-06 12:30:57 +00001012 auto VarEmission = CGF.EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001013 CGF.EmitAutoVarCleanups(VarEmission);
Alexey Bataeva8899172015-08-06 12:30:57 +00001014 Addr = VarEmission.getAllocatedAddress();
1015 return Addr;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001016 });
John McCall7f416cc2015-09-08 08:05:57 +00001017 (void)LoopScope.addPrivate(VD, [&]() -> Address { return Addr; });
Alexey Bataeva8899172015-08-06 12:30:57 +00001018 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001019 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +00001020}
1021
Alexey Bataev62dbb972015-04-22 11:59:37 +00001022static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1023 const Expr *Cond, llvm::BasicBlock *TrueBlock,
1024 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001025 {
1026 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001027 emitPrivateLoopCounters(CGF, PreCondScope, S.counters(),
1028 S.private_counters());
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001029 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001030 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00001031 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +00001032 CGF.EmitIgnoredExpr(I);
1033 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00001034 }
1035 // Check that loop is executed at least one time.
1036 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1037}
1038
Alexander Musman3276a272015-03-21 10:12:56 +00001039static void
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001040emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexander Musman3276a272015-03-21 10:12:56 +00001041 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001042 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001043 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +00001044 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001045 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1046 auto *PrivateVD =
1047 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001048 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001049 // Emit private VarDecl with copy init.
1050 CGF.EmitVarDecl(*PrivateVD);
1051 return CGF.GetAddrOfLocalVar(PrivateVD);
Alexander Musman3276a272015-03-21 10:12:56 +00001052 });
1053 assert(IsRegistered && "linear var already registered as private");
1054 // Silence the warning about unused variable.
1055 (void)IsRegistered;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00001056 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00001057 }
1058 }
1059}
1060
Alexey Bataev45bfad52015-08-21 12:19:04 +00001061static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
1062 const OMPExecutableDirective &D) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001063 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +00001064 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1065 /*ignoreResult=*/true);
1066 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1067 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1068 // In presence of finite 'safelen', it may be unsafe to mark all
1069 // the memory instructions parallel, because loop-carried
1070 // dependences of 'safelen' iterations are possible.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001071 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
1072 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001073 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1074 /*ignoreResult=*/true);
1075 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001076 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001077 // In presence of finite 'safelen', it may be unsafe to mark all
1078 // the memory instructions parallel, because loop-carried
1079 // dependences of 'safelen' iterations are possible.
1080 CGF.LoopStack.setParallel(false);
1081 }
1082}
1083
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001084void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D) {
1085 // Walk clauses and process safelen/lastprivate.
1086 LoopStack.setParallel();
Tyler Nowickida46d0e2015-07-14 23:03:09 +00001087 LoopStack.setVectorizeEnable(true);
Alexey Bataev45bfad52015-08-21 12:19:04 +00001088 emitSimdlenSafelenClause(*this, D);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001089}
1090
1091void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &D) {
1092 auto IC = D.counters().begin();
1093 for (auto F : D.finals()) {
1094 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001095 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001096 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1097 CapturedStmtInfo->lookup(OrigVD) != nullptr,
1098 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001099 Address OrigAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001100 OMPPrivateScope VarScope(*this);
1101 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +00001102 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001103 (void)VarScope.Privatize();
1104 EmitIgnoredExpr(F);
1105 }
1106 ++IC;
1107 }
1108 emitLinearClauseFinal(*this, D);
1109}
1110
Alexander Musman515ad8c2014-05-22 08:54:05 +00001111void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001112 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001113 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001114 // for (IV in 0..LastIteration) BODY;
1115 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001116 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001117 //
Alexander Musmana5f070a2014-10-01 06:03:56 +00001118
Alexey Bataev62dbb972015-04-22 11:59:37 +00001119 // Emit: if (PreCond) - begin.
1120 // If the condition constant folds and can be elided, avoid emitting the
1121 // whole loop.
1122 bool CondConstant;
1123 llvm::BasicBlock *ContBlock = nullptr;
1124 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1125 if (!CondConstant)
1126 return;
1127 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001128 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1129 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +00001130 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1131 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001132 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001133 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001134 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001135
1136 // Emit the loop iteration variable.
1137 const Expr *IVExpr = S.getIterationVariable();
1138 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1139 CGF.EmitVarDecl(*IVDecl);
1140 CGF.EmitIgnoredExpr(S.getInit());
1141
1142 // Emit the iterations count variable.
1143 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +00001144 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001145 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1146 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1147 // Emit calculation of the iterations count.
1148 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +00001149 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001150
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001151 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001152
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001153 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001154 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001155 bool HasLastprivateClause;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001156 {
1157 OMPPrivateScope LoopScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +00001158 emitPrivateLoopCounters(CGF, LoopScope, S.counters(),
1159 S.private_counters());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001160 emitPrivateLinearVars(CGF, S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001161 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001162 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001163 HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001164 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001165 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1166 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +00001167 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001168 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +00001169 CGF.EmitStopPoint(&S);
1170 },
1171 [](CodeGenFunction &) {});
Alexey Bataevfc087ec2015-06-16 13:14:42 +00001172 // Emit final copy of the lastprivate variables at the end of loops.
1173 if (HasLastprivateClause) {
1174 CGF.EmitOMPLastprivateClauseFinal(S);
1175 }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00001176 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001177 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001178 CGF.EmitOMPSimdFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001179 // Emit: if (PreCond) - end.
1180 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001181 CGF.EmitBranch(ContBlock);
1182 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001183 }
1184 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001185 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001186}
1187
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001188void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
1189 const OMPLoopDirective &S,
1190 OMPPrivateScope &LoopScope,
John McCall7f416cc2015-09-08 08:05:57 +00001191 bool Ordered, Address LB,
1192 Address UB, Address ST,
1193 Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001194 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +00001195
1196 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001197 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001198
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001199 assert((Ordered ||
1200 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001201 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001202
1203 // Emit outer loop.
1204 //
1205 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +00001206 // When schedule(dynamic,chunk_size) is specified, the iterations are
1207 // distributed to threads in the team in chunks as the threads request them.
1208 // Each thread executes a chunk of iterations, then requests another chunk,
1209 // until no chunks remain to be distributed. Each chunk contains chunk_size
1210 // iterations, except for the last chunk to be distributed, which may have
1211 // fewer iterations. When no chunk_size is specified, it defaults to 1.
1212 //
1213 // When schedule(guided,chunk_size) is specified, the iterations are assigned
1214 // to threads in the team in chunks as the executing threads request them.
1215 // Each thread executes a chunk of iterations, then requests another chunk,
1216 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1217 // each chunk is proportional to the number of unassigned iterations divided
1218 // by the number of threads in the team, decreasing to 1. For a chunk_size
1219 // with value k (greater than 1), the size of each chunk is determined in the
1220 // same way, with the restriction that the chunks do not contain fewer than k
1221 // iterations (except for the last chunk to be assigned, which may have fewer
1222 // than k iterations).
1223 //
1224 // When schedule(auto) is specified, the decision regarding scheduling is
1225 // delegated to the compiler and/or runtime system. The programmer gives the
1226 // implementation the freedom to choose any possible mapping of iterations to
1227 // threads in the team.
1228 //
1229 // When schedule(runtime) is specified, the decision regarding scheduling is
1230 // deferred until run time, and the schedule and chunk size are taken from the
1231 // run-sched-var ICV. If the ICV is set to auto, the schedule is
1232 // implementation defined
1233 //
1234 // while(__kmpc_dispatch_next(&LB, &UB)) {
1235 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001236 // while (idx <= UB) { BODY; ++idx;
1237 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1238 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +00001239 // }
1240 //
1241 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001242 // When schedule(static, chunk_size) is specified, iterations are divided into
1243 // chunks of size chunk_size, and the chunks are assigned to the threads in
1244 // the team in a round-robin fashion in the order of the thread number.
1245 //
1246 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1247 // while (idx <= UB) { BODY; ++idx; } // inner loop
1248 // LB = LB + ST;
1249 // UB = UB + ST;
1250 // }
1251 //
Alexander Musman92bdaab2015-03-12 13:37:50 +00001252
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001253 const Expr *IVExpr = S.getIterationVariable();
1254 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1255 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1256
John McCall7f416cc2015-09-08 08:05:57 +00001257 if (DynamicOrOrdered) {
1258 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
1259 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind,
1260 IVSize, IVSigned, Ordered, UBVal, Chunk);
1261 } else {
1262 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1263 IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
1264 }
Alexander Musman92bdaab2015-03-12 13:37:50 +00001265
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001266 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1267
1268 // Start the loop with a block that tests the condition.
1269 auto CondBlock = createBasicBlock("omp.dispatch.cond");
1270 EmitBlock(CondBlock);
1271 LoopStack.push(CondBlock);
1272
1273 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001274 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001275 // UB = min(UB, GlobalUB)
1276 EmitIgnoredExpr(S.getEnsureUpperBound());
1277 // IV = LB
1278 EmitIgnoredExpr(S.getInit());
1279 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +00001280 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +00001281 } else {
1282 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
1283 IL, LB, UB, ST);
1284 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001285
1286 // If there are any cleanups between here and the loop-exit scope,
1287 // create a block to stage a loop exit along.
1288 auto ExitBlock = LoopExit.getBlock();
1289 if (LoopScope.requiresCleanups())
1290 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1291
1292 auto LoopBody = createBasicBlock("omp.dispatch.body");
1293 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1294 if (ExitBlock != LoopExit.getBlock()) {
1295 EmitBlock(ExitBlock);
1296 EmitBranchThroughCleanup(LoopExit);
1297 }
1298 EmitBlock(LoopBody);
1299
Alexander Musman92bdaab2015-03-12 13:37:50 +00001300 // Emit "IV = LB" (in case of static schedule, we have already calculated new
1301 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001302 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +00001303 EmitIgnoredExpr(S.getInit());
1304
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001305 // Create a block for the increment.
1306 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1307 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1308
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001309 // Generate !llvm.loop.parallel metadata for loads and stores for loops
1310 // with dynamic/guided scheduling and without ordered clause.
1311 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
1312 LoopStack.setParallel((ScheduleKind == OMPC_SCHEDULE_dynamic ||
1313 ScheduleKind == OMPC_SCHEDULE_guided) &&
1314 !Ordered);
1315 } else {
1316 EmitOMPSimdInit(S);
1317 }
1318
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001319 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001320 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1321 [&S, LoopExit](CodeGenFunction &CGF) {
1322 CGF.EmitOMPLoopBody(S, LoopExit);
1323 CGF.EmitStopPoint(&S);
1324 },
1325 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1326 if (Ordered) {
1327 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1328 CGF, Loc, IVSize, IVSigned);
1329 }
1330 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001331
1332 EmitBlock(Continue.getBlock());
1333 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001334 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001335 // Emit "LB = LB + Stride", "UB = UB + Stride".
1336 EmitIgnoredExpr(S.getNextLowerBound());
1337 EmitIgnoredExpr(S.getNextUpperBound());
1338 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001339
1340 EmitBranch(CondBlock);
1341 LoopStack.pop();
1342 // Emit the fall-through block.
1343 EmitBlock(LoopExit.getBlock());
1344
1345 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001346 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001347 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001348}
1349
Alexander Musmanc6388682014-12-15 07:07:06 +00001350/// \brief Emit a helper variable and return corresponding lvalue.
1351static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1352 const DeclRefExpr *Helper) {
1353 auto VDecl = cast<VarDecl>(Helper->getDecl());
1354 CGF.EmitVarDecl(*VDecl);
1355 return CGF.EmitLValue(Helper);
1356}
1357
Alexey Bataev040d5402015-05-12 08:35:28 +00001358static std::pair<llvm::Value * /*Chunk*/, OpenMPScheduleClauseKind>
1359emitScheduleClause(CodeGenFunction &CGF, const OMPLoopDirective &S,
1360 bool OuterRegion) {
1361 // Detect the loop schedule kind and chunk.
1362 auto ScheduleKind = OMPC_SCHEDULE_unknown;
1363 llvm::Value *Chunk = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001364 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001365 ScheduleKind = C->getScheduleKind();
1366 if (const auto *Ch = C->getChunkSize()) {
1367 if (auto *ImpRef = cast_or_null<DeclRefExpr>(C->getHelperChunkSize())) {
1368 if (OuterRegion) {
1369 const VarDecl *ImpVar = cast<VarDecl>(ImpRef->getDecl());
1370 CGF.EmitVarDecl(*ImpVar);
1371 CGF.EmitStoreThroughLValue(
1372 CGF.EmitAnyExpr(Ch),
John McCall7f416cc2015-09-08 08:05:57 +00001373 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(ImpVar),
1374 ImpVar->getType()));
Alexey Bataev040d5402015-05-12 08:35:28 +00001375 } else {
1376 Ch = ImpRef;
1377 }
1378 }
1379 if (!C->getHelperChunkSize() || !OuterRegion) {
1380 Chunk = CGF.EmitScalarExpr(Ch);
1381 Chunk = CGF.EmitScalarConversion(Chunk, Ch->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001382 S.getIterationVariable()->getType(),
1383 S.getLocStart());
Alexey Bataev040d5402015-05-12 08:35:28 +00001384 }
1385 }
1386 }
1387 return std::make_pair(Chunk, ScheduleKind);
1388}
1389
Alexey Bataev38e89532015-04-16 04:54:05 +00001390bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001391 // Emit the loop iteration variable.
1392 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1393 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1394 EmitVarDecl(*IVDecl);
1395
1396 // Emit the iterations count variable.
1397 // If it is not a variable, Sema decided to calculate iterations count on each
1398 // iteration (e.g., it is foldable into a constant).
1399 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1400 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1401 // Emit calculation of the iterations count.
1402 EmitIgnoredExpr(S.getCalcLastIteration());
1403 }
1404
1405 auto &RT = CGM.getOpenMPRuntime();
1406
Alexey Bataev38e89532015-04-16 04:54:05 +00001407 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001408 // Check pre-condition.
1409 {
1410 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001411 // If the condition constant folds and can be elided, avoid emitting the
1412 // whole loop.
1413 bool CondConstant;
1414 llvm::BasicBlock *ContBlock = nullptr;
1415 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1416 if (!CondConstant)
1417 return false;
1418 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001419 auto *ThenBlock = createBasicBlock("omp.precond.then");
1420 ContBlock = createBasicBlock("omp.precond.end");
1421 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001422 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001423 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001424 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001425 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001426
1427 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001428 EmitOMPLinearClauseInit(S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001429 // Emit 'then' code.
1430 {
1431 // Emit helper vars inits.
1432 LValue LB =
1433 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1434 LValue UB =
1435 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1436 LValue ST =
1437 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1438 LValue IL =
1439 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1440
1441 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001442 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1443 // Emit implicit barrier to synchronize threads and avoid data races on
1444 // initialization of firstprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001445 CGM.getOpenMPRuntime().emitBarrierCall(
1446 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1447 /*ForceSimpleCall=*/true);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001448 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001449 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001450 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001451 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataeva8899172015-08-06 12:30:57 +00001452 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
1453 S.private_counters());
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001454 emitPrivateLinearVars(*this, S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001455 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001456
1457 // Detect the loop schedule kind and chunk.
Alexey Bataev040d5402015-05-12 08:35:28 +00001458 llvm::Value *Chunk;
1459 OpenMPScheduleClauseKind ScheduleKind;
1460 auto ScheduleInfo =
1461 emitScheduleClause(*this, S, /*OuterRegion=*/false);
1462 Chunk = ScheduleInfo.first;
1463 ScheduleKind = ScheduleInfo.second;
Alexander Musmanc6388682014-12-15 07:07:06 +00001464 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1465 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001466 const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
Alexander Musmanc6388682014-12-15 07:07:06 +00001467 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001468 /* Chunked */ Chunk != nullptr) &&
1469 !Ordered) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001470 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1471 EmitOMPSimdInit(S);
1472 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001473 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1474 // When no chunk_size is specified, the iteration space is divided into
1475 // chunks that are approximately equal in size, and at most one chunk is
1476 // distributed to each thread. Note that the size of the chunks is
1477 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00001478 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1479 IVSize, IVSigned, Ordered,
1480 IL.getAddress(), LB.getAddress(),
1481 UB.getAddress(), ST.getAddress());
Alexey Bataev0f34da12015-07-02 04:17:07 +00001482 auto LoopExit = getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00001483 // UB = min(UB, GlobalUB);
1484 EmitIgnoredExpr(S.getEnsureUpperBound());
1485 // IV = LB;
1486 EmitIgnoredExpr(S.getInit());
1487 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001488 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1489 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00001490 [&S, LoopExit](CodeGenFunction &CGF) {
1491 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001492 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001493 },
1494 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00001495 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00001496 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001497 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001498 } else {
1499 // Emit the outer loop, which requests its work chunk [LB..UB] from
1500 // runtime and runs the inner loop to process it.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001501 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, Ordered,
1502 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1503 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001504 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001505 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001506 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1507 if (HasLastprivateClause)
1508 EmitOMPLastprivateClauseFinal(
1509 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001510 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001511 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1512 EmitOMPSimdFinal(S);
1513 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001514 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001515 if (ContBlock) {
1516 EmitBranch(ContBlock);
1517 EmitBlock(ContBlock, true);
1518 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001519 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001520 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001521}
1522
1523void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001524 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev38e89532015-04-16 04:54:05 +00001525 bool HasLastprivates = false;
1526 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1527 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1528 };
Alexey Bataev25e5b442015-09-15 12:52:43 +00001529 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
1530 S.hasCancel());
Alexander Musmanc6388682014-12-15 07:07:06 +00001531
1532 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001533 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001534 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1535 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001536}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001537
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001538void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
1539 LexicalScope Scope(*this, S.getSourceRange());
1540 bool HasLastprivates = false;
1541 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1542 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1543 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001544 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001545
1546 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001547 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001548 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1549 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001550}
1551
Alexey Bataev2df54a02015-03-12 08:53:29 +00001552static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1553 const Twine &Name,
1554 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00001555 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001556 if (Init)
1557 CGF.EmitScalarInit(Init, LVal);
1558 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001559}
1560
Alexey Bataev0f34da12015-07-02 04:17:07 +00001561OpenMPDirectiveKind
1562CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001563 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1564 auto *CS = dyn_cast<CompoundStmt>(Stmt);
1565 if (CS && CS->size() > 1) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001566 bool HasLastprivates = false;
1567 auto &&CodeGen = [&S, CS, &HasLastprivates](CodeGenFunction &CGF) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001568 auto &C = CGF.CGM.getContext();
1569 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1570 // Emit helper vars inits.
1571 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1572 CGF.Builder.getInt32(0));
1573 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
1574 LValue UB =
1575 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1576 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1577 CGF.Builder.getInt32(1));
1578 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1579 CGF.Builder.getInt32(0));
1580 // Loop counter.
1581 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1582 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001583 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001584 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001585 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001586 // Generate condition for loop.
1587 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1588 OK_Ordinary, S.getLocStart(),
1589 /*fpContractable=*/false);
1590 // Increment for loop counter.
1591 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
1592 OK_Ordinary, S.getLocStart());
1593 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
1594 // Iterate through all sections and emit a switch construct:
1595 // switch (IV) {
1596 // case 0:
1597 // <SectionStmt[0]>;
1598 // break;
1599 // ...
1600 // case <NumSection> - 1:
1601 // <SectionStmt[<NumSection> - 1]>;
1602 // break;
1603 // }
1604 // .omp.sections.exit:
1605 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1606 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1607 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1608 CS->size());
1609 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00001610 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001611 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1612 CGF.EmitBlock(CaseBB);
1613 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001614 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001615 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001616 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001617 }
1618 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1619 };
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001620
1621 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1622 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
1623 // Emit implicit barrier to synchronize threads and avoid data races on
1624 // initialization of firstprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001625 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1626 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1627 /*ForceSimpleCall=*/true);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001628 }
Alexey Bataev73870832015-04-27 04:12:12 +00001629 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001630 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001631 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001632 (void)LoopScope.Privatize();
1633
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001634 // Emit static non-chunked loop.
John McCall7f416cc2015-09-08 08:05:57 +00001635 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001636 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001637 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
1638 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001639 // UB = min(UB, GlobalUB);
1640 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1641 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1642 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1643 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1644 // IV = LB;
1645 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1646 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001647 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1648 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001649 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001650 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataeva89adf22015-04-27 05:04:13 +00001651 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001652
1653 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1654 if (HasLastprivates)
1655 CGF.EmitOMPLastprivateClauseFinal(
1656 S, CGF.Builder.CreateIsNotNull(
1657 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev2df54a02015-03-12 08:53:29 +00001658 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001659
Alexey Bataev25e5b442015-09-15 12:52:43 +00001660 bool HasCancel = false;
1661 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
1662 HasCancel = OSD->hasCancel();
1663 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
1664 HasCancel = OPSD->hasCancel();
1665 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
1666 HasCancel);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001667 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1668 // clause. Otherwise the barrier will be generated by the codegen for the
1669 // directive.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001670 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001671 // Emit implicit barrier to synchronize threads and avoid data races on
1672 // initialization of firstprivate variables.
Alexey Bataev0f34da12015-07-02 04:17:07 +00001673 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1674 OMPD_unknown);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001675 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001676 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001677 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001678 // If only one section is found - no need to generate loop, emit as a single
1679 // region.
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001680 bool HasFirstprivates;
Alexey Bataeva89adf22015-04-27 05:04:13 +00001681 // No need to generate reductions for sections with single section region, we
1682 // can use original shared variables for all operations.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001683 bool HasReductions = S.hasClausesOfKind<OMPReductionClause>();
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001684 // No need to generate lastprivates for sections with single section region,
1685 // we can use original shared variable for all calculations with barrier at
1686 // the end of the sections.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001687 bool HasLastprivates = S.hasClausesOfKind<OMPLastprivateClause>();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001688 auto &&CodeGen = [Stmt, &S, &HasFirstprivates](CodeGenFunction &CGF) {
1689 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1690 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev73870832015-04-27 04:12:12 +00001691 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001692 (void)SingleScope.Privatize();
1693
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001694 CGF.EmitStmt(Stmt);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001695 };
Alexey Bataev0f34da12015-07-02 04:17:07 +00001696 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
1697 llvm::None, llvm::None, llvm::None,
1698 llvm::None);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001699 // Emit barrier for firstprivates, lastprivates or reductions only if
1700 // 'sections' directive has 'nowait' clause. Otherwise the barrier will be
1701 // generated by the codegen for the directive.
1702 if ((HasFirstprivates || HasLastprivates || HasReductions) &&
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001703 S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001704 // Emit implicit barrier to synchronize threads and avoid data races on
1705 // initialization of firstprivate variables.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001706 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_unknown,
1707 /*EmitChecks=*/false,
1708 /*ForceSimpleCall=*/true);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001709 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001710 return OMPD_single;
1711}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001712
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001713void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1714 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev0f34da12015-07-02 04:17:07 +00001715 OpenMPDirectiveKind EmittedAs = EmitSections(S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001716 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001717 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001718 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001719 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001720}
1721
1722void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001723 LexicalScope Scope(*this, S.getSourceRange());
1724 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1725 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1726 CGF.EnsureInsertPoint();
1727 };
Alexey Bataev25e5b442015-09-15 12:52:43 +00001728 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
1729 S.hasCancel());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001730}
1731
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001732void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001733 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001734 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001735 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001736 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001737 // Check if there are any 'copyprivate' clauses associated with this
1738 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001739 // construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001740 // Build a list of copyprivate variables along with helper expressions
1741 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001742 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001743 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001744 DestExprs.append(C->destination_exprs().begin(),
1745 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001746 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001747 AssignmentOps.append(C->assignment_ops().begin(),
1748 C->assignment_ops().end());
1749 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001750 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001751 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev5521d782015-04-24 04:21:15 +00001752 bool HasFirstprivates;
1753 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) {
1754 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1755 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev59c654a2015-04-27 03:48:52 +00001756 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev5521d782015-04-24 04:21:15 +00001757 (void)SingleScope.Privatize();
1758
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001759 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1760 CGF.EnsureInsertPoint();
1761 };
1762 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001763 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001764 AssignmentOps);
Alexey Bataev5521d782015-04-24 04:21:15 +00001765 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1766 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001767 if ((!S.getSingleClause<OMPNowaitClause>() || HasFirstprivates) &&
Alexey Bataev5521d782015-04-24 04:21:15 +00001768 CopyprivateVars.empty()) {
1769 CGM.getOpenMPRuntime().emitBarrierCall(
1770 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001771 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001772 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001773}
1774
Alexey Bataev8d690652014-12-04 07:23:53 +00001775void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001776 LexicalScope Scope(*this, S.getSourceRange());
1777 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1778 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1779 CGF.EnsureInsertPoint();
1780 };
1781 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001782}
1783
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001784void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001785 LexicalScope Scope(*this, S.getSourceRange());
1786 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1787 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1788 CGF.EnsureInsertPoint();
1789 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001790 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001791 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001792}
1793
Alexey Bataev671605e2015-04-13 05:28:11 +00001794void CodeGenFunction::EmitOMPParallelForDirective(
1795 const OMPParallelForDirective &S) {
1796 // Emit directive as a combined directive that consists of two implicit
1797 // directives: 'parallel' with 'for' directive.
1798 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev040d5402015-05-12 08:35:28 +00001799 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
Alexey Bataev671605e2015-04-13 05:28:11 +00001800 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1801 CGF.EmitOMPWorksharingLoop(S);
1802 // Emit implicit barrier at the end of parallel region, but this barrier
1803 // is at the end of 'for' directive, so emit it as the implicit barrier for
1804 // this 'for' directive.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001805 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1806 CGF, S.getLocStart(), OMPD_parallel, /*EmitChecks=*/false,
1807 /*ForceSimpleCall=*/true);
Alexey Bataev671605e2015-04-13 05:28:11 +00001808 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001809 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001810}
1811
Alexander Musmane4e893b2014-09-23 09:33:00 +00001812void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001813 const OMPParallelForSimdDirective &S) {
1814 // Emit directive as a combined directive that consists of two implicit
1815 // directives: 'parallel' with 'for' directive.
1816 LexicalScope Scope(*this, S.getSourceRange());
1817 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
1818 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1819 CGF.EmitOMPWorksharingLoop(S);
1820 // Emit implicit barrier at the end of parallel region, but this barrier
1821 // is at the end of 'for' directive, so emit it as the implicit barrier for
1822 // this 'for' directive.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001823 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1824 CGF, S.getLocStart(), OMPD_parallel, /*EmitChecks=*/false,
1825 /*ForceSimpleCall=*/true);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001826 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001827 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001828}
1829
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001830void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001831 const OMPParallelSectionsDirective &S) {
1832 // Emit directive as a combined directive that consists of two implicit
1833 // directives: 'parallel' with 'sections' directive.
1834 LexicalScope Scope(*this, S.getSourceRange());
1835 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001836 (void)CGF.EmitSections(S);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001837 // Emit implicit barrier at the end of parallel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +00001838 CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1839 CGF, S.getLocStart(), OMPD_parallel, /*EmitChecks=*/false,
1840 /*ForceSimpleCall=*/true);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001841 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001842 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001843}
1844
Alexey Bataev62b63b12015-03-10 07:28:44 +00001845void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1846 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001847 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001848 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1849 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1850 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001851 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001852 // The first function argument for tasks is a thread id, the second one is a
1853 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001854 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
1855 // Get list of private variables.
1856 llvm::SmallVector<const Expr *, 8> PrivateVars;
1857 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001858 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001859 auto IRef = C->varlist_begin();
1860 for (auto *IInit : C->private_copies()) {
1861 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1862 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1863 PrivateVars.push_back(*IRef);
1864 PrivateCopies.push_back(IInit);
1865 }
1866 ++IRef;
1867 }
1868 }
1869 EmittedAsPrivate.clear();
1870 // Get list of firstprivate variables.
1871 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
1872 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
1873 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001874 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001875 auto IRef = C->varlist_begin();
1876 auto IElemInitRef = C->inits().begin();
1877 for (auto *IInit : C->private_copies()) {
1878 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1879 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1880 FirstprivateVars.push_back(*IRef);
1881 FirstprivateCopies.push_back(IInit);
1882 FirstprivateInits.push_back(*IElemInitRef);
1883 }
1884 ++IRef, ++IElemInitRef;
1885 }
1886 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001887 // Build list of dependences.
1888 llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8>
1889 Dependences;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001890 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001891 for (auto *IRef : C->varlists()) {
1892 Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
1893 }
1894 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001895 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
1896 CodeGenFunction &CGF) {
1897 // Set proper addresses for generated private copies.
1898 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
1899 OMPPrivateScope Scope(CGF);
1900 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00001901 auto *CopyFn = CGF.Builder.CreateLoad(
1902 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
1903 auto *PrivatesPtr = CGF.Builder.CreateLoad(
1904 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001905 // Map privates.
John McCall7f416cc2015-09-08 08:05:57 +00001906 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16>
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001907 PrivatePtrs;
1908 llvm::SmallVector<llvm::Value *, 16> CallArgs;
1909 CallArgs.push_back(PrivatesPtr);
1910 for (auto *E : PrivateVars) {
1911 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001912 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001913 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
1914 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00001915 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001916 }
1917 for (auto *E : FirstprivateVars) {
1918 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001919 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001920 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
1921 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00001922 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001923 }
1924 CGF.EmitRuntimeCall(CopyFn, CallArgs);
1925 for (auto &&Pair : PrivatePtrs) {
John McCall7f416cc2015-09-08 08:05:57 +00001926 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
1927 CGF.getContext().getDeclAlign(Pair.first));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001928 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
1929 }
1930 }
1931 (void)Scope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001932 if (*PartId) {
1933 // TODO: emit code for untied tasks.
1934 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001935 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001936 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001937 auto OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
1938 S, *I, OMPD_task, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001939 // Check if we should emit tied or untied task.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001940 bool Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev62b63b12015-03-10 07:28:44 +00001941 // Check if the task is final
1942 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001943 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001944 // If the condition constant folds and can be elided, try to avoid emitting
1945 // the condition and the dead arm of the if/else.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001946 auto *Cond = Clause->getCondition();
Alexey Bataev62b63b12015-03-10 07:28:44 +00001947 bool CondConstant;
1948 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1949 Final.setInt(CondConstant);
1950 else
1951 Final.setPointer(EvaluateExprAsBool(Cond));
1952 } else {
1953 // By default the task is not final.
1954 Final.setInt(/*IntVal=*/false);
1955 }
1956 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00001957 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001958 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1959 if (C->getNameModifier() == OMPD_unknown ||
1960 C->getNameModifier() == OMPD_task) {
1961 IfCond = C->getCondition();
1962 break;
1963 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001964 }
Alexey Bataev9e034042015-05-05 04:05:12 +00001965 CGM.getOpenMPRuntime().emitTaskCall(
1966 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001967 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001968 FirstprivateCopies, FirstprivateInits, Dependences);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001969}
1970
Alexey Bataev9f797f32015-02-05 05:57:51 +00001971void CodeGenFunction::EmitOMPTaskyieldDirective(
1972 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001973 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001974}
1975
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001976void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001977 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001978}
1979
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001980void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
1981 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00001982}
1983
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001984void CodeGenFunction::EmitOMPTaskgroupDirective(
1985 const OMPTaskgroupDirective &S) {
1986 LexicalScope Scope(*this, S.getSourceRange());
1987 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1988 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1989 CGF.EnsureInsertPoint();
1990 };
1991 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
1992}
1993
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001994void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001995 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001996 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001997 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1998 FlushClause->varlist_end());
1999 }
2000 return llvm::None;
2001 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00002002}
2003
Alexey Bataev5f600d62015-09-29 03:48:57 +00002004static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2005 const CapturedStmt *S) {
2006 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2007 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2008 CGF.CapturedStmtInfo = &CapStmtInfo;
2009 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2010 Fn->addFnAttr(llvm::Attribute::NoInline);
2011 return Fn;
2012}
2013
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002014void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
2015 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev5f600d62015-09-29 03:48:57 +00002016 auto *C = S.getSingleClause<OMPSIMDClause>();
2017 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF) {
2018 if (C) {
2019 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2020 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2021 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2022 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2023 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2024 } else {
2025 CGF.EmitStmt(
2026 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2027 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002028 CGF.EnsureInsertPoint();
2029 };
Alexey Bataev5f600d62015-09-29 03:48:57 +00002030 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002031}
2032
Alexey Bataevb57056f2015-01-22 06:17:56 +00002033static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002034 QualType SrcType, QualType DestType,
2035 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002036 assert(CGF.hasScalarEvaluationKind(DestType) &&
2037 "DestType must have scalar evaluation kind.");
2038 assert(!Val.isAggregate() && "Must be a scalar or complex.");
2039 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002040 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2041 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00002042 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002043 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002044}
2045
2046static CodeGenFunction::ComplexPairTy
2047convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002048 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002049 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2050 "DestType must have complex evaluation kind.");
2051 CodeGenFunction::ComplexPairTy ComplexVal;
2052 if (Val.isScalar()) {
2053 // Convert the input element to the element type of the complex.
2054 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002055 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2056 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002057 ComplexVal = CodeGenFunction::ComplexPairTy(
2058 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2059 } else {
2060 assert(Val.isComplex() && "Must be a scalar or complex.");
2061 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2062 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2063 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002064 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002065 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002066 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002067 }
2068 return ComplexVal;
2069}
2070
Alexey Bataev5e018f92015-04-23 06:35:10 +00002071static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
2072 LValue LVal, RValue RVal) {
2073 if (LVal.isGlobalReg()) {
2074 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
2075 } else {
2076 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
2077 : llvm::Monotonic,
2078 LVal.isVolatile(), /*IsInit=*/false);
2079 }
2080}
2081
2082static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002083 QualType RValTy, SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002084 switch (CGF.getEvaluationKind(LVal.getType())) {
2085 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002086 CGF.EmitStoreThroughLValue(RValue::get(convertToScalarValue(
2087 CGF, RVal, RValTy, LVal.getType(), Loc)),
2088 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002089 break;
2090 case TEK_Complex:
2091 CGF.EmitStoreOfComplex(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002092 convertToComplexValue(CGF, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002093 /*isInit=*/false);
2094 break;
2095 case TEK_Aggregate:
2096 llvm_unreachable("Must be a scalar or complex.");
2097 }
2098}
2099
Alexey Bataevb57056f2015-01-22 06:17:56 +00002100static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
2101 const Expr *X, const Expr *V,
2102 SourceLocation Loc) {
2103 // v = x;
2104 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
2105 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
2106 LValue XLValue = CGF.EmitLValue(X);
2107 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00002108 RValue Res = XLValue.isGlobalReg()
2109 ? CGF.EmitLoadOfLValue(XLValue, Loc)
2110 : CGF.EmitAtomicLoad(XLValue, Loc,
2111 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00002112 : llvm::Monotonic,
2113 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00002114 // OpenMP, 2.12.6, atomic Construct
2115 // Any atomic construct with a seq_cst clause forces the atomically
2116 // performed operation to include an implicit flush operation without a
2117 // list.
2118 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002119 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002120 emitSimpleStore(CGF, VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002121}
2122
Alexey Bataevb8329262015-02-27 06:33:30 +00002123static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
2124 const Expr *X, const Expr *E,
2125 SourceLocation Loc) {
2126 // x = expr;
2127 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00002128 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00002129 // OpenMP, 2.12.6, atomic Construct
2130 // Any atomic construct with a seq_cst clause forces the atomically
2131 // performed operation to include an implicit flush operation without a
2132 // list.
2133 if (IsSeqCst)
2134 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2135}
2136
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00002137static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
2138 RValue Update,
2139 BinaryOperatorKind BO,
2140 llvm::AtomicOrdering AO,
2141 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002142 auto &Context = CGF.CGM.getContext();
2143 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00002144 // expression is simple and atomic is allowed for the given type for the
2145 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002146 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00002147 !Update.getScalarVal()->getType()->isIntegerTy() ||
2148 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
2149 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00002150 X.getAddress().getElementType())) ||
2151 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002152 !Context.getTargetInfo().hasBuiltinAtomic(
2153 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00002154 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002155
2156 llvm::AtomicRMWInst::BinOp RMWOp;
2157 switch (BO) {
2158 case BO_Add:
2159 RMWOp = llvm::AtomicRMWInst::Add;
2160 break;
2161 case BO_Sub:
2162 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00002163 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002164 RMWOp = llvm::AtomicRMWInst::Sub;
2165 break;
2166 case BO_And:
2167 RMWOp = llvm::AtomicRMWInst::And;
2168 break;
2169 case BO_Or:
2170 RMWOp = llvm::AtomicRMWInst::Or;
2171 break;
2172 case BO_Xor:
2173 RMWOp = llvm::AtomicRMWInst::Xor;
2174 break;
2175 case BO_LT:
2176 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2177 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
2178 : llvm::AtomicRMWInst::Max)
2179 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
2180 : llvm::AtomicRMWInst::UMax);
2181 break;
2182 case BO_GT:
2183 RMWOp = X.getType()->hasSignedIntegerRepresentation()
2184 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
2185 : llvm::AtomicRMWInst::Min)
2186 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
2187 : llvm::AtomicRMWInst::UMin);
2188 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002189 case BO_Assign:
2190 RMWOp = llvm::AtomicRMWInst::Xchg;
2191 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002192 case BO_Mul:
2193 case BO_Div:
2194 case BO_Rem:
2195 case BO_Shl:
2196 case BO_Shr:
2197 case BO_LAnd:
2198 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002199 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002200 case BO_PtrMemD:
2201 case BO_PtrMemI:
2202 case BO_LE:
2203 case BO_GE:
2204 case BO_EQ:
2205 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002206 case BO_AddAssign:
2207 case BO_SubAssign:
2208 case BO_AndAssign:
2209 case BO_OrAssign:
2210 case BO_XorAssign:
2211 case BO_MulAssign:
2212 case BO_DivAssign:
2213 case BO_RemAssign:
2214 case BO_ShlAssign:
2215 case BO_ShrAssign:
2216 case BO_Comma:
2217 llvm_unreachable("Unsupported atomic update operation");
2218 }
2219 auto *UpdateVal = Update.getScalarVal();
2220 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
2221 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00002222 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002223 X.getType()->hasSignedIntegerRepresentation());
2224 }
John McCall7f416cc2015-09-08 08:05:57 +00002225 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002226 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002227}
2228
Alexey Bataev5e018f92015-04-23 06:35:10 +00002229std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002230 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2231 llvm::AtomicOrdering AO, SourceLocation Loc,
2232 const llvm::function_ref<RValue(RValue)> &CommonGen) {
2233 // Update expressions are allowed to have the following forms:
2234 // x binop= expr; -> xrval + expr;
2235 // x++, ++x -> xrval + 1;
2236 // x--, --x -> xrval - 1;
2237 // x = x binop expr; -> xrval binop expr
2238 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00002239 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
2240 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002241 if (X.isGlobalReg()) {
2242 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
2243 // 'xrval'.
2244 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
2245 } else {
2246 // Perform compare-and-swap procedure.
2247 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00002248 }
2249 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00002250 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002251}
2252
2253static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
2254 const Expr *X, const Expr *E,
2255 const Expr *UE, bool IsXLHSInRHSPart,
2256 SourceLocation Loc) {
2257 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2258 "Update expr in 'atomic update' must be a binary operator.");
2259 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2260 // Update expressions are allowed to have the following forms:
2261 // x binop= expr; -> xrval + expr;
2262 // x++, ++x -> xrval + 1;
2263 // x--, --x -> xrval - 1;
2264 // x = x binop expr; -> xrval binop expr
2265 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002266 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00002267 LValue XLValue = CGF.EmitLValue(X);
2268 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002269 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002270 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2271 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2272 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2273 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2274 auto Gen =
2275 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
2276 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2277 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2278 return CGF.EmitAnyExpr(UE);
2279 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00002280 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
2281 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2282 // OpenMP, 2.12.6, atomic Construct
2283 // Any atomic construct with a seq_cst clause forces the atomically
2284 // performed operation to include an implicit flush operation without a
2285 // list.
2286 if (IsSeqCst)
2287 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2288}
2289
2290static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002291 QualType SourceType, QualType ResType,
2292 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002293 switch (CGF.getEvaluationKind(ResType)) {
2294 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002295 return RValue::get(
2296 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00002297 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002298 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002299 return RValue::getComplex(Res.first, Res.second);
2300 }
2301 case TEK_Aggregate:
2302 break;
2303 }
2304 llvm_unreachable("Must be a scalar or complex.");
2305}
2306
2307static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
2308 bool IsPostfixUpdate, const Expr *V,
2309 const Expr *X, const Expr *E,
2310 const Expr *UE, bool IsXLHSInRHSPart,
2311 SourceLocation Loc) {
2312 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
2313 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
2314 RValue NewVVal;
2315 LValue VLValue = CGF.EmitLValue(V);
2316 LValue XLValue = CGF.EmitLValue(X);
2317 RValue ExprRValue = CGF.EmitAnyExpr(E);
2318 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
2319 QualType NewVValType;
2320 if (UE) {
2321 // 'x' is updated with some additional value.
2322 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2323 "Update expr in 'atomic capture' must be a binary operator.");
2324 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2325 // Update expressions are allowed to have the following forms:
2326 // x binop= expr; -> xrval + expr;
2327 // x++, ++x -> xrval + 1;
2328 // x--, --x -> xrval - 1;
2329 // x = x binop expr; -> xrval binop expr
2330 // x = expr Op x; - > expr binop xrval;
2331 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2332 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2333 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2334 NewVValType = XRValExpr->getType();
2335 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2336 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
2337 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
2338 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2339 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2340 RValue Res = CGF.EmitAnyExpr(UE);
2341 NewVVal = IsPostfixUpdate ? XRValue : Res;
2342 return Res;
2343 };
2344 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2345 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2346 if (Res.first) {
2347 // 'atomicrmw' instruction was generated.
2348 if (IsPostfixUpdate) {
2349 // Use old value from 'atomicrmw'.
2350 NewVVal = Res.second;
2351 } else {
2352 // 'atomicrmw' does not provide new value, so evaluate it using old
2353 // value of 'x'.
2354 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2355 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
2356 NewVVal = CGF.EmitAnyExpr(UE);
2357 }
2358 }
2359 } else {
2360 // 'x' is simply rewritten with some 'expr'.
2361 NewVValType = X->getType().getNonReferenceType();
2362 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002363 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002364 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
2365 NewVVal = XRValue;
2366 return ExprRValue;
2367 };
2368 // Try to perform atomicrmw xchg, otherwise simple exchange.
2369 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2370 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
2371 Loc, Gen);
2372 if (Res.first) {
2373 // 'atomicrmw' instruction was generated.
2374 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2375 }
2376 }
2377 // Emit post-update store to 'v' of old/new 'x' value.
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002378 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002379 // OpenMP, 2.12.6, atomic Construct
2380 // Any atomic construct with a seq_cst clause forces the atomically
2381 // performed operation to include an implicit flush operation without a
2382 // list.
2383 if (IsSeqCst)
2384 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2385}
2386
Alexey Bataevb57056f2015-01-22 06:17:56 +00002387static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002388 bool IsSeqCst, bool IsPostfixUpdate,
2389 const Expr *X, const Expr *V, const Expr *E,
2390 const Expr *UE, bool IsXLHSInRHSPart,
2391 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002392 switch (Kind) {
2393 case OMPC_read:
2394 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
2395 break;
2396 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00002397 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
2398 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002399 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002400 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00002401 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2402 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002403 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002404 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2405 IsXLHSInRHSPart, Loc);
2406 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002407 case OMPC_if:
2408 case OMPC_final:
2409 case OMPC_num_threads:
2410 case OMPC_private:
2411 case OMPC_firstprivate:
2412 case OMPC_lastprivate:
2413 case OMPC_reduction:
2414 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00002415 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002416 case OMPC_collapse:
2417 case OMPC_default:
2418 case OMPC_seq_cst:
2419 case OMPC_shared:
2420 case OMPC_linear:
2421 case OMPC_aligned:
2422 case OMPC_copyin:
2423 case OMPC_copyprivate:
2424 case OMPC_flush:
2425 case OMPC_proc_bind:
2426 case OMPC_schedule:
2427 case OMPC_ordered:
2428 case OMPC_nowait:
2429 case OMPC_untied:
2430 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002431 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002432 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00002433 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00002434 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002435 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00002436 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00002437 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002438 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00002439 case OMPC_priority:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002440 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2441 }
2442}
2443
2444void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002445 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00002446 OpenMPClauseKind Kind = OMPC_unknown;
2447 for (auto *C : S.clauses()) {
2448 // Find first clause (skip seq_cst clause, if it is first).
2449 if (C->getClauseKind() != OMPC_seq_cst) {
2450 Kind = C->getClauseKind();
2451 break;
2452 }
2453 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002454
2455 const auto *CS =
2456 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002457 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00002458 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002459 }
2460 // Processing for statements under 'atomic capture'.
2461 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2462 for (const auto *C : Compound->body()) {
2463 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2464 enterFullExpression(EWC);
2465 }
2466 }
2467 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002468
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002469 LexicalScope Scope(*this, S.getSourceRange());
2470 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002471 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2472 S.getV(), S.getExpr(), S.getUpdateExpr(),
2473 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002474 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002475 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00002476}
2477
Samuel Antaobed3c462015-10-02 16:14:20 +00002478void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
2479 LexicalScope Scope(*this, S.getSourceRange());
2480 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
2481
2482 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2483 GenerateOpenMPCapturedVars(CS, CapturedVars, /*UseOnlyReferences=*/true);
2484
2485 // Emit target region as a standalone region.
2486 auto &&CodeGen = [&CS](CodeGenFunction &CGF) {
2487 CGF.EmitStmt(CS.getCapturedStmt());
2488 };
2489
2490 // Obtain the target region outlined function.
2491 llvm::Value *Fn =
2492 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, CodeGen);
2493
2494 // Check if we have any if clause associated with the directive.
2495 const Expr *IfCond = nullptr;
2496
2497 if (auto *C = S.getSingleClause<OMPIfClause>()) {
2498 IfCond = C->getCondition();
2499 }
2500
2501 // Check if we have any device clause associated with the directive.
2502 const Expr *Device = nullptr;
2503 if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
2504 Device = C->getDevice();
2505 }
2506
2507 CGM.getOpenMPRuntime().emitTargetCall(*this, S, Fn, IfCond, Device,
2508 CapturedVars);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002509}
2510
Alexey Bataev13314bf2014-10-09 04:18:56 +00002511void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
2512 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
2513}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002514
2515void CodeGenFunction::EmitOMPCancellationPointDirective(
2516 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00002517 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
2518 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002519}
2520
Alexey Bataev80909872015-07-02 11:25:17 +00002521void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev87933c72015-09-18 08:07:34 +00002522 const Expr *IfCond = nullptr;
2523 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2524 if (C->getNameModifier() == OMPD_unknown ||
2525 C->getNameModifier() == OMPD_cancel) {
2526 IfCond = C->getCondition();
2527 break;
2528 }
2529 }
2530 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002531 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00002532}
2533
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002534CodeGenFunction::JumpDest
2535CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
2536 if (Kind == OMPD_parallel || Kind == OMPD_task)
2537 return ReturnBlock;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002538 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
2539 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for);
2540 return BreakContinueStack.back().BreakBlock;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002541}
Michael Wong65f367f2015-07-21 13:44:28 +00002542
2543// Generate the instructions for '#pragma omp target data' directive.
2544void CodeGenFunction::EmitOMPTargetDataDirective(
2545 const OMPTargetDataDirective &S) {
Michael Wong65f367f2015-07-21 13:44:28 +00002546 // emit the code inside the construct for now
2547 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Michael Wongb5c16982015-08-11 04:52:01 +00002548 CGM.getOpenMPRuntime().emitInlinedDirective(
2549 *this, OMPD_target_data,
2550 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
Michael Wong65f367f2015-07-21 13:44:28 +00002551}
Alexey Bataev49f6e782015-12-01 04:18:41 +00002552
2553void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
2554 // emit the code inside the construct for now
2555 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2556 CGM.getOpenMPRuntime().emitInlinedDirective(
2557 *this, OMPD_taskloop,
2558 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2559}
2560