blob: 130f080ef08fded00c272c9180630538230c039e [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();
135 if (OrigVD->getType()->isArrayType()) {
136 // Emit VarDecl with copy init for arrays.
137 // Get the address of the original variable captured in current
138 // captured region.
139 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
140 auto Emission = EmitAutoVarAlloca(*VD);
141 auto *Init = VD->getInit();
142 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
143 // Perform simple memcpy.
144 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
145 (*IRef)->getType());
146 } else {
147 EmitOMPAggregateAssign(
148 Emission.getAllocatedAddress(), OriginalAddr,
149 (*IRef)->getType(),
150 [this, VDInit, Init](llvm::Value *DestElement,
151 llvm::Value *SrcElement) {
152 // Clean up any temporaries needed by the initialization.
153 RunCleanupsScope InitScope(*this);
154 // Emit initialization for single element.
155 LocalDeclMap[VDInit] = SrcElement;
156 EmitAnyExprToMem(Init, DestElement,
157 Init->getType().getQualifiers(),
158 /*IsInitializer*/ false);
159 LocalDeclMap.erase(VDInit);
160 });
161 }
162 EmitAutoVarCleanups(Emission);
163 return Emission.getAllocatedAddress();
164 });
165 } else {
166 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
167 // Emit private VarDecl with copy init.
168 // Remap temp VDInit variable to the address of the original
169 // variable
170 // (for proper handling of captured global variables).
171 LocalDeclMap[VDInit] = OriginalAddr;
172 EmitDecl(*VD);
173 LocalDeclMap.erase(VDInit);
174 return GetAddrOfLocalVar(VD);
175 });
176 }
177 assert(IsRegistered &&
178 "firstprivate var already registered as private");
179 // Silence the warning about unused variable.
180 (void)IsRegistered;
181 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000182 ++IRef, ++InitsRef;
183 }
184 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000185 return !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000186}
187
Alexey Bataev03b340a2014-10-21 03:16:40 +0000188void CodeGenFunction::EmitOMPPrivateClause(
189 const OMPExecutableDirective &D,
190 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev50a64582015-04-22 12:24:45 +0000191 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000192 for (auto &&I = D.getClausesOfKind(OMPC_private); I; ++I) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000193 auto *C = cast<OMPPrivateClause>(*I);
194 auto IRef = C->varlist_begin();
195 for (auto IInit : C->private_copies()) {
196 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000197 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
198 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
199 bool IsRegistered =
200 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
201 // Emit private VarDecl with copy init.
202 EmitDecl(*VD);
203 return GetAddrOfLocalVar(VD);
204 });
205 assert(IsRegistered && "private var already registered as private");
206 // Silence the warning about unused variable.
207 (void)IsRegistered;
208 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000209 ++IRef;
210 }
211 }
212}
213
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000214bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
215 // threadprivate_var1 = master_threadprivate_var1;
216 // operator=(threadprivate_var2, master_threadprivate_var2);
217 // ...
218 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000219 llvm::DenseSet<const VarDecl *> CopiedVars;
220 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000221 for (auto &&I = D.getClausesOfKind(OMPC_copyin); I; ++I) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000222 auto *C = cast<OMPCopyinClause>(*I);
223 auto IRef = C->varlist_begin();
224 auto ISrcRef = C->source_exprs().begin();
225 auto IDestRef = C->destination_exprs().begin();
226 for (auto *AssignOp : C->assignment_ops()) {
227 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
228 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
229 // Get the address of the master variable.
230 auto *MasterAddr = VD->isStaticLocal()
231 ? CGM.getStaticLocalDeclAddress(VD)
232 : CGM.GetAddrOfGlobal(VD);
233 // Get the address of the threadprivate variable.
234 auto *PrivateAddr = EmitLValue(*IRef).getAddress();
235 if (CopiedVars.size() == 1) {
236 // At first check if current thread is a master thread. If it is, no
237 // need to copy data.
238 CopyBegin = createBasicBlock("copyin.not.master");
239 CopyEnd = createBasicBlock("copyin.not.master.end");
240 Builder.CreateCondBr(
241 Builder.CreateICmpNE(
242 Builder.CreatePtrToInt(MasterAddr, CGM.IntPtrTy),
243 Builder.CreatePtrToInt(PrivateAddr, CGM.IntPtrTy)),
244 CopyBegin, CopyEnd);
245 EmitBlock(CopyBegin);
246 }
247 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
248 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
249 EmitOMPCopy(*this, (*IRef)->getType(), PrivateAddr, MasterAddr, DestVD,
250 SrcVD, AssignOp);
251 }
252 ++IRef;
253 ++ISrcRef;
254 ++IDestRef;
255 }
256 }
257 if (CopyEnd) {
258 // Exit out of copying procedure for non-master thread.
259 EmitBlock(CopyEnd, /*IsFinished=*/true);
260 return true;
261 }
262 return false;
263}
264
Alexey Bataev38e89532015-04-16 04:54:05 +0000265bool CodeGenFunction::EmitOMPLastprivateClauseInit(
266 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000267 bool HasAtLeastOneLastprivate = false;
268 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000269 for (auto &&I = D.getClausesOfKind(OMPC_lastprivate); I; ++I) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000270 auto *C = cast<OMPLastprivateClause>(*I);
271 auto IRef = C->varlist_begin();
272 auto IDestRef = C->destination_exprs().begin();
273 for (auto *IInit : C->private_copies()) {
274 // Keep the address of the original variable for future update at the end
275 // of the loop.
276 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
277 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
278 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
279 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> llvm::Value *{
280 DeclRefExpr DRE(
281 const_cast<VarDecl *>(OrigVD),
282 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
283 OrigVD) != nullptr,
284 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
285 return EmitLValue(&DRE).getAddress();
286 });
287 // Check if the variable is also a firstprivate: in this case IInit is
288 // not generated. Initialization of this variable will happen in codegen
289 // for 'firstprivate' clause.
290 if (!IInit)
291 continue;
292 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
293 bool IsRegistered =
294 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
295 // Emit private VarDecl with copy init.
296 EmitDecl(*VD);
297 return GetAddrOfLocalVar(VD);
298 });
299 assert(IsRegistered && "lastprivate var already registered as private");
300 HasAtLeastOneLastprivate = HasAtLeastOneLastprivate || IsRegistered;
301 }
302 ++IRef, ++IDestRef;
303 }
304 }
305 return HasAtLeastOneLastprivate;
306}
307
308void CodeGenFunction::EmitOMPLastprivateClauseFinal(
309 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
310 // Emit following code:
311 // if (<IsLastIterCond>) {
312 // orig_var1 = private_orig_var1;
313 // ...
314 // orig_varn = private_orig_varn;
315 // }
316 auto *ThenBB = createBasicBlock(".omp.lastprivate.then");
317 auto *DoneBB = createBasicBlock(".omp.lastprivate.done");
318 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
319 EmitBlock(ThenBB);
320 {
Alexey Bataev38e89532015-04-16 04:54:05 +0000321 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000322 for (auto &&I = D.getClausesOfKind(OMPC_lastprivate); I; ++I) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000323 auto *C = cast<OMPLastprivateClause>(*I);
324 auto IRef = C->varlist_begin();
325 auto ISrcRef = C->source_exprs().begin();
326 auto IDestRef = C->destination_exprs().begin();
327 for (auto *AssignOp : C->assignment_ops()) {
328 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
329 if (AlreadyEmittedVars.insert(PrivateVD->getCanonicalDecl()).second) {
330 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
331 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
332 // Get the address of the original variable.
333 auto *OriginalAddr = GetAddrOfLocalVar(DestVD);
334 // Get the address of the private variable.
335 auto *PrivateAddr = GetAddrOfLocalVar(PrivateVD);
336 EmitOMPCopy(*this, (*IRef)->getType(), OriginalAddr, PrivateAddr,
337 DestVD, SrcVD, AssignOp);
338 }
339 ++IRef;
340 ++ISrcRef;
341 ++IDestRef;
342 }
343 }
344 }
345 EmitBlock(DoneBB, /*IsFinished=*/true);
346}
347
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000348void CodeGenFunction::EmitOMPReductionClauseInit(
349 const OMPExecutableDirective &D,
350 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataevc925aa32015-04-27 08:00:32 +0000351 for (auto &&I = D.getClausesOfKind(OMPC_reduction); I; ++I) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000352 auto *C = cast<OMPReductionClause>(*I);
353 auto ILHS = C->lhs_exprs().begin();
354 auto IRHS = C->rhs_exprs().begin();
355 for (auto IRef : C->varlists()) {
356 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
357 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
358 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
359 // Store the address of the original variable associated with the LHS
360 // implicit variable.
361 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> llvm::Value *{
362 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
363 CapturedStmtInfo->lookup(OrigVD) != nullptr,
364 IRef->getType(), VK_LValue, IRef->getExprLoc());
365 return EmitLValue(&DRE).getAddress();
366 });
367 // Emit reduction copy.
368 bool IsRegistered =
369 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> llvm::Value *{
370 // Emit private VarDecl with reduction init.
371 EmitDecl(*PrivateVD);
372 return GetAddrOfLocalVar(PrivateVD);
373 });
374 assert(IsRegistered && "private var already registered as private");
375 // Silence the warning about unused variable.
376 (void)IsRegistered;
377 ++ILHS, ++IRHS;
378 }
379 }
380}
381
382void CodeGenFunction::EmitOMPReductionClauseFinal(
383 const OMPExecutableDirective &D) {
384 llvm::SmallVector<const Expr *, 8> LHSExprs;
385 llvm::SmallVector<const Expr *, 8> RHSExprs;
386 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000387 bool HasAtLeastOneReduction = false;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000388 for (auto &&I = D.getClausesOfKind(OMPC_reduction); I; ++I) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000389 HasAtLeastOneReduction = true;
390 auto *C = cast<OMPReductionClause>(*I);
391 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
392 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
393 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
394 }
395 if (HasAtLeastOneReduction) {
396 // Emit nowait reduction if nowait clause is present or directive is a
397 // parallel directive (it always has implicit barrier).
398 CGM.getOpenMPRuntime().emitReduction(
399 *this, D.getLocEnd(), LHSExprs, RHSExprs, ReductionOps,
400 D.getSingleClause(OMPC_nowait) ||
401 isOpenMPParallelDirective(D.getDirectiveKind()));
402 }
403}
404
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000405static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
406 const OMPExecutableDirective &S,
407 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000408 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000409 auto CapturedStruct = CGF.GenerateCapturedStmtArgument(*CS);
410 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
411 S, *CS->getCapturedDecl()->param_begin(), CodeGen);
Alexey Bataev1d677132015-04-22 13:57:31 +0000412 if (auto C = S.getSingleClause(OMPC_num_threads)) {
413 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
414 auto NumThreadsClause = cast<OMPNumThreadsClause>(C);
415 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
416 /*IgnoreResultAssign*/ true);
417 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
418 CGF, NumThreads, NumThreadsClause->getLocStart());
419 }
420 const Expr *IfCond = nullptr;
421 if (auto C = S.getSingleClause(OMPC_if)) {
422 IfCond = cast<OMPIfClause>(C)->getCondition();
423 }
424 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
425 CapturedStruct, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000426}
427
428void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
429 LexicalScope Scope(*this, S.getSourceRange());
430 // Emit parallel region as a standalone region.
431 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
432 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000433 bool Copyins = CGF.EmitOMPCopyinClause(S);
434 bool Firstprivates = CGF.EmitOMPFirstprivateClause(S, PrivateScope);
435 if (Copyins || Firstprivates) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000436 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000437 // initialization of firstprivate variables or propagation master's thread
438 // values of threadprivate variables to local instances of that variables
439 // of all other implicit threads.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000440 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
441 OMPD_unknown);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000442 }
443 CGF.EmitOMPPrivateClause(S, PrivateScope);
444 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
445 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000446 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000447 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000448 // Emit implicit barrier at the end of the 'parallel' directive.
449 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
450 OMPD_unknown);
451 };
452 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +0000453}
Alexander Musman515ad8c2014-05-22 08:54:05 +0000454
Alexander Musmand196ef22014-10-07 08:57:09 +0000455void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &S,
Alexander Musmana5f070a2014-10-01 06:03:56 +0000456 bool SeparateIter) {
457 RunCleanupsScope BodyScope(*this);
458 // Update counters values on current iteration.
459 for (auto I : S.updates()) {
460 EmitIgnoredExpr(I);
461 }
Alexander Musman3276a272015-03-21 10:12:56 +0000462 // Update the linear variables.
Alexey Bataevc925aa32015-04-27 08:00:32 +0000463 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
464 auto *C = cast<OMPLinearClause>(*I);
Alexander Musman3276a272015-03-21 10:12:56 +0000465 for (auto U : C->updates()) {
466 EmitIgnoredExpr(U);
467 }
468 }
469
Alexander Musmana5f070a2014-10-01 06:03:56 +0000470 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +0000471 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000472 BreakContinueStack.push_back(BreakContinue(JumpDest(), Continue));
473 // Emit loop body.
474 EmitStmt(S.getBody());
475 // The end (updates/cleanups).
476 EmitBlock(Continue.getBlock());
477 BreakContinueStack.pop_back();
478 if (SeparateIter) {
479 // TODO: Update lastprivates if the SeparateIter flag is true.
480 // This will be implemented in a follow-up OMPLastprivateClause patch, but
481 // result should be still correct without it, as we do not make these
482 // variables private yet.
483 }
484}
485
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000486void CodeGenFunction::EmitOMPInnerLoop(
487 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
488 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000489 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
490 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +0000491 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000492
493 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +0000494 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000495 EmitBlock(CondBlock);
496 LoopStack.push(CondBlock);
497
498 // If there are any cleanups between here and the loop-exit scope,
499 // create a block to stage a loop exit along.
500 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +0000501 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +0000502 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000503
Alexander Musmand196ef22014-10-07 08:57:09 +0000504 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000505
Alexey Bataev2df54a02015-03-12 08:53:29 +0000506 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +0000507 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000508 if (ExitBlock != LoopExit.getBlock()) {
509 EmitBlock(ExitBlock);
510 EmitBranchThroughCleanup(LoopExit);
511 }
512
513 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +0000514 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000515
516 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +0000517 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000518 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
519
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000520 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000521
522 // Emit "IV = IV + 1" and a back-edge to the condition block.
523 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +0000524 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000525 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000526 BreakContinueStack.pop_back();
527 EmitBranch(CondBlock);
528 LoopStack.pop();
529 // Emit the fall-through block.
530 EmitBlock(LoopExit.getBlock());
531}
532
533void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &S) {
534 auto IC = S.counters().begin();
535 for (auto F : S.finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000536 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
537 if (LocalDeclMap.lookup(OrigVD)) {
538 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
539 CapturedStmtInfo->lookup(OrigVD) != nullptr,
540 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
541 auto *OrigAddr = EmitLValue(&DRE).getAddress();
542 OMPPrivateScope VarScope(*this);
543 VarScope.addPrivate(OrigVD,
544 [OrigAddr]() -> llvm::Value *{ return OrigAddr; });
545 (void)VarScope.Privatize();
Alexander Musmana5f070a2014-10-01 06:03:56 +0000546 EmitIgnoredExpr(F);
547 }
548 ++IC;
549 }
Alexander Musman3276a272015-03-21 10:12:56 +0000550 // Emit the final values of the linear variables.
Alexey Bataevc925aa32015-04-27 08:00:32 +0000551 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
552 auto *C = cast<OMPLinearClause>(*I);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000553 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +0000554 for (auto F : C->finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000555 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
556 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
557 CapturedStmtInfo->lookup(OrigVD) != nullptr,
558 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
559 auto *OrigAddr = EmitLValue(&DRE).getAddress();
560 OMPPrivateScope VarScope(*this);
561 VarScope.addPrivate(OrigVD,
562 [OrigAddr]() -> llvm::Value *{ return OrigAddr; });
563 (void)VarScope.Privatize();
Alexander Musman3276a272015-03-21 10:12:56 +0000564 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000565 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +0000566 }
567 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000568}
569
Alexander Musman09184fe2014-09-30 05:29:28 +0000570static void EmitOMPAlignedClause(CodeGenFunction &CGF, CodeGenModule &CGM,
571 const OMPAlignedClause &Clause) {
572 unsigned ClauseAlignment = 0;
573 if (auto AlignmentExpr = Clause.getAlignment()) {
574 auto AlignmentCI =
575 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
576 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
577 }
578 for (auto E : Clause.varlists()) {
579 unsigned Alignment = ClauseAlignment;
580 if (Alignment == 0) {
581 // OpenMP [2.8.1, Description]
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000582 // If no optional parameter is specified, implementation-defined default
Alexander Musman09184fe2014-09-30 05:29:28 +0000583 // alignments for SIMD instructions on the target platforms are assumed.
584 Alignment = CGM.getTargetCodeGenInfo().getOpenMPSimdDefaultAlignment(
585 E->getType());
586 }
587 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
588 "alignment is not power of 2");
589 if (Alignment != 0) {
590 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
591 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
592 }
593 }
594}
595
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000596static void EmitPrivateLoopCounters(CodeGenFunction &CGF,
597 CodeGenFunction::OMPPrivateScope &LoopScope,
598 ArrayRef<Expr *> Counters) {
599 for (auto *E : Counters) {
600 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev61114692015-04-28 13:20:05 +0000601 (void)LoopScope.addPrivate(VD, [&]() -> llvm::Value *{
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000602 // Emit var without initialization.
603 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
604 CGF.EmitAutoVarCleanups(VarEmission);
605 return VarEmission.getAllocatedAddress();
606 });
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000607 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000608}
609
Alexey Bataev62dbb972015-04-22 11:59:37 +0000610static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
611 const Expr *Cond, llvm::BasicBlock *TrueBlock,
612 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
613 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
614 EmitPrivateLoopCounters(CGF, PreCondScope, S.counters());
615 const VarDecl *IVDecl =
616 cast<VarDecl>(cast<DeclRefExpr>(S.getIterationVariable())->getDecl());
617 bool IsRegistered = PreCondScope.addPrivate(IVDecl, [&]() -> llvm::Value *{
618 // Emit var without initialization.
619 auto VarEmission = CGF.EmitAutoVarAlloca(*IVDecl);
620 CGF.EmitAutoVarCleanups(VarEmission);
621 return VarEmission.getAllocatedAddress();
622 });
623 assert(IsRegistered && "counter already registered as private");
624 // Silence the warning about unused variable.
625 (void)IsRegistered;
626 (void)PreCondScope.Privatize();
627 // Initialize internal counter to 0 to calculate initial values of real
628 // counters.
629 LValue IV = CGF.EmitLValue(S.getIterationVariable());
630 CGF.EmitStoreOfScalar(
631 llvm::ConstantInt::getNullValue(
632 IV.getAddress()->getType()->getPointerElementType()),
633 CGF.EmitLValue(S.getIterationVariable()), /*isInit=*/true);
634 // Get initial values of real counters.
635 for (auto I : S.updates()) {
636 CGF.EmitIgnoredExpr(I);
637 }
638 // Check that loop is executed at least one time.
639 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
640}
641
Alexander Musman3276a272015-03-21 10:12:56 +0000642static void
643EmitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
644 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataevc925aa32015-04-27 08:00:32 +0000645 for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) {
646 auto *C = cast<OMPLinearClause>(*I);
647 for (auto *E : C->varlists()) {
Alexander Musman3276a272015-03-21 10:12:56 +0000648 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
649 bool IsRegistered = PrivateScope.addPrivate(VD, [&]()->llvm::Value * {
650 // Emit var without initialization.
651 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
652 CGF.EmitAutoVarCleanups(VarEmission);
653 return VarEmission.getAllocatedAddress();
654 });
655 assert(IsRegistered && "linear var already registered as private");
656 // Silence the warning about unused variable.
657 (void)IsRegistered;
658 }
659 }
660}
661
Alexander Musman515ad8c2014-05-22 08:54:05 +0000662void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000663 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
664 // Pragma 'simd' code depends on presence of 'lastprivate'.
665 // If present, we have to separate last iteration of the loop:
666 //
Alexey Bataev62dbb972015-04-22 11:59:37 +0000667 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000668 // for (IV in 0..LastIteration-1) BODY;
669 // BODY with updates of lastprivate vars;
670 // <Final counter/linear vars updates>;
671 // }
672 //
673 // otherwise (when there's no lastprivate):
674 //
Alexey Bataev62dbb972015-04-22 11:59:37 +0000675 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000676 // for (IV in 0..LastIteration) BODY;
677 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000678 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000679 //
Alexander Musmana5f070a2014-10-01 06:03:56 +0000680
Alexey Bataev62dbb972015-04-22 11:59:37 +0000681 // Emit: if (PreCond) - begin.
682 // If the condition constant folds and can be elided, avoid emitting the
683 // whole loop.
684 bool CondConstant;
685 llvm::BasicBlock *ContBlock = nullptr;
686 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
687 if (!CondConstant)
688 return;
689 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000690 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
691 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +0000692 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
693 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +0000694 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +0000695 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000696 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000697 // Walk clauses and process safelen/lastprivate.
698 bool SeparateIter = false;
699 CGF.LoopStack.setParallel();
700 CGF.LoopStack.setVectorizerEnable(true);
701 for (auto C : S.clauses()) {
702 switch (C->getClauseKind()) {
703 case OMPC_safelen: {
704 RValue Len = CGF.EmitAnyExpr(cast<OMPSafelenClause>(C)->getSafelen(),
705 AggValueSlot::ignored(), true);
706 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
707 CGF.LoopStack.setVectorizerWidth(Val->getZExtValue());
708 // In presence of finite 'safelen', it may be unsafe to mark all
709 // the memory instructions parallel, because loop-carried
710 // dependences of 'safelen' iterations are possible.
711 CGF.LoopStack.setParallel(false);
712 break;
Alexander Musman3276a272015-03-21 10:12:56 +0000713 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000714 case OMPC_aligned:
715 EmitOMPAlignedClause(CGF, CGF.CGM, cast<OMPAlignedClause>(*C));
716 break;
717 case OMPC_lastprivate:
718 SeparateIter = true;
719 break;
720 default:
721 // Not handled yet
722 ;
723 }
724 }
Alexander Musman3276a272015-03-21 10:12:56 +0000725
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000726 // Emit inits for the linear variables.
Alexey Bataevc925aa32015-04-27 08:00:32 +0000727 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
728 auto *C = cast<OMPLinearClause>(*I);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000729 for (auto Init : C->inits()) {
730 auto *D = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
731 CGF.EmitVarDecl(*D);
732 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000733 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000734
735 // Emit the loop iteration variable.
736 const Expr *IVExpr = S.getIterationVariable();
737 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
738 CGF.EmitVarDecl(*IVDecl);
739 CGF.EmitIgnoredExpr(S.getInit());
740
741 // Emit the iterations count variable.
742 // If it is not a variable, Sema decided to calculate iterations count on
743 // each
744 // iteration (e.g., it is foldable into a constant).
745 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
746 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
747 // Emit calculation of the iterations count.
748 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000749 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000750
751 // Emit the linear steps for the linear clauses.
752 // If a step is not constant, it is pre-calculated before the loop.
Alexey Bataevc925aa32015-04-27 08:00:32 +0000753 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
754 auto *C = cast<OMPLinearClause>(*I);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000755 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
756 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
757 CGF.EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
758 // Emit calculation of the linear step.
759 CGF.EmitIgnoredExpr(CS);
760 }
761 }
762
Alexey Bataev62dbb972015-04-22 11:59:37 +0000763 {
764 OMPPrivateScope LoopScope(CGF);
765 EmitPrivateLoopCounters(CGF, LoopScope, S.counters());
766 EmitPrivateLinearVars(CGF, S, LoopScope);
767 CGF.EmitOMPPrivateClause(S, LoopScope);
768 (void)LoopScope.Privatize();
769 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
770 S.getCond(SeparateIter), S.getInc(),
771 [&S](CodeGenFunction &CGF) {
772 CGF.EmitOMPLoopBody(S);
773 CGF.EmitStopPoint(&S);
774 },
775 [](CodeGenFunction &) {});
776 if (SeparateIter) {
777 CGF.EmitOMPLoopBody(S, /*SeparateIter=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000778 }
Alexey Bataev62dbb972015-04-22 11:59:37 +0000779 }
780 CGF.EmitOMPSimdFinal(S);
781 // Emit: if (PreCond) - end.
782 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000783 CGF.EmitBranch(ContBlock);
784 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000785 }
786 };
787 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +0000788}
789
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000790void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
791 const OMPLoopDirective &S,
792 OMPPrivateScope &LoopScope,
793 llvm::Value *LB, llvm::Value *UB,
794 llvm::Value *ST, llvm::Value *IL,
795 llvm::Value *Chunk) {
796 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000797
798 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
799 const bool Dynamic = RT.isDynamic(ScheduleKind);
800
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000801 assert(!RT.isStaticNonchunked(ScheduleKind, /* Chunked */ Chunk != nullptr) &&
802 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000803
804 // Emit outer loop.
805 //
806 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +0000807 // When schedule(dynamic,chunk_size) is specified, the iterations are
808 // distributed to threads in the team in chunks as the threads request them.
809 // Each thread executes a chunk of iterations, then requests another chunk,
810 // until no chunks remain to be distributed. Each chunk contains chunk_size
811 // iterations, except for the last chunk to be distributed, which may have
812 // fewer iterations. When no chunk_size is specified, it defaults to 1.
813 //
814 // When schedule(guided,chunk_size) is specified, the iterations are assigned
815 // to threads in the team in chunks as the executing threads request them.
816 // Each thread executes a chunk of iterations, then requests another chunk,
817 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
818 // each chunk is proportional to the number of unassigned iterations divided
819 // by the number of threads in the team, decreasing to 1. For a chunk_size
820 // with value k (greater than 1), the size of each chunk is determined in the
821 // same way, with the restriction that the chunks do not contain fewer than k
822 // iterations (except for the last chunk to be assigned, which may have fewer
823 // than k iterations).
824 //
825 // When schedule(auto) is specified, the decision regarding scheduling is
826 // delegated to the compiler and/or runtime system. The programmer gives the
827 // implementation the freedom to choose any possible mapping of iterations to
828 // threads in the team.
829 //
830 // When schedule(runtime) is specified, the decision regarding scheduling is
831 // deferred until run time, and the schedule and chunk size are taken from the
832 // run-sched-var ICV. If the ICV is set to auto, the schedule is
833 // implementation defined
834 //
835 // while(__kmpc_dispatch_next(&LB, &UB)) {
836 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000837 // while (idx <= UB) { BODY; ++idx;
838 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
839 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +0000840 // }
841 //
842 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000843 // When schedule(static, chunk_size) is specified, iterations are divided into
844 // chunks of size chunk_size, and the chunks are assigned to the threads in
845 // the team in a round-robin fashion in the order of the thread number.
846 //
847 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
848 // while (idx <= UB) { BODY; ++idx; } // inner loop
849 // LB = LB + ST;
850 // UB = UB + ST;
851 // }
852 //
Alexander Musman92bdaab2015-03-12 13:37:50 +0000853
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000854 const Expr *IVExpr = S.getIterationVariable();
855 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
856 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
857
Alexander Musman92bdaab2015-03-12 13:37:50 +0000858 RT.emitForInit(
859 *this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, IL, LB,
860 (Dynamic ? EmitAnyExpr(S.getLastIteration()).getScalarVal() : UB), ST,
861 Chunk);
862
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000863 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
864
865 // Start the loop with a block that tests the condition.
866 auto CondBlock = createBasicBlock("omp.dispatch.cond");
867 EmitBlock(CondBlock);
868 LoopStack.push(CondBlock);
869
870 llvm::Value *BoolCondVal = nullptr;
Alexander Musman92bdaab2015-03-12 13:37:50 +0000871 if (!Dynamic) {
872 // UB = min(UB, GlobalUB)
873 EmitIgnoredExpr(S.getEnsureUpperBound());
874 // IV = LB
875 EmitIgnoredExpr(S.getInit());
876 // IV < UB
877 BoolCondVal = EvaluateExprAsBool(S.getCond(false));
878 } else {
879 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
880 IL, LB, UB, ST);
881 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000882
883 // If there are any cleanups between here and the loop-exit scope,
884 // create a block to stage a loop exit along.
885 auto ExitBlock = LoopExit.getBlock();
886 if (LoopScope.requiresCleanups())
887 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
888
889 auto LoopBody = createBasicBlock("omp.dispatch.body");
890 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
891 if (ExitBlock != LoopExit.getBlock()) {
892 EmitBlock(ExitBlock);
893 EmitBranchThroughCleanup(LoopExit);
894 }
895 EmitBlock(LoopBody);
896
Alexander Musman92bdaab2015-03-12 13:37:50 +0000897 // Emit "IV = LB" (in case of static schedule, we have already calculated new
898 // LB for loop condition and emitted it above).
899 if (Dynamic)
900 EmitIgnoredExpr(S.getInit());
901
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000902 // Create a block for the increment.
903 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
904 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
905
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000906 bool DynamicWithOrderedClause =
907 Dynamic && S.getSingleClause(OMPC_ordered) != nullptr;
908 SourceLocation Loc = S.getLocStart();
Alexey Bataev53223c92015-05-07 04:25:17 +0000909 // Generate !llvm.loop.parallel metadata for loads and stores for loops with
910 // dynamic/guided scheduling and without ordered clause.
911 LoopStack.setParallel((ScheduleKind == OMPC_SCHEDULE_dynamic ||
912 ScheduleKind == OMPC_SCHEDULE_guided) &&
913 !DynamicWithOrderedClause);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000914 EmitOMPInnerLoop(
915 S, LoopScope.requiresCleanups(), S.getCond(/*SeparateIter=*/false),
916 S.getInc(),
917 [&S](CodeGenFunction &CGF) {
918 CGF.EmitOMPLoopBody(S);
919 CGF.EmitStopPoint(&S);
920 },
921 [DynamicWithOrderedClause, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
922 if (DynamicWithOrderedClause) {
923 CGF.CGM.getOpenMPRuntime().emitForOrderedDynamicIterationEnd(
924 CGF, Loc, IVSize, IVSigned);
925 }
926 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000927
928 EmitBlock(Continue.getBlock());
929 BreakContinueStack.pop_back();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000930 if (!Dynamic) {
931 // Emit "LB = LB + Stride", "UB = UB + Stride".
932 EmitIgnoredExpr(S.getNextLowerBound());
933 EmitIgnoredExpr(S.getNextUpperBound());
934 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000935
936 EmitBranch(CondBlock);
937 LoopStack.pop();
938 // Emit the fall-through block.
939 EmitBlock(LoopExit.getBlock());
940
941 // Tell the runtime we are done.
Alexander Musman92bdaab2015-03-12 13:37:50 +0000942 if (!Dynamic)
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000943 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000944}
945
Alexander Musmanc6388682014-12-15 07:07:06 +0000946/// \brief Emit a helper variable and return corresponding lvalue.
947static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
948 const DeclRefExpr *Helper) {
949 auto VDecl = cast<VarDecl>(Helper->getDecl());
950 CGF.EmitVarDecl(*VDecl);
951 return CGF.EmitLValue(Helper);
952}
953
Alexey Bataev040d5402015-05-12 08:35:28 +0000954static std::pair<llvm::Value * /*Chunk*/, OpenMPScheduleClauseKind>
955emitScheduleClause(CodeGenFunction &CGF, const OMPLoopDirective &S,
956 bool OuterRegion) {
957 // Detect the loop schedule kind and chunk.
958 auto ScheduleKind = OMPC_SCHEDULE_unknown;
959 llvm::Value *Chunk = nullptr;
960 if (auto *C =
961 cast_or_null<OMPScheduleClause>(S.getSingleClause(OMPC_schedule))) {
962 ScheduleKind = C->getScheduleKind();
963 if (const auto *Ch = C->getChunkSize()) {
964 if (auto *ImpRef = cast_or_null<DeclRefExpr>(C->getHelperChunkSize())) {
965 if (OuterRegion) {
966 const VarDecl *ImpVar = cast<VarDecl>(ImpRef->getDecl());
967 CGF.EmitVarDecl(*ImpVar);
968 CGF.EmitStoreThroughLValue(
969 CGF.EmitAnyExpr(Ch),
970 CGF.MakeNaturalAlignAddrLValue(CGF.GetAddrOfLocalVar(ImpVar),
971 ImpVar->getType()));
972 } else {
973 Ch = ImpRef;
974 }
975 }
976 if (!C->getHelperChunkSize() || !OuterRegion) {
977 Chunk = CGF.EmitScalarExpr(Ch);
978 Chunk = CGF.EmitScalarConversion(Chunk, Ch->getType(),
979 S.getIterationVariable()->getType());
980 }
981 }
982 }
983 return std::make_pair(Chunk, ScheduleKind);
984}
985
Alexey Bataev38e89532015-04-16 04:54:05 +0000986bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +0000987 // Emit the loop iteration variable.
988 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
989 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
990 EmitVarDecl(*IVDecl);
991
992 // Emit the iterations count variable.
993 // If it is not a variable, Sema decided to calculate iterations count on each
994 // iteration (e.g., it is foldable into a constant).
995 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
996 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
997 // Emit calculation of the iterations count.
998 EmitIgnoredExpr(S.getCalcLastIteration());
999 }
1000
1001 auto &RT = CGM.getOpenMPRuntime();
1002
Alexey Bataev38e89532015-04-16 04:54:05 +00001003 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001004 // Check pre-condition.
1005 {
1006 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001007 // If the condition constant folds and can be elided, avoid emitting the
1008 // whole loop.
1009 bool CondConstant;
1010 llvm::BasicBlock *ContBlock = nullptr;
1011 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1012 if (!CondConstant)
1013 return false;
1014 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001015 auto *ThenBlock = createBasicBlock("omp.precond.then");
1016 ContBlock = createBasicBlock("omp.precond.end");
1017 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001018 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001019 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001020 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001021 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001022 // Emit 'then' code.
1023 {
1024 // Emit helper vars inits.
1025 LValue LB =
1026 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1027 LValue UB =
1028 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1029 LValue ST =
1030 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1031 LValue IL =
1032 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1033
1034 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001035 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1036 // Emit implicit barrier to synchronize threads and avoid data races on
1037 // initialization of firstprivate variables.
1038 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1039 OMPD_unknown);
1040 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001041 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001042 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001043 EmitOMPReductionClauseInit(S, LoopScope);
Alexander Musmanc6388682014-12-15 07:07:06 +00001044 EmitPrivateLoopCounters(*this, LoopScope, S.counters());
Alexander Musman7931b982015-03-16 07:14:41 +00001045 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001046
1047 // Detect the loop schedule kind and chunk.
Alexey Bataev040d5402015-05-12 08:35:28 +00001048 llvm::Value *Chunk;
1049 OpenMPScheduleClauseKind ScheduleKind;
1050 auto ScheduleInfo =
1051 emitScheduleClause(*this, S, /*OuterRegion=*/false);
1052 Chunk = ScheduleInfo.first;
1053 ScheduleKind = ScheduleInfo.second;
Alexander Musmanc6388682014-12-15 07:07:06 +00001054 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1055 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1056 if (RT.isStaticNonchunked(ScheduleKind,
1057 /* Chunked */ Chunk != nullptr)) {
1058 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1059 // When no chunk_size is specified, the iteration space is divided into
1060 // chunks that are approximately equal in size, and at most one chunk is
1061 // distributed to each thread. Note that the size of the chunks is
1062 // unspecified in this case.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001063 RT.emitForInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
1064 IL.getAddress(), LB.getAddress(), UB.getAddress(),
1065 ST.getAddress());
Alexander Musmanc6388682014-12-15 07:07:06 +00001066 // UB = min(UB, GlobalUB);
1067 EmitIgnoredExpr(S.getEnsureUpperBound());
1068 // IV = LB;
1069 EmitIgnoredExpr(S.getInit());
1070 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001071 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
1072 S.getCond(/*SeparateIter=*/false), S.getInc(),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001073 [&S](CodeGenFunction &CGF) {
1074 CGF.EmitOMPLoopBody(S);
1075 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001076 },
1077 [](CodeGenFunction &) {});
Alexander Musmanc6388682014-12-15 07:07:06 +00001078 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001079 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001080 } else {
1081 // Emit the outer loop, which requests its work chunk [LB..UB] from
1082 // runtime and runs the inner loop to process it.
1083 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, LB.getAddress(),
1084 UB.getAddress(), ST.getAddress(), IL.getAddress(),
1085 Chunk);
1086 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001087 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001088 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1089 if (HasLastprivateClause)
1090 EmitOMPLastprivateClauseFinal(
1091 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001092 }
1093 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001094 if (ContBlock) {
1095 EmitBranch(ContBlock);
1096 EmitBlock(ContBlock, true);
1097 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001098 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001099 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001100}
1101
1102void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001103 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev38e89532015-04-16 04:54:05 +00001104 bool HasLastprivates = false;
1105 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1106 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1107 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001108 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musmanc6388682014-12-15 07:07:06 +00001109
1110 // Emit an implicit barrier at the end.
Alexey Bataev38e89532015-04-16 04:54:05 +00001111 if (!S.getSingleClause(OMPC_nowait) || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001112 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1113 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001114}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001115
Alexander Musmanf82886e2014-09-18 05:12:34 +00001116void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &) {
1117 llvm_unreachable("CodeGen for 'omp for simd' is not supported yet.");
1118}
1119
Alexey Bataev2df54a02015-03-12 08:53:29 +00001120static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1121 const Twine &Name,
1122 llvm::Value *Init = nullptr) {
1123 auto LVal = CGF.MakeNaturalAlignAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
1124 if (Init)
1125 CGF.EmitScalarInit(Init, LVal);
1126 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001127}
1128
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001129static OpenMPDirectiveKind emitSections(CodeGenFunction &CGF,
1130 const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001131 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1132 auto *CS = dyn_cast<CompoundStmt>(Stmt);
1133 if (CS && CS->size() > 1) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001134 bool HasLastprivates = false;
1135 auto &&CodeGen = [&S, CS, &HasLastprivates](CodeGenFunction &CGF) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001136 auto &C = CGF.CGM.getContext();
1137 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1138 // Emit helper vars inits.
1139 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1140 CGF.Builder.getInt32(0));
1141 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
1142 LValue UB =
1143 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1144 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1145 CGF.Builder.getInt32(1));
1146 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1147 CGF.Builder.getInt32(0));
1148 // Loop counter.
1149 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1150 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001151 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001152 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001153 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001154 // Generate condition for loop.
1155 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1156 OK_Ordinary, S.getLocStart(),
1157 /*fpContractable=*/false);
1158 // Increment for loop counter.
1159 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
1160 OK_Ordinary, S.getLocStart());
1161 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
1162 // Iterate through all sections and emit a switch construct:
1163 // switch (IV) {
1164 // case 0:
1165 // <SectionStmt[0]>;
1166 // break;
1167 // ...
1168 // case <NumSection> - 1:
1169 // <SectionStmt[<NumSection> - 1]>;
1170 // break;
1171 // }
1172 // .omp.sections.exit:
1173 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1174 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1175 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1176 CS->size());
1177 unsigned CaseNumber = 0;
1178 for (auto C = CS->children(); C; ++C, ++CaseNumber) {
1179 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1180 CGF.EmitBlock(CaseBB);
1181 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
1182 CGF.EmitStmt(*C);
1183 CGF.EmitBranch(ExitBB);
1184 }
1185 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1186 };
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001187
1188 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1189 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
1190 // Emit implicit barrier to synchronize threads and avoid data races on
1191 // initialization of firstprivate variables.
1192 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1193 OMPD_unknown);
1194 }
Alexey Bataev73870832015-04-27 04:12:12 +00001195 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001196 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001197 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001198 (void)LoopScope.Privatize();
1199
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001200 // Emit static non-chunked loop.
1201 CGF.CGM.getOpenMPRuntime().emitForInit(
1202 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
1203 /*IVSigned=*/true, IL.getAddress(), LB.getAddress(), UB.getAddress(),
1204 ST.getAddress());
1205 // UB = min(UB, GlobalUB);
1206 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1207 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1208 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1209 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1210 // IV = LB;
1211 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1212 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001213 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1214 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001215 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001216 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataeva89adf22015-04-27 05:04:13 +00001217 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001218
1219 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1220 if (HasLastprivates)
1221 CGF.EmitOMPLastprivateClauseFinal(
1222 S, CGF.Builder.CreateIsNotNull(
1223 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev2df54a02015-03-12 08:53:29 +00001224 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001225
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001226 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, CodeGen);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001227 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1228 // clause. Otherwise the barrier will be generated by the codegen for the
1229 // directive.
1230 if (HasLastprivates && S.getSingleClause(OMPC_nowait)) {
1231 // Emit implicit barrier to synchronize threads and avoid data races on
1232 // initialization of firstprivate variables.
1233 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1234 OMPD_unknown);
1235 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001236 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001237 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001238 // If only one section is found - no need to generate loop, emit as a single
1239 // region.
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001240 bool HasFirstprivates;
Alexey Bataeva89adf22015-04-27 05:04:13 +00001241 // No need to generate reductions for sections with single section region, we
1242 // can use original shared variables for all operations.
Alexey Bataevc925aa32015-04-27 08:00:32 +00001243 bool HasReductions = !S.getClausesOfKind(OMPC_reduction).empty();
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001244 // No need to generate lastprivates for sections with single section region,
1245 // we can use original shared variable for all calculations with barrier at
1246 // the end of the sections.
Alexey Bataevc925aa32015-04-27 08:00:32 +00001247 bool HasLastprivates = !S.getClausesOfKind(OMPC_lastprivate).empty();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001248 auto &&CodeGen = [Stmt, &S, &HasFirstprivates](CodeGenFunction &CGF) {
1249 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1250 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev73870832015-04-27 04:12:12 +00001251 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001252 (void)SingleScope.Privatize();
1253
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001254 CGF.EmitStmt(Stmt);
1255 CGF.EnsureInsertPoint();
1256 };
1257 CGF.CGM.getOpenMPRuntime().emitSingleRegion(CGF, CodeGen, S.getLocStart(),
1258 llvm::None, llvm::None,
1259 llvm::None, llvm::None);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001260 // Emit barrier for firstprivates, lastprivates or reductions only if
1261 // 'sections' directive has 'nowait' clause. Otherwise the barrier will be
1262 // generated by the codegen for the directive.
1263 if ((HasFirstprivates || HasLastprivates || HasReductions) &&
1264 S.getSingleClause(OMPC_nowait)) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001265 // Emit implicit barrier to synchronize threads and avoid data races on
1266 // initialization of firstprivate variables.
1267 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1268 OMPD_unknown);
1269 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001270 return OMPD_single;
1271}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001272
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001273void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1274 LexicalScope Scope(*this, S.getSourceRange());
1275 OpenMPDirectiveKind EmittedAs = emitSections(*this, S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001276 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001277 if (!S.getSingleClause(OMPC_nowait)) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001278 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001279 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001280}
1281
1282void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001283 LexicalScope Scope(*this, S.getSourceRange());
1284 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1285 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1286 CGF.EnsureInsertPoint();
1287 };
1288 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001289}
1290
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001291void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001292 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001293 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001294 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001295 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001296 // Check if there are any 'copyprivate' clauses associated with this
1297 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001298 // construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001299 // Build a list of copyprivate variables along with helper expressions
1300 // (<source>, <destination>, <destination>=<source> expressions)
Alexey Bataevc925aa32015-04-27 08:00:32 +00001301 for (auto &&I = S.getClausesOfKind(OMPC_copyprivate); I; ++I) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001302 auto *C = cast<OMPCopyprivateClause>(*I);
1303 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001304 DestExprs.append(C->destination_exprs().begin(),
1305 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001306 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001307 AssignmentOps.append(C->assignment_ops().begin(),
1308 C->assignment_ops().end());
1309 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001310 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001311 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev5521d782015-04-24 04:21:15 +00001312 bool HasFirstprivates;
1313 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) {
1314 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1315 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev59c654a2015-04-27 03:48:52 +00001316 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev5521d782015-04-24 04:21:15 +00001317 (void)SingleScope.Privatize();
1318
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001319 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1320 CGF.EnsureInsertPoint();
1321 };
1322 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001323 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001324 AssignmentOps);
Alexey Bataev5521d782015-04-24 04:21:15 +00001325 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1326 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
1327 if ((!S.getSingleClause(OMPC_nowait) || HasFirstprivates) &&
1328 CopyprivateVars.empty()) {
1329 CGM.getOpenMPRuntime().emitBarrierCall(
1330 *this, S.getLocStart(),
1331 S.getSingleClause(OMPC_nowait) ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001332 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001333}
1334
Alexey Bataev8d690652014-12-04 07:23:53 +00001335void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001336 LexicalScope Scope(*this, S.getSourceRange());
1337 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1338 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1339 CGF.EnsureInsertPoint();
1340 };
1341 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001342}
1343
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001344void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001345 LexicalScope Scope(*this, S.getSourceRange());
1346 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1347 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1348 CGF.EnsureInsertPoint();
1349 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001350 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001351 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001352}
1353
Alexey Bataev671605e2015-04-13 05:28:11 +00001354void CodeGenFunction::EmitOMPParallelForDirective(
1355 const OMPParallelForDirective &S) {
1356 // Emit directive as a combined directive that consists of two implicit
1357 // directives: 'parallel' with 'for' directive.
1358 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev040d5402015-05-12 08:35:28 +00001359 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
Alexey Bataev671605e2015-04-13 05:28:11 +00001360 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1361 CGF.EmitOMPWorksharingLoop(S);
1362 // Emit implicit barrier at the end of parallel region, but this barrier
1363 // is at the end of 'for' directive, so emit it as the implicit barrier for
1364 // this 'for' directive.
1365 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1366 OMPD_parallel);
1367 };
1368 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001369}
1370
Alexander Musmane4e893b2014-09-23 09:33:00 +00001371void CodeGenFunction::EmitOMPParallelForSimdDirective(
1372 const OMPParallelForSimdDirective &) {
1373 llvm_unreachable("CodeGen for 'omp parallel for simd' is not supported yet.");
1374}
1375
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001376void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001377 const OMPParallelSectionsDirective &S) {
1378 // Emit directive as a combined directive that consists of two implicit
1379 // directives: 'parallel' with 'sections' directive.
1380 LexicalScope Scope(*this, S.getSourceRange());
1381 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1382 (void)emitSections(CGF, S);
1383 // Emit implicit barrier at the end of parallel region.
1384 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1385 OMPD_parallel);
1386 };
1387 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001388}
1389
Alexey Bataev62b63b12015-03-10 07:28:44 +00001390void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1391 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001392 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001393 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1394 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1395 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001396 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001397 // The first function argument for tasks is a thread id, the second one is a
1398 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001399 auto &&CodeGen = [PartId, &S](CodeGenFunction &CGF) {
1400 if (*PartId) {
1401 // TODO: emit code for untied tasks.
1402 }
1403 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1404 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00001405 auto OutlinedFn =
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001406 CGM.getOpenMPRuntime().emitTaskOutlinedFunction(S, *I, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001407 // Check if we should emit tied or untied task.
1408 bool Tied = !S.getSingleClause(OMPC_untied);
1409 // Check if the task is final
1410 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
1411 if (auto *Clause = S.getSingleClause(OMPC_final)) {
1412 // If the condition constant folds and can be elided, try to avoid emitting
1413 // the condition and the dead arm of the if/else.
1414 auto *Cond = cast<OMPFinalClause>(Clause)->getCondition();
1415 bool CondConstant;
1416 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1417 Final.setInt(CondConstant);
1418 else
1419 Final.setPointer(EvaluateExprAsBool(Cond));
1420 } else {
1421 // By default the task is not final.
1422 Final.setInt(/*IntVal=*/false);
1423 }
1424 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00001425 const Expr *IfCond = nullptr;
1426 if (auto C = S.getSingleClause(OMPC_if)) {
1427 IfCond = cast<OMPIfClause>(C)->getCondition();
1428 }
Alexey Bataev9e034042015-05-05 04:05:12 +00001429 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001430 // Get list of private variables.
1431 llvm::SmallVector<const Expr *, 8> Privates;
1432 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001433 for (auto &&I = S.getClausesOfKind(OMPC_private); I; ++I) {
1434 auto *C = cast<OMPPrivateClause>(*I);
1435 auto IRef = C->varlist_begin();
1436 for (auto *IInit : C->private_copies()) {
1437 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1438 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1439 Privates.push_back(*IRef);
1440 PrivateCopies.push_back(IInit);
1441 }
1442 ++IRef;
1443 }
1444 }
Alexey Bataev9e034042015-05-05 04:05:12 +00001445 EmittedAsPrivate.clear();
1446 // Get list of firstprivate variables.
1447 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
1448 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
1449 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
1450 for (auto &&I = S.getClausesOfKind(OMPC_firstprivate); I; ++I) {
1451 auto *C = cast<OMPFirstprivateClause>(*I);
1452 auto IRef = C->varlist_begin();
1453 auto IElemInitRef = C->inits().begin();
1454 for (auto *IInit : C->private_copies()) {
1455 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1456 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1457 FirstprivateVars.push_back(*IRef);
1458 FirstprivateCopies.push_back(IInit);
1459 FirstprivateInits.push_back(*IElemInitRef);
1460 }
1461 ++IRef, ++IElemInitRef;
1462 }
1463 }
1464 CGM.getOpenMPRuntime().emitTaskCall(
1465 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
1466 CapturedStruct, IfCond, Privates, PrivateCopies, FirstprivateVars,
1467 FirstprivateCopies, FirstprivateInits);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001468}
1469
Alexey Bataev9f797f32015-02-05 05:57:51 +00001470void CodeGenFunction::EmitOMPTaskyieldDirective(
1471 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001472 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001473}
1474
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001475void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001476 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001477}
1478
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001479void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
1480 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00001481}
1482
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001483void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001484 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
1485 if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) {
1486 auto FlushClause = cast<OMPFlushClause>(C);
1487 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1488 FlushClause->varlist_end());
1489 }
1490 return llvm::None;
1491 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00001492}
1493
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001494void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
1495 LexicalScope Scope(*this, S.getSourceRange());
1496 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1497 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1498 CGF.EnsureInsertPoint();
1499 };
1500 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001501}
1502
Alexey Bataevb57056f2015-01-22 06:17:56 +00001503static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
1504 QualType SrcType, QualType DestType) {
1505 assert(CGF.hasScalarEvaluationKind(DestType) &&
1506 "DestType must have scalar evaluation kind.");
1507 assert(!Val.isAggregate() && "Must be a scalar or complex.");
1508 return Val.isScalar()
1509 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType)
1510 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
1511 DestType);
1512}
1513
1514static CodeGenFunction::ComplexPairTy
1515convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
1516 QualType DestType) {
1517 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
1518 "DestType must have complex evaluation kind.");
1519 CodeGenFunction::ComplexPairTy ComplexVal;
1520 if (Val.isScalar()) {
1521 // Convert the input element to the element type of the complex.
1522 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1523 auto ScalarVal =
1524 CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestElementType);
1525 ComplexVal = CodeGenFunction::ComplexPairTy(
1526 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
1527 } else {
1528 assert(Val.isComplex() && "Must be a scalar or complex.");
1529 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
1530 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1531 ComplexVal.first = CGF.EmitScalarConversion(
1532 Val.getComplexVal().first, SrcElementType, DestElementType);
1533 ComplexVal.second = CGF.EmitScalarConversion(
1534 Val.getComplexVal().second, SrcElementType, DestElementType);
1535 }
1536 return ComplexVal;
1537}
1538
Alexey Bataev5e018f92015-04-23 06:35:10 +00001539static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
1540 LValue LVal, RValue RVal) {
1541 if (LVal.isGlobalReg()) {
1542 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
1543 } else {
1544 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
1545 : llvm::Monotonic,
1546 LVal.isVolatile(), /*IsInit=*/false);
1547 }
1548}
1549
1550static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal,
1551 QualType RValTy) {
1552 switch (CGF.getEvaluationKind(LVal.getType())) {
1553 case TEK_Scalar:
1554 CGF.EmitStoreThroughLValue(
1555 RValue::get(convertToScalarValue(CGF, RVal, RValTy, LVal.getType())),
1556 LVal);
1557 break;
1558 case TEK_Complex:
1559 CGF.EmitStoreOfComplex(
1560 convertToComplexValue(CGF, RVal, RValTy, LVal.getType()), LVal,
1561 /*isInit=*/false);
1562 break;
1563 case TEK_Aggregate:
1564 llvm_unreachable("Must be a scalar or complex.");
1565 }
1566}
1567
Alexey Bataevb57056f2015-01-22 06:17:56 +00001568static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
1569 const Expr *X, const Expr *V,
1570 SourceLocation Loc) {
1571 // v = x;
1572 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
1573 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
1574 LValue XLValue = CGF.EmitLValue(X);
1575 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00001576 RValue Res = XLValue.isGlobalReg()
1577 ? CGF.EmitLoadOfLValue(XLValue, Loc)
1578 : CGF.EmitAtomicLoad(XLValue, Loc,
1579 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00001580 : llvm::Monotonic,
1581 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001582 // OpenMP, 2.12.6, atomic Construct
1583 // Any atomic construct with a seq_cst clause forces the atomically
1584 // performed operation to include an implicit flush operation without a
1585 // list.
1586 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001587 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001588 emitSimpleStore(CGF,VLValue, Res, X->getType().getNonReferenceType());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001589}
1590
Alexey Bataevb8329262015-02-27 06:33:30 +00001591static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
1592 const Expr *X, const Expr *E,
1593 SourceLocation Loc) {
1594 // x = expr;
1595 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00001596 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00001597 // OpenMP, 2.12.6, atomic Construct
1598 // Any atomic construct with a seq_cst clause forces the atomically
1599 // performed operation to include an implicit flush operation without a
1600 // list.
1601 if (IsSeqCst)
1602 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1603}
1604
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00001605static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
1606 RValue Update,
1607 BinaryOperatorKind BO,
1608 llvm::AtomicOrdering AO,
1609 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001610 auto &Context = CGF.CGM.getContext();
1611 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00001612 // expression is simple and atomic is allowed for the given type for the
1613 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001614 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00001615 !Update.getScalarVal()->getType()->isIntegerTy() ||
1616 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
1617 (Update.getScalarVal()->getType() !=
1618 X.getAddress()->getType()->getPointerElementType())) ||
1619 !X.getAddress()->getType()->getPointerElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001620 !Context.getTargetInfo().hasBuiltinAtomic(
1621 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00001622 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001623
1624 llvm::AtomicRMWInst::BinOp RMWOp;
1625 switch (BO) {
1626 case BO_Add:
1627 RMWOp = llvm::AtomicRMWInst::Add;
1628 break;
1629 case BO_Sub:
1630 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00001631 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001632 RMWOp = llvm::AtomicRMWInst::Sub;
1633 break;
1634 case BO_And:
1635 RMWOp = llvm::AtomicRMWInst::And;
1636 break;
1637 case BO_Or:
1638 RMWOp = llvm::AtomicRMWInst::Or;
1639 break;
1640 case BO_Xor:
1641 RMWOp = llvm::AtomicRMWInst::Xor;
1642 break;
1643 case BO_LT:
1644 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1645 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
1646 : llvm::AtomicRMWInst::Max)
1647 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
1648 : llvm::AtomicRMWInst::UMax);
1649 break;
1650 case BO_GT:
1651 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1652 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
1653 : llvm::AtomicRMWInst::Min)
1654 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
1655 : llvm::AtomicRMWInst::UMin);
1656 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001657 case BO_Assign:
1658 RMWOp = llvm::AtomicRMWInst::Xchg;
1659 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001660 case BO_Mul:
1661 case BO_Div:
1662 case BO_Rem:
1663 case BO_Shl:
1664 case BO_Shr:
1665 case BO_LAnd:
1666 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001667 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001668 case BO_PtrMemD:
1669 case BO_PtrMemI:
1670 case BO_LE:
1671 case BO_GE:
1672 case BO_EQ:
1673 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001674 case BO_AddAssign:
1675 case BO_SubAssign:
1676 case BO_AndAssign:
1677 case BO_OrAssign:
1678 case BO_XorAssign:
1679 case BO_MulAssign:
1680 case BO_DivAssign:
1681 case BO_RemAssign:
1682 case BO_ShlAssign:
1683 case BO_ShrAssign:
1684 case BO_Comma:
1685 llvm_unreachable("Unsupported atomic update operation");
1686 }
1687 auto *UpdateVal = Update.getScalarVal();
1688 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
1689 UpdateVal = CGF.Builder.CreateIntCast(
1690 IC, X.getAddress()->getType()->getPointerElementType(),
1691 X.getType()->hasSignedIntegerRepresentation());
1692 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001693 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getAddress(), UpdateVal, AO);
1694 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001695}
1696
Alexey Bataev5e018f92015-04-23 06:35:10 +00001697std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001698 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
1699 llvm::AtomicOrdering AO, SourceLocation Loc,
1700 const llvm::function_ref<RValue(RValue)> &CommonGen) {
1701 // Update expressions are allowed to have the following forms:
1702 // x binop= expr; -> xrval + expr;
1703 // x++, ++x -> xrval + 1;
1704 // x--, --x -> xrval - 1;
1705 // x = x binop expr; -> xrval binop expr
1706 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001707 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
1708 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001709 if (X.isGlobalReg()) {
1710 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
1711 // 'xrval'.
1712 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
1713 } else {
1714 // Perform compare-and-swap procedure.
1715 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00001716 }
1717 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001718 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001719}
1720
1721static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
1722 const Expr *X, const Expr *E,
1723 const Expr *UE, bool IsXLHSInRHSPart,
1724 SourceLocation Loc) {
1725 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1726 "Update expr in 'atomic update' must be a binary operator.");
1727 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1728 // Update expressions are allowed to have the following forms:
1729 // x binop= expr; -> xrval + expr;
1730 // x++, ++x -> xrval + 1;
1731 // x--, --x -> xrval - 1;
1732 // x = x binop expr; -> xrval binop expr
1733 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001734 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00001735 LValue XLValue = CGF.EmitLValue(X);
1736 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001737 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001738 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1739 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1740 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1741 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1742 auto Gen =
1743 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
1744 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1745 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1746 return CGF.EmitAnyExpr(UE);
1747 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00001748 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
1749 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1750 // OpenMP, 2.12.6, atomic Construct
1751 // Any atomic construct with a seq_cst clause forces the atomically
1752 // performed operation to include an implicit flush operation without a
1753 // list.
1754 if (IsSeqCst)
1755 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1756}
1757
1758static RValue convertToType(CodeGenFunction &CGF, RValue Value,
1759 QualType SourceType, QualType ResType) {
1760 switch (CGF.getEvaluationKind(ResType)) {
1761 case TEK_Scalar:
1762 return RValue::get(convertToScalarValue(CGF, Value, SourceType, ResType));
1763 case TEK_Complex: {
1764 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType);
1765 return RValue::getComplex(Res.first, Res.second);
1766 }
1767 case TEK_Aggregate:
1768 break;
1769 }
1770 llvm_unreachable("Must be a scalar or complex.");
1771}
1772
1773static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
1774 bool IsPostfixUpdate, const Expr *V,
1775 const Expr *X, const Expr *E,
1776 const Expr *UE, bool IsXLHSInRHSPart,
1777 SourceLocation Loc) {
1778 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
1779 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
1780 RValue NewVVal;
1781 LValue VLValue = CGF.EmitLValue(V);
1782 LValue XLValue = CGF.EmitLValue(X);
1783 RValue ExprRValue = CGF.EmitAnyExpr(E);
1784 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
1785 QualType NewVValType;
1786 if (UE) {
1787 // 'x' is updated with some additional value.
1788 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1789 "Update expr in 'atomic capture' must be a binary operator.");
1790 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1791 // Update expressions are allowed to have the following forms:
1792 // x binop= expr; -> xrval + expr;
1793 // x++, ++x -> xrval + 1;
1794 // x--, --x -> xrval - 1;
1795 // x = x binop expr; -> xrval binop expr
1796 // x = expr Op x; - > expr binop xrval;
1797 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1798 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1799 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1800 NewVValType = XRValExpr->getType();
1801 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1802 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
1803 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
1804 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1805 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1806 RValue Res = CGF.EmitAnyExpr(UE);
1807 NewVVal = IsPostfixUpdate ? XRValue : Res;
1808 return Res;
1809 };
1810 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1811 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1812 if (Res.first) {
1813 // 'atomicrmw' instruction was generated.
1814 if (IsPostfixUpdate) {
1815 // Use old value from 'atomicrmw'.
1816 NewVVal = Res.second;
1817 } else {
1818 // 'atomicrmw' does not provide new value, so evaluate it using old
1819 // value of 'x'.
1820 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1821 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
1822 NewVVal = CGF.EmitAnyExpr(UE);
1823 }
1824 }
1825 } else {
1826 // 'x' is simply rewritten with some 'expr'.
1827 NewVValType = X->getType().getNonReferenceType();
1828 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
1829 X->getType().getNonReferenceType());
1830 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
1831 NewVVal = XRValue;
1832 return ExprRValue;
1833 };
1834 // Try to perform atomicrmw xchg, otherwise simple exchange.
1835 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1836 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
1837 Loc, Gen);
1838 if (Res.first) {
1839 // 'atomicrmw' instruction was generated.
1840 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
1841 }
1842 }
1843 // Emit post-update store to 'v' of old/new 'x' value.
1844 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001845 // OpenMP, 2.12.6, atomic Construct
1846 // Any atomic construct with a seq_cst clause forces the atomically
1847 // performed operation to include an implicit flush operation without a
1848 // list.
1849 if (IsSeqCst)
1850 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1851}
1852
Alexey Bataevb57056f2015-01-22 06:17:56 +00001853static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00001854 bool IsSeqCst, bool IsPostfixUpdate,
1855 const Expr *X, const Expr *V, const Expr *E,
1856 const Expr *UE, bool IsXLHSInRHSPart,
1857 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001858 switch (Kind) {
1859 case OMPC_read:
1860 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
1861 break;
1862 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00001863 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
1864 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001865 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001866 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00001867 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
1868 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001869 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001870 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
1871 IsXLHSInRHSPart, Loc);
1872 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001873 case OMPC_if:
1874 case OMPC_final:
1875 case OMPC_num_threads:
1876 case OMPC_private:
1877 case OMPC_firstprivate:
1878 case OMPC_lastprivate:
1879 case OMPC_reduction:
1880 case OMPC_safelen:
1881 case OMPC_collapse:
1882 case OMPC_default:
1883 case OMPC_seq_cst:
1884 case OMPC_shared:
1885 case OMPC_linear:
1886 case OMPC_aligned:
1887 case OMPC_copyin:
1888 case OMPC_copyprivate:
1889 case OMPC_flush:
1890 case OMPC_proc_bind:
1891 case OMPC_schedule:
1892 case OMPC_ordered:
1893 case OMPC_nowait:
1894 case OMPC_untied:
1895 case OMPC_threadprivate:
1896 case OMPC_mergeable:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001897 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
1898 }
1899}
1900
1901void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
1902 bool IsSeqCst = S.getSingleClause(/*K=*/OMPC_seq_cst);
1903 OpenMPClauseKind Kind = OMPC_unknown;
1904 for (auto *C : S.clauses()) {
1905 // Find first clause (skip seq_cst clause, if it is first).
1906 if (C->getClauseKind() != OMPC_seq_cst) {
1907 Kind = C->getClauseKind();
1908 break;
1909 }
1910 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001911
1912 const auto *CS =
1913 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001914 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00001915 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001916 }
1917 // Processing for statements under 'atomic capture'.
1918 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
1919 for (const auto *C : Compound->body()) {
1920 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
1921 enterFullExpression(EWC);
1922 }
1923 }
1924 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001925
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001926 LexicalScope Scope(*this, S.getSourceRange());
1927 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00001928 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
1929 S.getV(), S.getExpr(), S.getUpdateExpr(),
1930 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001931 };
1932 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00001933}
1934
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001935void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) {
1936 llvm_unreachable("CodeGen for 'omp target' is not supported yet.");
1937}
1938
Alexey Bataev13314bf2014-10-09 04:18:56 +00001939void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
1940 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
1941}