blob: 61945c63ab1f4df2b645fa8769fe273f066c2082 [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
23//===----------------------------------------------------------------------===//
24// OpenMP Directive Emission
25//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +000026void CodeGenFunction::EmitOMPAggregateAssign(
27 llvm::Value *DestAddr, llvm::Value *SrcAddr, QualType OriginalType,
28 const llvm::function_ref<void(llvm::Value *, llvm::Value *)> &CopyGen) {
29 // Perform element-by-element initialization.
30 QualType ElementTy;
31 auto SrcBegin = SrcAddr;
32 auto DestBegin = DestAddr;
33 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
34 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestBegin);
35 // Cast from pointer to array type to pointer to single element.
36 SrcBegin = Builder.CreatePointerBitCastOrAddrSpaceCast(SrcBegin,
37 DestBegin->getType());
38 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
39 // The basic structure here is a while-do loop.
40 auto BodyBB = createBasicBlock("omp.arraycpy.body");
41 auto DoneBB = createBasicBlock("omp.arraycpy.done");
42 auto IsEmpty =
43 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
44 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000045
Alexey Bataev420d45b2015-04-14 05:11:24 +000046 // Enter the loop body, making that address the current address.
47 auto EntryBB = Builder.GetInsertBlock();
48 EmitBlock(BodyBB);
49 auto SrcElementCurrent =
50 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
51 SrcElementCurrent->addIncoming(SrcBegin, EntryBB);
52 auto DestElementCurrent = Builder.CreatePHI(DestBegin->getType(), 2,
53 "omp.arraycpy.destElementPast");
54 DestElementCurrent->addIncoming(DestBegin, EntryBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000055
Alexey Bataev420d45b2015-04-14 05:11:24 +000056 // Emit copy.
57 CopyGen(DestElementCurrent, SrcElementCurrent);
58
59 // Shift the address forward by one element.
60 auto DestElementNext = Builder.CreateConstGEP1_32(
61 DestElementCurrent, /*Idx0=*/1, "omp.arraycpy.dest.element");
62 auto SrcElementNext = Builder.CreateConstGEP1_32(
63 SrcElementCurrent, /*Idx0=*/1, "omp.arraycpy.src.element");
64 // Check whether we've reached the end.
65 auto Done =
66 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
67 Builder.CreateCondBr(Done, DoneBB, BodyBB);
68 DestElementCurrent->addIncoming(DestElementNext, Builder.GetInsertBlock());
69 SrcElementCurrent->addIncoming(SrcElementNext, Builder.GetInsertBlock());
70
71 // Done.
72 EmitBlock(DoneBB, /*IsFinished=*/true);
73}
74
75void CodeGenFunction::EmitOMPCopy(CodeGenFunction &CGF,
76 QualType OriginalType, llvm::Value *DestAddr,
77 llvm::Value *SrcAddr, const VarDecl *DestVD,
78 const VarDecl *SrcVD, const Expr *Copy) {
79 if (OriginalType->isArrayType()) {
80 auto *BO = dyn_cast<BinaryOperator>(Copy);
81 if (BO && BO->getOpcode() == BO_Assign) {
82 // Perform simple memcpy for simple copying.
83 CGF.EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
84 } else {
85 // For arrays with complex element types perform element by element
86 // copying.
87 CGF.EmitOMPAggregateAssign(
88 DestAddr, SrcAddr, OriginalType,
89 [&CGF, Copy, SrcVD, DestVD](llvm::Value *DestElement,
90 llvm::Value *SrcElement) {
91 // Working with the single array element, so have to remap
92 // destination and source variables to corresponding array
93 // elements.
94 CodeGenFunction::OMPPrivateScope Remap(CGF);
95 Remap.addPrivate(DestVD, [DestElement]() -> llvm::Value *{
96 return DestElement;
97 });
98 Remap.addPrivate(
99 SrcVD, [SrcElement]() -> llvm::Value *{ return SrcElement; });
100 (void)Remap.Privatize();
101 CGF.EmitIgnoredExpr(Copy);
102 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000103 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000104 } else {
105 // Remap pseudo source variable to private copy.
106 CodeGenFunction::OMPPrivateScope Remap(CGF);
107 Remap.addPrivate(SrcVD, [SrcAddr]() -> llvm::Value *{ return SrcAddr; });
108 Remap.addPrivate(DestVD, [DestAddr]() -> llvm::Value *{ return DestAddr; });
109 (void)Remap.Privatize();
110 // Emit copying of the whole variable.
111 CGF.EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000112 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000113}
114
Alexey Bataev69c62a92015-04-15 04:52:20 +0000115bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
116 OMPPrivateScope &PrivateScope) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000117 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000118 for (auto &&I = D.getClausesOfKind(OMPC_firstprivate); I; ++I) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000119 auto *C = cast<OMPFirstprivateClause>(*I);
120 auto IRef = C->varlist_begin();
121 auto InitsRef = C->inits().begin();
122 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000123 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000124 if (EmittedAsFirstprivate.count(OrigVD) == 0) {
125 EmittedAsFirstprivate.insert(OrigVD);
126 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
127 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
128 bool IsRegistered;
129 DeclRefExpr DRE(
130 const_cast<VarDecl *>(OrigVD),
131 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
132 OrigVD) != nullptr,
133 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
134 auto *OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000135 QualType Type = OrigVD->getType();
136 if (auto *PVD = dyn_cast<ParmVarDecl>(OrigVD)) {
137 Type = PVD->getOriginalType();
138 }
139 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000140 // Emit VarDecl with copy init for arrays.
141 // Get the address of the original variable captured in current
142 // captured region.
143 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
144 auto Emission = EmitAutoVarAlloca(*VD);
145 auto *Init = VD->getInit();
146 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
147 // Perform simple memcpy.
148 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000149 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000150 } else {
151 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000152 Emission.getAllocatedAddress(), OriginalAddr, Type,
Alexey Bataev69c62a92015-04-15 04:52:20 +0000153 [this, VDInit, Init](llvm::Value *DestElement,
154 llvm::Value *SrcElement) {
155 // Clean up any temporaries needed by the initialization.
156 RunCleanupsScope InitScope(*this);
157 // Emit initialization for single element.
158 LocalDeclMap[VDInit] = SrcElement;
159 EmitAnyExprToMem(Init, DestElement,
160 Init->getType().getQualifiers(),
161 /*IsInitializer*/ false);
162 LocalDeclMap.erase(VDInit);
163 });
164 }
165 EmitAutoVarCleanups(Emission);
166 return Emission.getAllocatedAddress();
167 });
168 } else {
169 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
170 // Emit private VarDecl with copy init.
171 // Remap temp VDInit variable to the address of the original
172 // variable
173 // (for proper handling of captured global variables).
174 LocalDeclMap[VDInit] = OriginalAddr;
175 EmitDecl(*VD);
176 LocalDeclMap.erase(VDInit);
177 return GetAddrOfLocalVar(VD);
178 });
179 }
180 assert(IsRegistered &&
181 "firstprivate var already registered as private");
182 // Silence the warning about unused variable.
183 (void)IsRegistered;
184 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000185 ++IRef, ++InitsRef;
186 }
187 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000188 return !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000189}
190
Alexey Bataev03b340a2014-10-21 03:16:40 +0000191void CodeGenFunction::EmitOMPPrivateClause(
192 const OMPExecutableDirective &D,
193 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev50a64582015-04-22 12:24:45 +0000194 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000195 for (auto &&I = D.getClausesOfKind(OMPC_private); I; ++I) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000196 auto *C = cast<OMPPrivateClause>(*I);
197 auto IRef = C->varlist_begin();
198 for (auto IInit : C->private_copies()) {
199 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000200 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
201 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
202 bool IsRegistered =
203 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
204 // Emit private VarDecl with copy init.
205 EmitDecl(*VD);
206 return GetAddrOfLocalVar(VD);
207 });
208 assert(IsRegistered && "private var already registered as private");
209 // Silence the warning about unused variable.
210 (void)IsRegistered;
211 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000212 ++IRef;
213 }
214 }
215}
216
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000217bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
218 // threadprivate_var1 = master_threadprivate_var1;
219 // operator=(threadprivate_var2, master_threadprivate_var2);
220 // ...
221 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000222 llvm::DenseSet<const VarDecl *> CopiedVars;
223 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000224 for (auto &&I = D.getClausesOfKind(OMPC_copyin); I; ++I) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000225 auto *C = cast<OMPCopyinClause>(*I);
226 auto IRef = C->varlist_begin();
227 auto ISrcRef = C->source_exprs().begin();
228 auto IDestRef = C->destination_exprs().begin();
229 for (auto *AssignOp : C->assignment_ops()) {
230 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000231 QualType Type = VD->getType();
232 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
233 Type = PVD->getOriginalType();
234 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000235 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
236 // Get the address of the master variable.
237 auto *MasterAddr = VD->isStaticLocal()
238 ? CGM.getStaticLocalDeclAddress(VD)
239 : CGM.GetAddrOfGlobal(VD);
240 // Get the address of the threadprivate variable.
241 auto *PrivateAddr = EmitLValue(*IRef).getAddress();
242 if (CopiedVars.size() == 1) {
243 // At first check if current thread is a master thread. If it is, no
244 // need to copy data.
245 CopyBegin = createBasicBlock("copyin.not.master");
246 CopyEnd = createBasicBlock("copyin.not.master.end");
247 Builder.CreateCondBr(
248 Builder.CreateICmpNE(
249 Builder.CreatePtrToInt(MasterAddr, CGM.IntPtrTy),
250 Builder.CreatePtrToInt(PrivateAddr, CGM.IntPtrTy)),
251 CopyBegin, CopyEnd);
252 EmitBlock(CopyBegin);
253 }
254 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
255 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000256 EmitOMPCopy(*this, Type, PrivateAddr, MasterAddr, DestVD, SrcVD,
257 AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000258 }
259 ++IRef;
260 ++ISrcRef;
261 ++IDestRef;
262 }
263 }
264 if (CopyEnd) {
265 // Exit out of copying procedure for non-master thread.
266 EmitBlock(CopyEnd, /*IsFinished=*/true);
267 return true;
268 }
269 return false;
270}
271
Alexey Bataev38e89532015-04-16 04:54:05 +0000272bool CodeGenFunction::EmitOMPLastprivateClauseInit(
273 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000274 bool HasAtLeastOneLastprivate = false;
275 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000276 for (auto &&I = D.getClausesOfKind(OMPC_lastprivate); I; ++I) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000277 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000278 auto *C = cast<OMPLastprivateClause>(*I);
279 auto IRef = C->varlist_begin();
280 auto IDestRef = C->destination_exprs().begin();
281 for (auto *IInit : C->private_copies()) {
282 // Keep the address of the original variable for future update at the end
283 // of the loop.
284 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
285 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
286 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
287 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> llvm::Value *{
288 DeclRefExpr DRE(
289 const_cast<VarDecl *>(OrigVD),
290 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
291 OrigVD) != nullptr,
292 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
293 return EmitLValue(&DRE).getAddress();
294 });
295 // Check if the variable is also a firstprivate: in this case IInit is
296 // not generated. Initialization of this variable will happen in codegen
297 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000298 if (IInit) {
299 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
300 bool IsRegistered =
301 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
302 // Emit private VarDecl with copy init.
303 EmitDecl(*VD);
304 return GetAddrOfLocalVar(VD);
305 });
306 assert(IsRegistered &&
307 "lastprivate var already registered as private");
308 (void)IsRegistered;
309 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000310 }
311 ++IRef, ++IDestRef;
312 }
313 }
314 return HasAtLeastOneLastprivate;
315}
316
317void CodeGenFunction::EmitOMPLastprivateClauseFinal(
318 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
319 // Emit following code:
320 // if (<IsLastIterCond>) {
321 // orig_var1 = private_orig_var1;
322 // ...
323 // orig_varn = private_orig_varn;
324 // }
325 auto *ThenBB = createBasicBlock(".omp.lastprivate.then");
326 auto *DoneBB = createBasicBlock(".omp.lastprivate.done");
327 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
328 EmitBlock(ThenBB);
329 {
Alexey Bataev38e89532015-04-16 04:54:05 +0000330 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000331 for (auto &&I = D.getClausesOfKind(OMPC_lastprivate); I; ++I) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000332 auto *C = cast<OMPLastprivateClause>(*I);
333 auto IRef = C->varlist_begin();
334 auto ISrcRef = C->source_exprs().begin();
335 auto IDestRef = C->destination_exprs().begin();
336 for (auto *AssignOp : C->assignment_ops()) {
337 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000338 QualType Type = PrivateVD->getType();
339 if (auto *PVD = dyn_cast<ParmVarDecl>(PrivateVD)) {
340 Type = PVD->getOriginalType();
341 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000342 if (AlreadyEmittedVars.insert(PrivateVD->getCanonicalDecl()).second) {
343 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
344 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
345 // Get the address of the original variable.
346 auto *OriginalAddr = GetAddrOfLocalVar(DestVD);
347 // Get the address of the private variable.
348 auto *PrivateAddr = GetAddrOfLocalVar(PrivateVD);
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000349 EmitOMPCopy(*this, Type, OriginalAddr, PrivateAddr, DestVD, SrcVD,
350 AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000351 }
352 ++IRef;
353 ++ISrcRef;
354 ++IDestRef;
355 }
356 }
357 }
358 EmitBlock(DoneBB, /*IsFinished=*/true);
359}
360
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000361void CodeGenFunction::EmitOMPReductionClauseInit(
362 const OMPExecutableDirective &D,
363 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataevc925aa32015-04-27 08:00:32 +0000364 for (auto &&I = D.getClausesOfKind(OMPC_reduction); I; ++I) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000365 auto *C = cast<OMPReductionClause>(*I);
366 auto ILHS = C->lhs_exprs().begin();
367 auto IRHS = C->rhs_exprs().begin();
368 for (auto IRef : C->varlists()) {
369 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
370 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
371 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
372 // Store the address of the original variable associated with the LHS
373 // implicit variable.
374 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> llvm::Value *{
375 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
376 CapturedStmtInfo->lookup(OrigVD) != nullptr,
377 IRef->getType(), VK_LValue, IRef->getExprLoc());
378 return EmitLValue(&DRE).getAddress();
379 });
380 // Emit reduction copy.
381 bool IsRegistered =
382 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> llvm::Value *{
383 // Emit private VarDecl with reduction init.
384 EmitDecl(*PrivateVD);
385 return GetAddrOfLocalVar(PrivateVD);
386 });
387 assert(IsRegistered && "private var already registered as private");
388 // Silence the warning about unused variable.
389 (void)IsRegistered;
390 ++ILHS, ++IRHS;
391 }
392 }
393}
394
395void CodeGenFunction::EmitOMPReductionClauseFinal(
396 const OMPExecutableDirective &D) {
397 llvm::SmallVector<const Expr *, 8> LHSExprs;
398 llvm::SmallVector<const Expr *, 8> RHSExprs;
399 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000400 bool HasAtLeastOneReduction = false;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000401 for (auto &&I = D.getClausesOfKind(OMPC_reduction); I; ++I) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000402 HasAtLeastOneReduction = true;
403 auto *C = cast<OMPReductionClause>(*I);
404 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
405 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
406 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
407 }
408 if (HasAtLeastOneReduction) {
409 // Emit nowait reduction if nowait clause is present or directive is a
410 // parallel directive (it always has implicit barrier).
411 CGM.getOpenMPRuntime().emitReduction(
412 *this, D.getLocEnd(), LHSExprs, RHSExprs, ReductionOps,
413 D.getSingleClause(OMPC_nowait) ||
414 isOpenMPParallelDirective(D.getDirectiveKind()));
415 }
416}
417
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000418static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
419 const OMPExecutableDirective &S,
420 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000421 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000422 auto CapturedStruct = CGF.GenerateCapturedStmtArgument(*CS);
423 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
424 S, *CS->getCapturedDecl()->param_begin(), CodeGen);
Alexey Bataev1d677132015-04-22 13:57:31 +0000425 if (auto C = S.getSingleClause(OMPC_num_threads)) {
426 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
427 auto NumThreadsClause = cast<OMPNumThreadsClause>(C);
428 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
429 /*IgnoreResultAssign*/ true);
430 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
431 CGF, NumThreads, NumThreadsClause->getLocStart());
432 }
433 const Expr *IfCond = nullptr;
434 if (auto C = S.getSingleClause(OMPC_if)) {
435 IfCond = cast<OMPIfClause>(C)->getCondition();
436 }
437 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
438 CapturedStruct, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000439}
440
441void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
442 LexicalScope Scope(*this, S.getSourceRange());
443 // Emit parallel region as a standalone region.
444 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
445 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000446 bool Copyins = CGF.EmitOMPCopyinClause(S);
447 bool Firstprivates = CGF.EmitOMPFirstprivateClause(S, PrivateScope);
448 if (Copyins || Firstprivates) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000449 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000450 // initialization of firstprivate variables or propagation master's thread
451 // values of threadprivate variables to local instances of that variables
452 // of all other implicit threads.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000453 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
454 OMPD_unknown);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000455 }
456 CGF.EmitOMPPrivateClause(S, PrivateScope);
457 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
458 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000459 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000460 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000461 // Emit implicit barrier at the end of the 'parallel' directive.
462 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
463 OMPD_unknown);
464 };
465 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +0000466}
Alexander Musman515ad8c2014-05-22 08:54:05 +0000467
Alexander Musmand196ef22014-10-07 08:57:09 +0000468void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &S,
Alexander Musmana5f070a2014-10-01 06:03:56 +0000469 bool SeparateIter) {
470 RunCleanupsScope BodyScope(*this);
471 // Update counters values on current iteration.
472 for (auto I : S.updates()) {
473 EmitIgnoredExpr(I);
474 }
Alexander Musman3276a272015-03-21 10:12:56 +0000475 // Update the linear variables.
Alexey Bataevc925aa32015-04-27 08:00:32 +0000476 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
477 auto *C = cast<OMPLinearClause>(*I);
Alexander Musman3276a272015-03-21 10:12:56 +0000478 for (auto U : C->updates()) {
479 EmitIgnoredExpr(U);
480 }
481 }
482
Alexander Musmana5f070a2014-10-01 06:03:56 +0000483 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +0000484 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000485 BreakContinueStack.push_back(BreakContinue(JumpDest(), Continue));
486 // Emit loop body.
487 EmitStmt(S.getBody());
488 // The end (updates/cleanups).
489 EmitBlock(Continue.getBlock());
490 BreakContinueStack.pop_back();
491 if (SeparateIter) {
492 // TODO: Update lastprivates if the SeparateIter flag is true.
493 // This will be implemented in a follow-up OMPLastprivateClause patch, but
494 // result should be still correct without it, as we do not make these
495 // variables private yet.
496 }
497}
498
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000499void CodeGenFunction::EmitOMPInnerLoop(
500 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
501 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000502 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
503 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +0000504 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000505
506 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +0000507 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000508 EmitBlock(CondBlock);
509 LoopStack.push(CondBlock);
510
511 // If there are any cleanups between here and the loop-exit scope,
512 // create a block to stage a loop exit along.
513 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +0000514 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +0000515 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000516
Alexander Musmand196ef22014-10-07 08:57:09 +0000517 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000518
Alexey Bataev2df54a02015-03-12 08:53:29 +0000519 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +0000520 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000521 if (ExitBlock != LoopExit.getBlock()) {
522 EmitBlock(ExitBlock);
523 EmitBranchThroughCleanup(LoopExit);
524 }
525
526 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +0000527 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000528
529 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +0000530 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000531 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
532
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000533 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000534
535 // Emit "IV = IV + 1" and a back-edge to the condition block.
536 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +0000537 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000538 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000539 BreakContinueStack.pop_back();
540 EmitBranch(CondBlock);
541 LoopStack.pop();
542 // Emit the fall-through block.
543 EmitBlock(LoopExit.getBlock());
544}
545
546void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &S) {
547 auto IC = S.counters().begin();
548 for (auto F : S.finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000549 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
550 if (LocalDeclMap.lookup(OrigVD)) {
551 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
552 CapturedStmtInfo->lookup(OrigVD) != nullptr,
553 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
554 auto *OrigAddr = EmitLValue(&DRE).getAddress();
555 OMPPrivateScope VarScope(*this);
556 VarScope.addPrivate(OrigVD,
557 [OrigAddr]() -> llvm::Value *{ return OrigAddr; });
558 (void)VarScope.Privatize();
Alexander Musmana5f070a2014-10-01 06:03:56 +0000559 EmitIgnoredExpr(F);
560 }
561 ++IC;
562 }
Alexander Musman3276a272015-03-21 10:12:56 +0000563 // Emit the final values of the linear variables.
Alexey Bataevc925aa32015-04-27 08:00:32 +0000564 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
565 auto *C = cast<OMPLinearClause>(*I);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000566 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +0000567 for (auto F : C->finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000568 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
569 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
570 CapturedStmtInfo->lookup(OrigVD) != nullptr,
571 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
572 auto *OrigAddr = EmitLValue(&DRE).getAddress();
573 OMPPrivateScope VarScope(*this);
574 VarScope.addPrivate(OrigVD,
575 [OrigAddr]() -> llvm::Value *{ return OrigAddr; });
576 (void)VarScope.Privatize();
Alexander Musman3276a272015-03-21 10:12:56 +0000577 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000578 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +0000579 }
580 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000581}
582
Alexander Musman09184fe2014-09-30 05:29:28 +0000583static void EmitOMPAlignedClause(CodeGenFunction &CGF, CodeGenModule &CGM,
584 const OMPAlignedClause &Clause) {
585 unsigned ClauseAlignment = 0;
586 if (auto AlignmentExpr = Clause.getAlignment()) {
587 auto AlignmentCI =
588 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
589 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
590 }
591 for (auto E : Clause.varlists()) {
592 unsigned Alignment = ClauseAlignment;
593 if (Alignment == 0) {
594 // OpenMP [2.8.1, Description]
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000595 // If no optional parameter is specified, implementation-defined default
Alexander Musman09184fe2014-09-30 05:29:28 +0000596 // alignments for SIMD instructions on the target platforms are assumed.
597 Alignment = CGM.getTargetCodeGenInfo().getOpenMPSimdDefaultAlignment(
598 E->getType());
599 }
600 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
601 "alignment is not power of 2");
602 if (Alignment != 0) {
603 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
604 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
605 }
606 }
607}
608
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000609static void EmitPrivateLoopCounters(CodeGenFunction &CGF,
610 CodeGenFunction::OMPPrivateScope &LoopScope,
611 ArrayRef<Expr *> Counters) {
612 for (auto *E : Counters) {
613 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev61114692015-04-28 13:20:05 +0000614 (void)LoopScope.addPrivate(VD, [&]() -> llvm::Value *{
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000615 // Emit var without initialization.
616 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
617 CGF.EmitAutoVarCleanups(VarEmission);
618 return VarEmission.getAllocatedAddress();
619 });
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000620 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000621}
622
Alexey Bataev62dbb972015-04-22 11:59:37 +0000623static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
624 const Expr *Cond, llvm::BasicBlock *TrueBlock,
625 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
626 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
627 EmitPrivateLoopCounters(CGF, PreCondScope, S.counters());
628 const VarDecl *IVDecl =
629 cast<VarDecl>(cast<DeclRefExpr>(S.getIterationVariable())->getDecl());
630 bool IsRegistered = PreCondScope.addPrivate(IVDecl, [&]() -> llvm::Value *{
631 // Emit var without initialization.
632 auto VarEmission = CGF.EmitAutoVarAlloca(*IVDecl);
633 CGF.EmitAutoVarCleanups(VarEmission);
634 return VarEmission.getAllocatedAddress();
635 });
636 assert(IsRegistered && "counter already registered as private");
637 // Silence the warning about unused variable.
638 (void)IsRegistered;
639 (void)PreCondScope.Privatize();
640 // Initialize internal counter to 0 to calculate initial values of real
641 // counters.
642 LValue IV = CGF.EmitLValue(S.getIterationVariable());
643 CGF.EmitStoreOfScalar(
644 llvm::ConstantInt::getNullValue(
645 IV.getAddress()->getType()->getPointerElementType()),
646 CGF.EmitLValue(S.getIterationVariable()), /*isInit=*/true);
647 // Get initial values of real counters.
648 for (auto I : S.updates()) {
649 CGF.EmitIgnoredExpr(I);
650 }
651 // Check that loop is executed at least one time.
652 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
653}
654
Alexander Musman3276a272015-03-21 10:12:56 +0000655static void
656EmitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
657 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataevc925aa32015-04-27 08:00:32 +0000658 for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) {
659 auto *C = cast<OMPLinearClause>(*I);
660 for (auto *E : C->varlists()) {
Alexander Musman3276a272015-03-21 10:12:56 +0000661 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
662 bool IsRegistered = PrivateScope.addPrivate(VD, [&]()->llvm::Value * {
663 // Emit var without initialization.
664 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
665 CGF.EmitAutoVarCleanups(VarEmission);
666 return VarEmission.getAllocatedAddress();
667 });
668 assert(IsRegistered && "linear var already registered as private");
669 // Silence the warning about unused variable.
670 (void)IsRegistered;
671 }
672 }
673}
674
Alexander Musman515ad8c2014-05-22 08:54:05 +0000675void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000676 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
677 // Pragma 'simd' code depends on presence of 'lastprivate'.
678 // If present, we have to separate last iteration of the loop:
679 //
Alexey Bataev62dbb972015-04-22 11:59:37 +0000680 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000681 // for (IV in 0..LastIteration-1) BODY;
682 // BODY with updates of lastprivate vars;
683 // <Final counter/linear vars updates>;
684 // }
685 //
686 // otherwise (when there's no lastprivate):
687 //
Alexey Bataev62dbb972015-04-22 11:59:37 +0000688 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000689 // for (IV in 0..LastIteration) BODY;
690 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000691 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000692 //
Alexander Musmana5f070a2014-10-01 06:03:56 +0000693
Alexey Bataev62dbb972015-04-22 11:59:37 +0000694 // Emit: if (PreCond) - begin.
695 // If the condition constant folds and can be elided, avoid emitting the
696 // whole loop.
697 bool CondConstant;
698 llvm::BasicBlock *ContBlock = nullptr;
699 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
700 if (!CondConstant)
701 return;
702 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000703 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
704 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +0000705 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
706 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +0000707 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +0000708 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000709 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000710 // Walk clauses and process safelen/lastprivate.
711 bool SeparateIter = false;
712 CGF.LoopStack.setParallel();
713 CGF.LoopStack.setVectorizerEnable(true);
714 for (auto C : S.clauses()) {
715 switch (C->getClauseKind()) {
716 case OMPC_safelen: {
717 RValue Len = CGF.EmitAnyExpr(cast<OMPSafelenClause>(C)->getSafelen(),
718 AggValueSlot::ignored(), true);
719 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
720 CGF.LoopStack.setVectorizerWidth(Val->getZExtValue());
721 // In presence of finite 'safelen', it may be unsafe to mark all
722 // the memory instructions parallel, because loop-carried
723 // dependences of 'safelen' iterations are possible.
724 CGF.LoopStack.setParallel(false);
725 break;
Alexander Musman3276a272015-03-21 10:12:56 +0000726 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000727 case OMPC_aligned:
728 EmitOMPAlignedClause(CGF, CGF.CGM, cast<OMPAlignedClause>(*C));
729 break;
730 case OMPC_lastprivate:
731 SeparateIter = true;
732 break;
733 default:
734 // Not handled yet
735 ;
736 }
737 }
Alexander Musman3276a272015-03-21 10:12:56 +0000738
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000739 // Emit inits for the linear variables.
Alexey Bataevc925aa32015-04-27 08:00:32 +0000740 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
741 auto *C = cast<OMPLinearClause>(*I);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000742 for (auto Init : C->inits()) {
743 auto *D = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
744 CGF.EmitVarDecl(*D);
745 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000746 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000747
748 // Emit the loop iteration variable.
749 const Expr *IVExpr = S.getIterationVariable();
750 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
751 CGF.EmitVarDecl(*IVDecl);
752 CGF.EmitIgnoredExpr(S.getInit());
753
754 // Emit the iterations count variable.
755 // If it is not a variable, Sema decided to calculate iterations count on
756 // each
757 // iteration (e.g., it is foldable into a constant).
758 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
759 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
760 // Emit calculation of the iterations count.
761 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000762 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000763
764 // Emit the linear steps for the linear clauses.
765 // If a step is not constant, it is pre-calculated before the loop.
Alexey Bataevc925aa32015-04-27 08:00:32 +0000766 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
767 auto *C = cast<OMPLinearClause>(*I);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000768 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
769 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
770 CGF.EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
771 // Emit calculation of the linear step.
772 CGF.EmitIgnoredExpr(CS);
773 }
774 }
775
Alexey Bataev62dbb972015-04-22 11:59:37 +0000776 {
777 OMPPrivateScope LoopScope(CGF);
778 EmitPrivateLoopCounters(CGF, LoopScope, S.counters());
779 EmitPrivateLinearVars(CGF, S, LoopScope);
780 CGF.EmitOMPPrivateClause(S, LoopScope);
781 (void)LoopScope.Privatize();
782 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
783 S.getCond(SeparateIter), S.getInc(),
784 [&S](CodeGenFunction &CGF) {
785 CGF.EmitOMPLoopBody(S);
786 CGF.EmitStopPoint(&S);
787 },
788 [](CodeGenFunction &) {});
789 if (SeparateIter) {
790 CGF.EmitOMPLoopBody(S, /*SeparateIter=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000791 }
Alexey Bataev62dbb972015-04-22 11:59:37 +0000792 }
793 CGF.EmitOMPSimdFinal(S);
794 // Emit: if (PreCond) - end.
795 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000796 CGF.EmitBranch(ContBlock);
797 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000798 }
799 };
800 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +0000801}
802
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000803void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
804 const OMPLoopDirective &S,
805 OMPPrivateScope &LoopScope,
806 llvm::Value *LB, llvm::Value *UB,
807 llvm::Value *ST, llvm::Value *IL,
808 llvm::Value *Chunk) {
809 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000810
811 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
812 const bool Dynamic = RT.isDynamic(ScheduleKind);
813
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000814 assert(!RT.isStaticNonchunked(ScheduleKind, /* Chunked */ Chunk != nullptr) &&
815 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000816
817 // Emit outer loop.
818 //
819 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +0000820 // When schedule(dynamic,chunk_size) is specified, the iterations are
821 // distributed to threads in the team in chunks as the threads request them.
822 // Each thread executes a chunk of iterations, then requests another chunk,
823 // until no chunks remain to be distributed. Each chunk contains chunk_size
824 // iterations, except for the last chunk to be distributed, which may have
825 // fewer iterations. When no chunk_size is specified, it defaults to 1.
826 //
827 // When schedule(guided,chunk_size) is specified, the iterations are assigned
828 // to threads in the team in chunks as the executing threads request them.
829 // Each thread executes a chunk of iterations, then requests another chunk,
830 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
831 // each chunk is proportional to the number of unassigned iterations divided
832 // by the number of threads in the team, decreasing to 1. For a chunk_size
833 // with value k (greater than 1), the size of each chunk is determined in the
834 // same way, with the restriction that the chunks do not contain fewer than k
835 // iterations (except for the last chunk to be assigned, which may have fewer
836 // than k iterations).
837 //
838 // When schedule(auto) is specified, the decision regarding scheduling is
839 // delegated to the compiler and/or runtime system. The programmer gives the
840 // implementation the freedom to choose any possible mapping of iterations to
841 // threads in the team.
842 //
843 // When schedule(runtime) is specified, the decision regarding scheduling is
844 // deferred until run time, and the schedule and chunk size are taken from the
845 // run-sched-var ICV. If the ICV is set to auto, the schedule is
846 // implementation defined
847 //
848 // while(__kmpc_dispatch_next(&LB, &UB)) {
849 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000850 // while (idx <= UB) { BODY; ++idx;
851 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
852 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +0000853 // }
854 //
855 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000856 // When schedule(static, chunk_size) is specified, iterations are divided into
857 // chunks of size chunk_size, and the chunks are assigned to the threads in
858 // the team in a round-robin fashion in the order of the thread number.
859 //
860 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
861 // while (idx <= UB) { BODY; ++idx; } // inner loop
862 // LB = LB + ST;
863 // UB = UB + ST;
864 // }
865 //
Alexander Musman92bdaab2015-03-12 13:37:50 +0000866
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000867 const Expr *IVExpr = S.getIterationVariable();
868 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
869 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
870
Alexander Musman92bdaab2015-03-12 13:37:50 +0000871 RT.emitForInit(
872 *this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, IL, LB,
873 (Dynamic ? EmitAnyExpr(S.getLastIteration()).getScalarVal() : UB), ST,
874 Chunk);
875
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000876 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
877
878 // Start the loop with a block that tests the condition.
879 auto CondBlock = createBasicBlock("omp.dispatch.cond");
880 EmitBlock(CondBlock);
881 LoopStack.push(CondBlock);
882
883 llvm::Value *BoolCondVal = nullptr;
Alexander Musman92bdaab2015-03-12 13:37:50 +0000884 if (!Dynamic) {
885 // UB = min(UB, GlobalUB)
886 EmitIgnoredExpr(S.getEnsureUpperBound());
887 // IV = LB
888 EmitIgnoredExpr(S.getInit());
889 // IV < UB
890 BoolCondVal = EvaluateExprAsBool(S.getCond(false));
891 } else {
892 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
893 IL, LB, UB, ST);
894 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000895
896 // If there are any cleanups between here and the loop-exit scope,
897 // create a block to stage a loop exit along.
898 auto ExitBlock = LoopExit.getBlock();
899 if (LoopScope.requiresCleanups())
900 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
901
902 auto LoopBody = createBasicBlock("omp.dispatch.body");
903 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
904 if (ExitBlock != LoopExit.getBlock()) {
905 EmitBlock(ExitBlock);
906 EmitBranchThroughCleanup(LoopExit);
907 }
908 EmitBlock(LoopBody);
909
Alexander Musman92bdaab2015-03-12 13:37:50 +0000910 // Emit "IV = LB" (in case of static schedule, we have already calculated new
911 // LB for loop condition and emitted it above).
912 if (Dynamic)
913 EmitIgnoredExpr(S.getInit());
914
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000915 // Create a block for the increment.
916 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
917 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
918
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000919 bool DynamicWithOrderedClause =
920 Dynamic && S.getSingleClause(OMPC_ordered) != nullptr;
921 SourceLocation Loc = S.getLocStart();
Alexey Bataev53223c92015-05-07 04:25:17 +0000922 // Generate !llvm.loop.parallel metadata for loads and stores for loops with
923 // dynamic/guided scheduling and without ordered clause.
924 LoopStack.setParallel((ScheduleKind == OMPC_SCHEDULE_dynamic ||
925 ScheduleKind == OMPC_SCHEDULE_guided) &&
926 !DynamicWithOrderedClause);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000927 EmitOMPInnerLoop(
928 S, LoopScope.requiresCleanups(), S.getCond(/*SeparateIter=*/false),
929 S.getInc(),
930 [&S](CodeGenFunction &CGF) {
931 CGF.EmitOMPLoopBody(S);
932 CGF.EmitStopPoint(&S);
933 },
934 [DynamicWithOrderedClause, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
935 if (DynamicWithOrderedClause) {
936 CGF.CGM.getOpenMPRuntime().emitForOrderedDynamicIterationEnd(
937 CGF, Loc, IVSize, IVSigned);
938 }
939 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000940
941 EmitBlock(Continue.getBlock());
942 BreakContinueStack.pop_back();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000943 if (!Dynamic) {
944 // Emit "LB = LB + Stride", "UB = UB + Stride".
945 EmitIgnoredExpr(S.getNextLowerBound());
946 EmitIgnoredExpr(S.getNextUpperBound());
947 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000948
949 EmitBranch(CondBlock);
950 LoopStack.pop();
951 // Emit the fall-through block.
952 EmitBlock(LoopExit.getBlock());
953
954 // Tell the runtime we are done.
Alexander Musman92bdaab2015-03-12 13:37:50 +0000955 if (!Dynamic)
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000956 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000957}
958
Alexander Musmanc6388682014-12-15 07:07:06 +0000959/// \brief Emit a helper variable and return corresponding lvalue.
960static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
961 const DeclRefExpr *Helper) {
962 auto VDecl = cast<VarDecl>(Helper->getDecl());
963 CGF.EmitVarDecl(*VDecl);
964 return CGF.EmitLValue(Helper);
965}
966
Alexey Bataev040d5402015-05-12 08:35:28 +0000967static std::pair<llvm::Value * /*Chunk*/, OpenMPScheduleClauseKind>
968emitScheduleClause(CodeGenFunction &CGF, const OMPLoopDirective &S,
969 bool OuterRegion) {
970 // Detect the loop schedule kind and chunk.
971 auto ScheduleKind = OMPC_SCHEDULE_unknown;
972 llvm::Value *Chunk = nullptr;
973 if (auto *C =
974 cast_or_null<OMPScheduleClause>(S.getSingleClause(OMPC_schedule))) {
975 ScheduleKind = C->getScheduleKind();
976 if (const auto *Ch = C->getChunkSize()) {
977 if (auto *ImpRef = cast_or_null<DeclRefExpr>(C->getHelperChunkSize())) {
978 if (OuterRegion) {
979 const VarDecl *ImpVar = cast<VarDecl>(ImpRef->getDecl());
980 CGF.EmitVarDecl(*ImpVar);
981 CGF.EmitStoreThroughLValue(
982 CGF.EmitAnyExpr(Ch),
983 CGF.MakeNaturalAlignAddrLValue(CGF.GetAddrOfLocalVar(ImpVar),
984 ImpVar->getType()));
985 } else {
986 Ch = ImpRef;
987 }
988 }
989 if (!C->getHelperChunkSize() || !OuterRegion) {
990 Chunk = CGF.EmitScalarExpr(Ch);
991 Chunk = CGF.EmitScalarConversion(Chunk, Ch->getType(),
992 S.getIterationVariable()->getType());
993 }
994 }
995 }
996 return std::make_pair(Chunk, ScheduleKind);
997}
998
Alexey Bataev38e89532015-04-16 04:54:05 +0000999bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001000 // Emit the loop iteration variable.
1001 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1002 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1003 EmitVarDecl(*IVDecl);
1004
1005 // Emit the iterations count variable.
1006 // If it is not a variable, Sema decided to calculate iterations count on each
1007 // iteration (e.g., it is foldable into a constant).
1008 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1009 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1010 // Emit calculation of the iterations count.
1011 EmitIgnoredExpr(S.getCalcLastIteration());
1012 }
1013
1014 auto &RT = CGM.getOpenMPRuntime();
1015
Alexey Bataev38e89532015-04-16 04:54:05 +00001016 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001017 // Check pre-condition.
1018 {
1019 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001020 // If the condition constant folds and can be elided, avoid emitting the
1021 // whole loop.
1022 bool CondConstant;
1023 llvm::BasicBlock *ContBlock = nullptr;
1024 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1025 if (!CondConstant)
1026 return false;
1027 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001028 auto *ThenBlock = createBasicBlock("omp.precond.then");
1029 ContBlock = createBasicBlock("omp.precond.end");
1030 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001031 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001032 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001033 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001034 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001035 // Emit 'then' code.
1036 {
1037 // Emit helper vars inits.
1038 LValue LB =
1039 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1040 LValue UB =
1041 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1042 LValue ST =
1043 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1044 LValue IL =
1045 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1046
1047 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001048 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1049 // Emit implicit barrier to synchronize threads and avoid data races on
1050 // initialization of firstprivate variables.
1051 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1052 OMPD_unknown);
1053 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001054 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001055 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001056 EmitOMPReductionClauseInit(S, LoopScope);
Alexander Musmanc6388682014-12-15 07:07:06 +00001057 EmitPrivateLoopCounters(*this, LoopScope, S.counters());
Alexander Musman7931b982015-03-16 07:14:41 +00001058 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001059
1060 // Detect the loop schedule kind and chunk.
Alexey Bataev040d5402015-05-12 08:35:28 +00001061 llvm::Value *Chunk;
1062 OpenMPScheduleClauseKind ScheduleKind;
1063 auto ScheduleInfo =
1064 emitScheduleClause(*this, S, /*OuterRegion=*/false);
1065 Chunk = ScheduleInfo.first;
1066 ScheduleKind = ScheduleInfo.second;
Alexander Musmanc6388682014-12-15 07:07:06 +00001067 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1068 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1069 if (RT.isStaticNonchunked(ScheduleKind,
1070 /* Chunked */ Chunk != nullptr)) {
1071 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1072 // When no chunk_size is specified, the iteration space is divided into
1073 // chunks that are approximately equal in size, and at most one chunk is
1074 // distributed to each thread. Note that the size of the chunks is
1075 // unspecified in this case.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001076 RT.emitForInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
1077 IL.getAddress(), LB.getAddress(), UB.getAddress(),
1078 ST.getAddress());
Alexander Musmanc6388682014-12-15 07:07:06 +00001079 // UB = min(UB, GlobalUB);
1080 EmitIgnoredExpr(S.getEnsureUpperBound());
1081 // IV = LB;
1082 EmitIgnoredExpr(S.getInit());
1083 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001084 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
1085 S.getCond(/*SeparateIter=*/false), S.getInc(),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001086 [&S](CodeGenFunction &CGF) {
1087 CGF.EmitOMPLoopBody(S);
1088 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001089 },
1090 [](CodeGenFunction &) {});
Alexander Musmanc6388682014-12-15 07:07:06 +00001091 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001092 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001093 } else {
1094 // Emit the outer loop, which requests its work chunk [LB..UB] from
1095 // runtime and runs the inner loop to process it.
1096 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, LB.getAddress(),
1097 UB.getAddress(), ST.getAddress(), IL.getAddress(),
1098 Chunk);
1099 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001100 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001101 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1102 if (HasLastprivateClause)
1103 EmitOMPLastprivateClauseFinal(
1104 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001105 }
1106 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001107 if (ContBlock) {
1108 EmitBranch(ContBlock);
1109 EmitBlock(ContBlock, true);
1110 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001111 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001112 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001113}
1114
1115void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001116 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev38e89532015-04-16 04:54:05 +00001117 bool HasLastprivates = false;
1118 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1119 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1120 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001121 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musmanc6388682014-12-15 07:07:06 +00001122
1123 // Emit an implicit barrier at the end.
Alexey Bataev38e89532015-04-16 04:54:05 +00001124 if (!S.getSingleClause(OMPC_nowait) || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001125 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1126 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001127}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001128
Alexander Musmanf82886e2014-09-18 05:12:34 +00001129void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &) {
1130 llvm_unreachable("CodeGen for 'omp for simd' is not supported yet.");
1131}
1132
Alexey Bataev2df54a02015-03-12 08:53:29 +00001133static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1134 const Twine &Name,
1135 llvm::Value *Init = nullptr) {
1136 auto LVal = CGF.MakeNaturalAlignAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
1137 if (Init)
1138 CGF.EmitScalarInit(Init, LVal);
1139 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001140}
1141
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001142static OpenMPDirectiveKind emitSections(CodeGenFunction &CGF,
1143 const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001144 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1145 auto *CS = dyn_cast<CompoundStmt>(Stmt);
1146 if (CS && CS->size() > 1) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001147 bool HasLastprivates = false;
1148 auto &&CodeGen = [&S, CS, &HasLastprivates](CodeGenFunction &CGF) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001149 auto &C = CGF.CGM.getContext();
1150 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1151 // Emit helper vars inits.
1152 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1153 CGF.Builder.getInt32(0));
1154 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
1155 LValue UB =
1156 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1157 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1158 CGF.Builder.getInt32(1));
1159 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1160 CGF.Builder.getInt32(0));
1161 // Loop counter.
1162 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1163 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001164 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001165 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001166 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001167 // Generate condition for loop.
1168 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1169 OK_Ordinary, S.getLocStart(),
1170 /*fpContractable=*/false);
1171 // Increment for loop counter.
1172 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
1173 OK_Ordinary, S.getLocStart());
1174 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
1175 // Iterate through all sections and emit a switch construct:
1176 // switch (IV) {
1177 // case 0:
1178 // <SectionStmt[0]>;
1179 // break;
1180 // ...
1181 // case <NumSection> - 1:
1182 // <SectionStmt[<NumSection> - 1]>;
1183 // break;
1184 // }
1185 // .omp.sections.exit:
1186 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1187 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1188 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1189 CS->size());
1190 unsigned CaseNumber = 0;
1191 for (auto C = CS->children(); C; ++C, ++CaseNumber) {
1192 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1193 CGF.EmitBlock(CaseBB);
1194 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
1195 CGF.EmitStmt(*C);
1196 CGF.EmitBranch(ExitBB);
1197 }
1198 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1199 };
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001200
1201 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1202 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
1203 // Emit implicit barrier to synchronize threads and avoid data races on
1204 // initialization of firstprivate variables.
1205 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1206 OMPD_unknown);
1207 }
Alexey Bataev73870832015-04-27 04:12:12 +00001208 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001209 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001210 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001211 (void)LoopScope.Privatize();
1212
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001213 // Emit static non-chunked loop.
1214 CGF.CGM.getOpenMPRuntime().emitForInit(
1215 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
1216 /*IVSigned=*/true, IL.getAddress(), LB.getAddress(), UB.getAddress(),
1217 ST.getAddress());
1218 // UB = min(UB, GlobalUB);
1219 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1220 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1221 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1222 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1223 // IV = LB;
1224 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1225 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001226 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1227 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001228 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001229 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataeva89adf22015-04-27 05:04:13 +00001230 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001231
1232 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1233 if (HasLastprivates)
1234 CGF.EmitOMPLastprivateClauseFinal(
1235 S, CGF.Builder.CreateIsNotNull(
1236 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev2df54a02015-03-12 08:53:29 +00001237 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001238
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001239 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, CodeGen);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001240 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1241 // clause. Otherwise the barrier will be generated by the codegen for the
1242 // directive.
1243 if (HasLastprivates && S.getSingleClause(OMPC_nowait)) {
1244 // Emit implicit barrier to synchronize threads and avoid data races on
1245 // initialization of firstprivate variables.
1246 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1247 OMPD_unknown);
1248 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001249 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001250 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001251 // If only one section is found - no need to generate loop, emit as a single
1252 // region.
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001253 bool HasFirstprivates;
Alexey Bataeva89adf22015-04-27 05:04:13 +00001254 // No need to generate reductions for sections with single section region, we
1255 // can use original shared variables for all operations.
Alexey Bataevc925aa32015-04-27 08:00:32 +00001256 bool HasReductions = !S.getClausesOfKind(OMPC_reduction).empty();
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001257 // No need to generate lastprivates for sections with single section region,
1258 // we can use original shared variable for all calculations with barrier at
1259 // the end of the sections.
Alexey Bataevc925aa32015-04-27 08:00:32 +00001260 bool HasLastprivates = !S.getClausesOfKind(OMPC_lastprivate).empty();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001261 auto &&CodeGen = [Stmt, &S, &HasFirstprivates](CodeGenFunction &CGF) {
1262 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1263 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev73870832015-04-27 04:12:12 +00001264 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001265 (void)SingleScope.Privatize();
1266
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001267 CGF.EmitStmt(Stmt);
1268 CGF.EnsureInsertPoint();
1269 };
1270 CGF.CGM.getOpenMPRuntime().emitSingleRegion(CGF, CodeGen, S.getLocStart(),
1271 llvm::None, llvm::None,
1272 llvm::None, llvm::None);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001273 // Emit barrier for firstprivates, lastprivates or reductions only if
1274 // 'sections' directive has 'nowait' clause. Otherwise the barrier will be
1275 // generated by the codegen for the directive.
1276 if ((HasFirstprivates || HasLastprivates || HasReductions) &&
1277 S.getSingleClause(OMPC_nowait)) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001278 // Emit implicit barrier to synchronize threads and avoid data races on
1279 // initialization of firstprivate variables.
1280 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1281 OMPD_unknown);
1282 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001283 return OMPD_single;
1284}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001285
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001286void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1287 LexicalScope Scope(*this, S.getSourceRange());
1288 OpenMPDirectiveKind EmittedAs = emitSections(*this, S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001289 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001290 if (!S.getSingleClause(OMPC_nowait)) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001291 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001292 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001293}
1294
1295void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001296 LexicalScope Scope(*this, S.getSourceRange());
1297 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1298 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1299 CGF.EnsureInsertPoint();
1300 };
1301 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001302}
1303
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001304void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001305 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001306 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001307 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001308 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001309 // Check if there are any 'copyprivate' clauses associated with this
1310 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001311 // construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001312 // Build a list of copyprivate variables along with helper expressions
1313 // (<source>, <destination>, <destination>=<source> expressions)
Alexey Bataevc925aa32015-04-27 08:00:32 +00001314 for (auto &&I = S.getClausesOfKind(OMPC_copyprivate); I; ++I) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001315 auto *C = cast<OMPCopyprivateClause>(*I);
1316 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001317 DestExprs.append(C->destination_exprs().begin(),
1318 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001319 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001320 AssignmentOps.append(C->assignment_ops().begin(),
1321 C->assignment_ops().end());
1322 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001323 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001324 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev5521d782015-04-24 04:21:15 +00001325 bool HasFirstprivates;
1326 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) {
1327 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1328 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev59c654a2015-04-27 03:48:52 +00001329 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev5521d782015-04-24 04:21:15 +00001330 (void)SingleScope.Privatize();
1331
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001332 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1333 CGF.EnsureInsertPoint();
1334 };
1335 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001336 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001337 AssignmentOps);
Alexey Bataev5521d782015-04-24 04:21:15 +00001338 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1339 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
1340 if ((!S.getSingleClause(OMPC_nowait) || HasFirstprivates) &&
1341 CopyprivateVars.empty()) {
1342 CGM.getOpenMPRuntime().emitBarrierCall(
1343 *this, S.getLocStart(),
1344 S.getSingleClause(OMPC_nowait) ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001345 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001346}
1347
Alexey Bataev8d690652014-12-04 07:23:53 +00001348void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001349 LexicalScope Scope(*this, S.getSourceRange());
1350 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1351 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1352 CGF.EnsureInsertPoint();
1353 };
1354 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001355}
1356
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001357void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001358 LexicalScope Scope(*this, S.getSourceRange());
1359 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1360 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1361 CGF.EnsureInsertPoint();
1362 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001363 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001364 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001365}
1366
Alexey Bataev671605e2015-04-13 05:28:11 +00001367void CodeGenFunction::EmitOMPParallelForDirective(
1368 const OMPParallelForDirective &S) {
1369 // Emit directive as a combined directive that consists of two implicit
1370 // directives: 'parallel' with 'for' directive.
1371 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev040d5402015-05-12 08:35:28 +00001372 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
Alexey Bataev671605e2015-04-13 05:28:11 +00001373 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1374 CGF.EmitOMPWorksharingLoop(S);
1375 // Emit implicit barrier at the end of parallel region, but this barrier
1376 // is at the end of 'for' directive, so emit it as the implicit barrier for
1377 // this 'for' directive.
1378 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1379 OMPD_parallel);
1380 };
1381 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001382}
1383
Alexander Musmane4e893b2014-09-23 09:33:00 +00001384void CodeGenFunction::EmitOMPParallelForSimdDirective(
1385 const OMPParallelForSimdDirective &) {
1386 llvm_unreachable("CodeGen for 'omp parallel for simd' is not supported yet.");
1387}
1388
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001389void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001390 const OMPParallelSectionsDirective &S) {
1391 // Emit directive as a combined directive that consists of two implicit
1392 // directives: 'parallel' with 'sections' directive.
1393 LexicalScope Scope(*this, S.getSourceRange());
1394 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1395 (void)emitSections(CGF, S);
1396 // Emit implicit barrier at the end of parallel region.
1397 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1398 OMPD_parallel);
1399 };
1400 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001401}
1402
Alexey Bataev62b63b12015-03-10 07:28:44 +00001403void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1404 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001405 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001406 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1407 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1408 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001409 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001410 // The first function argument for tasks is a thread id, the second one is a
1411 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001412 auto &&CodeGen = [PartId, &S](CodeGenFunction &CGF) {
1413 if (*PartId) {
1414 // TODO: emit code for untied tasks.
1415 }
1416 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1417 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00001418 auto OutlinedFn =
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001419 CGM.getOpenMPRuntime().emitTaskOutlinedFunction(S, *I, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001420 // Check if we should emit tied or untied task.
1421 bool Tied = !S.getSingleClause(OMPC_untied);
1422 // Check if the task is final
1423 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
1424 if (auto *Clause = S.getSingleClause(OMPC_final)) {
1425 // If the condition constant folds and can be elided, try to avoid emitting
1426 // the condition and the dead arm of the if/else.
1427 auto *Cond = cast<OMPFinalClause>(Clause)->getCondition();
1428 bool CondConstant;
1429 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1430 Final.setInt(CondConstant);
1431 else
1432 Final.setPointer(EvaluateExprAsBool(Cond));
1433 } else {
1434 // By default the task is not final.
1435 Final.setInt(/*IntVal=*/false);
1436 }
1437 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00001438 const Expr *IfCond = nullptr;
1439 if (auto C = S.getSingleClause(OMPC_if)) {
1440 IfCond = cast<OMPIfClause>(C)->getCondition();
1441 }
Alexey Bataev9e034042015-05-05 04:05:12 +00001442 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001443 // Get list of private variables.
1444 llvm::SmallVector<const Expr *, 8> Privates;
1445 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001446 for (auto &&I = S.getClausesOfKind(OMPC_private); I; ++I) {
1447 auto *C = cast<OMPPrivateClause>(*I);
1448 auto IRef = C->varlist_begin();
1449 for (auto *IInit : C->private_copies()) {
1450 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1451 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1452 Privates.push_back(*IRef);
1453 PrivateCopies.push_back(IInit);
1454 }
1455 ++IRef;
1456 }
1457 }
Alexey Bataev9e034042015-05-05 04:05:12 +00001458 EmittedAsPrivate.clear();
1459 // Get list of firstprivate variables.
1460 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
1461 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
1462 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
1463 for (auto &&I = S.getClausesOfKind(OMPC_firstprivate); I; ++I) {
1464 auto *C = cast<OMPFirstprivateClause>(*I);
1465 auto IRef = C->varlist_begin();
1466 auto IElemInitRef = C->inits().begin();
1467 for (auto *IInit : C->private_copies()) {
1468 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1469 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1470 FirstprivateVars.push_back(*IRef);
1471 FirstprivateCopies.push_back(IInit);
1472 FirstprivateInits.push_back(*IElemInitRef);
1473 }
1474 ++IRef, ++IElemInitRef;
1475 }
1476 }
1477 CGM.getOpenMPRuntime().emitTaskCall(
1478 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
1479 CapturedStruct, IfCond, Privates, PrivateCopies, FirstprivateVars,
1480 FirstprivateCopies, FirstprivateInits);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001481}
1482
Alexey Bataev9f797f32015-02-05 05:57:51 +00001483void CodeGenFunction::EmitOMPTaskyieldDirective(
1484 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001485 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001486}
1487
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001488void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001489 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001490}
1491
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001492void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
1493 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00001494}
1495
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001496void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001497 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
1498 if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) {
1499 auto FlushClause = cast<OMPFlushClause>(C);
1500 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1501 FlushClause->varlist_end());
1502 }
1503 return llvm::None;
1504 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00001505}
1506
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001507void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
1508 LexicalScope Scope(*this, S.getSourceRange());
1509 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1510 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1511 CGF.EnsureInsertPoint();
1512 };
1513 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001514}
1515
Alexey Bataevb57056f2015-01-22 06:17:56 +00001516static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
1517 QualType SrcType, QualType DestType) {
1518 assert(CGF.hasScalarEvaluationKind(DestType) &&
1519 "DestType must have scalar evaluation kind.");
1520 assert(!Val.isAggregate() && "Must be a scalar or complex.");
1521 return Val.isScalar()
1522 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType)
1523 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
1524 DestType);
1525}
1526
1527static CodeGenFunction::ComplexPairTy
1528convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
1529 QualType DestType) {
1530 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
1531 "DestType must have complex evaluation kind.");
1532 CodeGenFunction::ComplexPairTy ComplexVal;
1533 if (Val.isScalar()) {
1534 // Convert the input element to the element type of the complex.
1535 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1536 auto ScalarVal =
1537 CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestElementType);
1538 ComplexVal = CodeGenFunction::ComplexPairTy(
1539 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
1540 } else {
1541 assert(Val.isComplex() && "Must be a scalar or complex.");
1542 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
1543 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1544 ComplexVal.first = CGF.EmitScalarConversion(
1545 Val.getComplexVal().first, SrcElementType, DestElementType);
1546 ComplexVal.second = CGF.EmitScalarConversion(
1547 Val.getComplexVal().second, SrcElementType, DestElementType);
1548 }
1549 return ComplexVal;
1550}
1551
Alexey Bataev5e018f92015-04-23 06:35:10 +00001552static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
1553 LValue LVal, RValue RVal) {
1554 if (LVal.isGlobalReg()) {
1555 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
1556 } else {
1557 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
1558 : llvm::Monotonic,
1559 LVal.isVolatile(), /*IsInit=*/false);
1560 }
1561}
1562
1563static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal,
1564 QualType RValTy) {
1565 switch (CGF.getEvaluationKind(LVal.getType())) {
1566 case TEK_Scalar:
1567 CGF.EmitStoreThroughLValue(
1568 RValue::get(convertToScalarValue(CGF, RVal, RValTy, LVal.getType())),
1569 LVal);
1570 break;
1571 case TEK_Complex:
1572 CGF.EmitStoreOfComplex(
1573 convertToComplexValue(CGF, RVal, RValTy, LVal.getType()), LVal,
1574 /*isInit=*/false);
1575 break;
1576 case TEK_Aggregate:
1577 llvm_unreachable("Must be a scalar or complex.");
1578 }
1579}
1580
Alexey Bataevb57056f2015-01-22 06:17:56 +00001581static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
1582 const Expr *X, const Expr *V,
1583 SourceLocation Loc) {
1584 // v = x;
1585 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
1586 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
1587 LValue XLValue = CGF.EmitLValue(X);
1588 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00001589 RValue Res = XLValue.isGlobalReg()
1590 ? CGF.EmitLoadOfLValue(XLValue, Loc)
1591 : CGF.EmitAtomicLoad(XLValue, Loc,
1592 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00001593 : llvm::Monotonic,
1594 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001595 // OpenMP, 2.12.6, atomic Construct
1596 // Any atomic construct with a seq_cst clause forces the atomically
1597 // performed operation to include an implicit flush operation without a
1598 // list.
1599 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001600 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001601 emitSimpleStore(CGF,VLValue, Res, X->getType().getNonReferenceType());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001602}
1603
Alexey Bataevb8329262015-02-27 06:33:30 +00001604static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
1605 const Expr *X, const Expr *E,
1606 SourceLocation Loc) {
1607 // x = expr;
1608 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00001609 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00001610 // OpenMP, 2.12.6, atomic Construct
1611 // Any atomic construct with a seq_cst clause forces the atomically
1612 // performed operation to include an implicit flush operation without a
1613 // list.
1614 if (IsSeqCst)
1615 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1616}
1617
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00001618static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
1619 RValue Update,
1620 BinaryOperatorKind BO,
1621 llvm::AtomicOrdering AO,
1622 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001623 auto &Context = CGF.CGM.getContext();
1624 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00001625 // expression is simple and atomic is allowed for the given type for the
1626 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001627 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00001628 !Update.getScalarVal()->getType()->isIntegerTy() ||
1629 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
1630 (Update.getScalarVal()->getType() !=
1631 X.getAddress()->getType()->getPointerElementType())) ||
1632 !X.getAddress()->getType()->getPointerElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001633 !Context.getTargetInfo().hasBuiltinAtomic(
1634 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00001635 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001636
1637 llvm::AtomicRMWInst::BinOp RMWOp;
1638 switch (BO) {
1639 case BO_Add:
1640 RMWOp = llvm::AtomicRMWInst::Add;
1641 break;
1642 case BO_Sub:
1643 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00001644 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001645 RMWOp = llvm::AtomicRMWInst::Sub;
1646 break;
1647 case BO_And:
1648 RMWOp = llvm::AtomicRMWInst::And;
1649 break;
1650 case BO_Or:
1651 RMWOp = llvm::AtomicRMWInst::Or;
1652 break;
1653 case BO_Xor:
1654 RMWOp = llvm::AtomicRMWInst::Xor;
1655 break;
1656 case BO_LT:
1657 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1658 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
1659 : llvm::AtomicRMWInst::Max)
1660 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
1661 : llvm::AtomicRMWInst::UMax);
1662 break;
1663 case BO_GT:
1664 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1665 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
1666 : llvm::AtomicRMWInst::Min)
1667 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
1668 : llvm::AtomicRMWInst::UMin);
1669 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001670 case BO_Assign:
1671 RMWOp = llvm::AtomicRMWInst::Xchg;
1672 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001673 case BO_Mul:
1674 case BO_Div:
1675 case BO_Rem:
1676 case BO_Shl:
1677 case BO_Shr:
1678 case BO_LAnd:
1679 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001680 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001681 case BO_PtrMemD:
1682 case BO_PtrMemI:
1683 case BO_LE:
1684 case BO_GE:
1685 case BO_EQ:
1686 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001687 case BO_AddAssign:
1688 case BO_SubAssign:
1689 case BO_AndAssign:
1690 case BO_OrAssign:
1691 case BO_XorAssign:
1692 case BO_MulAssign:
1693 case BO_DivAssign:
1694 case BO_RemAssign:
1695 case BO_ShlAssign:
1696 case BO_ShrAssign:
1697 case BO_Comma:
1698 llvm_unreachable("Unsupported atomic update operation");
1699 }
1700 auto *UpdateVal = Update.getScalarVal();
1701 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
1702 UpdateVal = CGF.Builder.CreateIntCast(
1703 IC, X.getAddress()->getType()->getPointerElementType(),
1704 X.getType()->hasSignedIntegerRepresentation());
1705 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001706 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getAddress(), UpdateVal, AO);
1707 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001708}
1709
Alexey Bataev5e018f92015-04-23 06:35:10 +00001710std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001711 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
1712 llvm::AtomicOrdering AO, SourceLocation Loc,
1713 const llvm::function_ref<RValue(RValue)> &CommonGen) {
1714 // Update expressions are allowed to have the following forms:
1715 // x binop= expr; -> xrval + expr;
1716 // x++, ++x -> xrval + 1;
1717 // x--, --x -> xrval - 1;
1718 // x = x binop expr; -> xrval binop expr
1719 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001720 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
1721 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001722 if (X.isGlobalReg()) {
1723 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
1724 // 'xrval'.
1725 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
1726 } else {
1727 // Perform compare-and-swap procedure.
1728 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00001729 }
1730 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001731 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001732}
1733
1734static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
1735 const Expr *X, const Expr *E,
1736 const Expr *UE, bool IsXLHSInRHSPart,
1737 SourceLocation Loc) {
1738 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1739 "Update expr in 'atomic update' must be a binary operator.");
1740 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1741 // Update expressions are allowed to have the following forms:
1742 // x binop= expr; -> xrval + expr;
1743 // x++, ++x -> xrval + 1;
1744 // x--, --x -> xrval - 1;
1745 // x = x binop expr; -> xrval binop expr
1746 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001747 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00001748 LValue XLValue = CGF.EmitLValue(X);
1749 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001750 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001751 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1752 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1753 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1754 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1755 auto Gen =
1756 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
1757 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1758 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1759 return CGF.EmitAnyExpr(UE);
1760 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00001761 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
1762 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1763 // OpenMP, 2.12.6, atomic Construct
1764 // Any atomic construct with a seq_cst clause forces the atomically
1765 // performed operation to include an implicit flush operation without a
1766 // list.
1767 if (IsSeqCst)
1768 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1769}
1770
1771static RValue convertToType(CodeGenFunction &CGF, RValue Value,
1772 QualType SourceType, QualType ResType) {
1773 switch (CGF.getEvaluationKind(ResType)) {
1774 case TEK_Scalar:
1775 return RValue::get(convertToScalarValue(CGF, Value, SourceType, ResType));
1776 case TEK_Complex: {
1777 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType);
1778 return RValue::getComplex(Res.first, Res.second);
1779 }
1780 case TEK_Aggregate:
1781 break;
1782 }
1783 llvm_unreachable("Must be a scalar or complex.");
1784}
1785
1786static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
1787 bool IsPostfixUpdate, const Expr *V,
1788 const Expr *X, const Expr *E,
1789 const Expr *UE, bool IsXLHSInRHSPart,
1790 SourceLocation Loc) {
1791 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
1792 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
1793 RValue NewVVal;
1794 LValue VLValue = CGF.EmitLValue(V);
1795 LValue XLValue = CGF.EmitLValue(X);
1796 RValue ExprRValue = CGF.EmitAnyExpr(E);
1797 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
1798 QualType NewVValType;
1799 if (UE) {
1800 // 'x' is updated with some additional value.
1801 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1802 "Update expr in 'atomic capture' must be a binary operator.");
1803 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1804 // Update expressions are allowed to have the following forms:
1805 // x binop= expr; -> xrval + expr;
1806 // x++, ++x -> xrval + 1;
1807 // x--, --x -> xrval - 1;
1808 // x = x binop expr; -> xrval binop expr
1809 // x = expr Op x; - > expr binop xrval;
1810 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1811 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1812 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1813 NewVValType = XRValExpr->getType();
1814 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1815 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
1816 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
1817 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1818 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1819 RValue Res = CGF.EmitAnyExpr(UE);
1820 NewVVal = IsPostfixUpdate ? XRValue : Res;
1821 return Res;
1822 };
1823 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1824 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1825 if (Res.first) {
1826 // 'atomicrmw' instruction was generated.
1827 if (IsPostfixUpdate) {
1828 // Use old value from 'atomicrmw'.
1829 NewVVal = Res.second;
1830 } else {
1831 // 'atomicrmw' does not provide new value, so evaluate it using old
1832 // value of 'x'.
1833 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1834 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
1835 NewVVal = CGF.EmitAnyExpr(UE);
1836 }
1837 }
1838 } else {
1839 // 'x' is simply rewritten with some 'expr'.
1840 NewVValType = X->getType().getNonReferenceType();
1841 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
1842 X->getType().getNonReferenceType());
1843 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
1844 NewVVal = XRValue;
1845 return ExprRValue;
1846 };
1847 // Try to perform atomicrmw xchg, otherwise simple exchange.
1848 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1849 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
1850 Loc, Gen);
1851 if (Res.first) {
1852 // 'atomicrmw' instruction was generated.
1853 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
1854 }
1855 }
1856 // Emit post-update store to 'v' of old/new 'x' value.
1857 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001858 // OpenMP, 2.12.6, atomic Construct
1859 // Any atomic construct with a seq_cst clause forces the atomically
1860 // performed operation to include an implicit flush operation without a
1861 // list.
1862 if (IsSeqCst)
1863 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1864}
1865
Alexey Bataevb57056f2015-01-22 06:17:56 +00001866static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00001867 bool IsSeqCst, bool IsPostfixUpdate,
1868 const Expr *X, const Expr *V, const Expr *E,
1869 const Expr *UE, bool IsXLHSInRHSPart,
1870 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001871 switch (Kind) {
1872 case OMPC_read:
1873 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
1874 break;
1875 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00001876 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
1877 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001878 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001879 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00001880 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
1881 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001882 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001883 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
1884 IsXLHSInRHSPart, Loc);
1885 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001886 case OMPC_if:
1887 case OMPC_final:
1888 case OMPC_num_threads:
1889 case OMPC_private:
1890 case OMPC_firstprivate:
1891 case OMPC_lastprivate:
1892 case OMPC_reduction:
1893 case OMPC_safelen:
1894 case OMPC_collapse:
1895 case OMPC_default:
1896 case OMPC_seq_cst:
1897 case OMPC_shared:
1898 case OMPC_linear:
1899 case OMPC_aligned:
1900 case OMPC_copyin:
1901 case OMPC_copyprivate:
1902 case OMPC_flush:
1903 case OMPC_proc_bind:
1904 case OMPC_schedule:
1905 case OMPC_ordered:
1906 case OMPC_nowait:
1907 case OMPC_untied:
1908 case OMPC_threadprivate:
1909 case OMPC_mergeable:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001910 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
1911 }
1912}
1913
1914void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
1915 bool IsSeqCst = S.getSingleClause(/*K=*/OMPC_seq_cst);
1916 OpenMPClauseKind Kind = OMPC_unknown;
1917 for (auto *C : S.clauses()) {
1918 // Find first clause (skip seq_cst clause, if it is first).
1919 if (C->getClauseKind() != OMPC_seq_cst) {
1920 Kind = C->getClauseKind();
1921 break;
1922 }
1923 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001924
1925 const auto *CS =
1926 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001927 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00001928 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001929 }
1930 // Processing for statements under 'atomic capture'.
1931 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
1932 for (const auto *C : Compound->body()) {
1933 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
1934 enterFullExpression(EWC);
1935 }
1936 }
1937 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001938
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001939 LexicalScope Scope(*this, S.getSourceRange());
1940 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00001941 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
1942 S.getV(), S.getExpr(), S.getUpdateExpr(),
1943 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001944 };
1945 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00001946}
1947
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001948void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) {
1949 llvm_unreachable("CodeGen for 'omp target' is not supported yet.");
1950}
1951
Alexey Bataev13314bf2014-10-09 04:18:56 +00001952void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
1953 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
1954}