blob: 5305db8fd21f56a4bf6a481a0c7ec57c28ed680e [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) {
117 auto FirstprivateFilter = [](const OMPClause *C) -> bool {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000118 return C->getClauseKind() == OMPC_firstprivate;
119 };
Alexey Bataev69c62a92015-04-15 04:52:20 +0000120 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
121 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
122 FirstprivateFilter)> I(D.clauses(), FirstprivateFilter);
123 I; ++I) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000124 auto *C = cast<OMPFirstprivateClause>(*I);
125 auto IRef = C->varlist_begin();
126 auto InitsRef = C->inits().begin();
127 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000128 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000129 if (EmittedAsFirstprivate.count(OrigVD) == 0) {
130 EmittedAsFirstprivate.insert(OrigVD);
131 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
132 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
133 bool IsRegistered;
134 DeclRefExpr DRE(
135 const_cast<VarDecl *>(OrigVD),
136 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
137 OrigVD) != nullptr,
138 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
139 auto *OriginalAddr = EmitLValue(&DRE).getAddress();
140 if (OrigVD->getType()->isArrayType()) {
141 // Emit VarDecl with copy init for arrays.
142 // Get the address of the original variable captured in current
143 // captured region.
144 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
145 auto Emission = EmitAutoVarAlloca(*VD);
146 auto *Init = VD->getInit();
147 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
148 // Perform simple memcpy.
149 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
150 (*IRef)->getType());
151 } else {
152 EmitOMPAggregateAssign(
153 Emission.getAllocatedAddress(), OriginalAddr,
154 (*IRef)->getType(),
155 [this, VDInit, Init](llvm::Value *DestElement,
156 llvm::Value *SrcElement) {
157 // Clean up any temporaries needed by the initialization.
158 RunCleanupsScope InitScope(*this);
159 // Emit initialization for single element.
160 LocalDeclMap[VDInit] = SrcElement;
161 EmitAnyExprToMem(Init, DestElement,
162 Init->getType().getQualifiers(),
163 /*IsInitializer*/ false);
164 LocalDeclMap.erase(VDInit);
165 });
166 }
167 EmitAutoVarCleanups(Emission);
168 return Emission.getAllocatedAddress();
169 });
170 } else {
171 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
172 // Emit private VarDecl with copy init.
173 // Remap temp VDInit variable to the address of the original
174 // variable
175 // (for proper handling of captured global variables).
176 LocalDeclMap[VDInit] = OriginalAddr;
177 EmitDecl(*VD);
178 LocalDeclMap.erase(VDInit);
179 return GetAddrOfLocalVar(VD);
180 });
181 }
182 assert(IsRegistered &&
183 "firstprivate var already registered as private");
184 // Silence the warning about unused variable.
185 (void)IsRegistered;
186 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000187 ++IRef, ++InitsRef;
188 }
189 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000190 return !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000191}
192
Alexey Bataev03b340a2014-10-21 03:16:40 +0000193void CodeGenFunction::EmitOMPPrivateClause(
194 const OMPExecutableDirective &D,
195 CodeGenFunction::OMPPrivateScope &PrivateScope) {
196 auto PrivateFilter = [](const OMPClause *C) -> bool {
197 return C->getClauseKind() == OMPC_private;
198 };
Alexey Bataev50a64582015-04-22 12:24:45 +0000199 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000200 for (OMPExecutableDirective::filtered_clause_iterator<decltype(PrivateFilter)>
Alexey Bataev50a64582015-04-22 12:24:45 +0000201 I(D.clauses(), PrivateFilter);
202 I; ++I) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000203 auto *C = cast<OMPPrivateClause>(*I);
204 auto IRef = C->varlist_begin();
205 for (auto IInit : C->private_copies()) {
206 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000207 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
208 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
209 bool IsRegistered =
210 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
211 // Emit private VarDecl with copy init.
212 EmitDecl(*VD);
213 return GetAddrOfLocalVar(VD);
214 });
215 assert(IsRegistered && "private var already registered as private");
216 // Silence the warning about unused variable.
217 (void)IsRegistered;
218 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000219 ++IRef;
220 }
221 }
222}
223
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000224bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
225 // threadprivate_var1 = master_threadprivate_var1;
226 // operator=(threadprivate_var2, master_threadprivate_var2);
227 // ...
228 // __kmpc_barrier(&loc, global_tid);
229 auto CopyinFilter = [](const OMPClause *C) -> bool {
230 return C->getClauseKind() == OMPC_copyin;
231 };
232 llvm::DenseSet<const VarDecl *> CopiedVars;
233 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
234 for (OMPExecutableDirective::filtered_clause_iterator<decltype(CopyinFilter)>
235 I(D.clauses(), CopyinFilter);
236 I; ++I) {
237 auto *C = cast<OMPCopyinClause>(*I);
238 auto IRef = C->varlist_begin();
239 auto ISrcRef = C->source_exprs().begin();
240 auto IDestRef = C->destination_exprs().begin();
241 for (auto *AssignOp : C->assignment_ops()) {
242 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
243 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
244 // Get the address of the master variable.
245 auto *MasterAddr = VD->isStaticLocal()
246 ? CGM.getStaticLocalDeclAddress(VD)
247 : CGM.GetAddrOfGlobal(VD);
248 // Get the address of the threadprivate variable.
249 auto *PrivateAddr = EmitLValue(*IRef).getAddress();
250 if (CopiedVars.size() == 1) {
251 // At first check if current thread is a master thread. If it is, no
252 // need to copy data.
253 CopyBegin = createBasicBlock("copyin.not.master");
254 CopyEnd = createBasicBlock("copyin.not.master.end");
255 Builder.CreateCondBr(
256 Builder.CreateICmpNE(
257 Builder.CreatePtrToInt(MasterAddr, CGM.IntPtrTy),
258 Builder.CreatePtrToInt(PrivateAddr, CGM.IntPtrTy)),
259 CopyBegin, CopyEnd);
260 EmitBlock(CopyBegin);
261 }
262 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
263 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
264 EmitOMPCopy(*this, (*IRef)->getType(), PrivateAddr, MasterAddr, DestVD,
265 SrcVD, AssignOp);
266 }
267 ++IRef;
268 ++ISrcRef;
269 ++IDestRef;
270 }
271 }
272 if (CopyEnd) {
273 // Exit out of copying procedure for non-master thread.
274 EmitBlock(CopyEnd, /*IsFinished=*/true);
275 return true;
276 }
277 return false;
278}
279
Alexey Bataev38e89532015-04-16 04:54:05 +0000280bool CodeGenFunction::EmitOMPLastprivateClauseInit(
281 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
282 auto LastprivateFilter = [](const OMPClause *C) -> bool {
283 return C->getClauseKind() == OMPC_lastprivate;
284 };
285 bool HasAtLeastOneLastprivate = false;
286 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
287 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
288 LastprivateFilter)> I(D.clauses(), LastprivateFilter);
289 I; ++I) {
290 auto *C = cast<OMPLastprivateClause>(*I);
291 auto IRef = C->varlist_begin();
292 auto IDestRef = C->destination_exprs().begin();
293 for (auto *IInit : C->private_copies()) {
294 // Keep the address of the original variable for future update at the end
295 // of the loop.
296 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
297 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
298 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
299 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> llvm::Value *{
300 DeclRefExpr DRE(
301 const_cast<VarDecl *>(OrigVD),
302 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
303 OrigVD) != nullptr,
304 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
305 return EmitLValue(&DRE).getAddress();
306 });
307 // Check if the variable is also a firstprivate: in this case IInit is
308 // not generated. Initialization of this variable will happen in codegen
309 // for 'firstprivate' clause.
310 if (!IInit)
311 continue;
312 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
313 bool IsRegistered =
314 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
315 // Emit private VarDecl with copy init.
316 EmitDecl(*VD);
317 return GetAddrOfLocalVar(VD);
318 });
319 assert(IsRegistered && "lastprivate var already registered as private");
320 HasAtLeastOneLastprivate = HasAtLeastOneLastprivate || IsRegistered;
321 }
322 ++IRef, ++IDestRef;
323 }
324 }
325 return HasAtLeastOneLastprivate;
326}
327
328void CodeGenFunction::EmitOMPLastprivateClauseFinal(
329 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
330 // Emit following code:
331 // if (<IsLastIterCond>) {
332 // orig_var1 = private_orig_var1;
333 // ...
334 // orig_varn = private_orig_varn;
335 // }
336 auto *ThenBB = createBasicBlock(".omp.lastprivate.then");
337 auto *DoneBB = createBasicBlock(".omp.lastprivate.done");
338 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
339 EmitBlock(ThenBB);
340 {
341 auto LastprivateFilter = [](const OMPClause *C) -> bool {
342 return C->getClauseKind() == OMPC_lastprivate;
343 };
344 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
345 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
346 LastprivateFilter)> I(D.clauses(), LastprivateFilter);
347 I; ++I) {
348 auto *C = cast<OMPLastprivateClause>(*I);
349 auto IRef = C->varlist_begin();
350 auto ISrcRef = C->source_exprs().begin();
351 auto IDestRef = C->destination_exprs().begin();
352 for (auto *AssignOp : C->assignment_ops()) {
353 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
354 if (AlreadyEmittedVars.insert(PrivateVD->getCanonicalDecl()).second) {
355 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
356 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
357 // Get the address of the original variable.
358 auto *OriginalAddr = GetAddrOfLocalVar(DestVD);
359 // Get the address of the private variable.
360 auto *PrivateAddr = GetAddrOfLocalVar(PrivateVD);
361 EmitOMPCopy(*this, (*IRef)->getType(), OriginalAddr, PrivateAddr,
362 DestVD, SrcVD, AssignOp);
363 }
364 ++IRef;
365 ++ISrcRef;
366 ++IDestRef;
367 }
368 }
369 }
370 EmitBlock(DoneBB, /*IsFinished=*/true);
371}
372
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000373void CodeGenFunction::EmitOMPReductionClauseInit(
374 const OMPExecutableDirective &D,
375 CodeGenFunction::OMPPrivateScope &PrivateScope) {
376 auto ReductionFilter = [](const OMPClause *C) -> bool {
377 return C->getClauseKind() == OMPC_reduction;
378 };
379 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
380 ReductionFilter)> I(D.clauses(), ReductionFilter);
381 I; ++I) {
382 auto *C = cast<OMPReductionClause>(*I);
383 auto ILHS = C->lhs_exprs().begin();
384 auto IRHS = C->rhs_exprs().begin();
385 for (auto IRef : C->varlists()) {
386 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
387 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
388 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
389 // Store the address of the original variable associated with the LHS
390 // implicit variable.
391 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> llvm::Value *{
392 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
393 CapturedStmtInfo->lookup(OrigVD) != nullptr,
394 IRef->getType(), VK_LValue, IRef->getExprLoc());
395 return EmitLValue(&DRE).getAddress();
396 });
397 // Emit reduction copy.
398 bool IsRegistered =
399 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> llvm::Value *{
400 // Emit private VarDecl with reduction init.
401 EmitDecl(*PrivateVD);
402 return GetAddrOfLocalVar(PrivateVD);
403 });
404 assert(IsRegistered && "private var already registered as private");
405 // Silence the warning about unused variable.
406 (void)IsRegistered;
407 ++ILHS, ++IRHS;
408 }
409 }
410}
411
412void CodeGenFunction::EmitOMPReductionClauseFinal(
413 const OMPExecutableDirective &D) {
414 llvm::SmallVector<const Expr *, 8> LHSExprs;
415 llvm::SmallVector<const Expr *, 8> RHSExprs;
416 llvm::SmallVector<const Expr *, 8> ReductionOps;
417 auto ReductionFilter = [](const OMPClause *C) -> bool {
418 return C->getClauseKind() == OMPC_reduction;
419 };
420 bool HasAtLeastOneReduction = false;
421 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
422 ReductionFilter)> I(D.clauses(), ReductionFilter);
423 I; ++I) {
424 HasAtLeastOneReduction = true;
425 auto *C = cast<OMPReductionClause>(*I);
426 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
427 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
428 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
429 }
430 if (HasAtLeastOneReduction) {
431 // Emit nowait reduction if nowait clause is present or directive is a
432 // parallel directive (it always has implicit barrier).
433 CGM.getOpenMPRuntime().emitReduction(
434 *this, D.getLocEnd(), LHSExprs, RHSExprs, ReductionOps,
435 D.getSingleClause(OMPC_nowait) ||
436 isOpenMPParallelDirective(D.getDirectiveKind()));
437 }
438}
439
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000440static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
441 const OMPExecutableDirective &S,
442 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000443 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000444 auto CapturedStruct = CGF.GenerateCapturedStmtArgument(*CS);
445 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
446 S, *CS->getCapturedDecl()->param_begin(), CodeGen);
Alexey Bataev1d677132015-04-22 13:57:31 +0000447 if (auto C = S.getSingleClause(OMPC_num_threads)) {
448 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
449 auto NumThreadsClause = cast<OMPNumThreadsClause>(C);
450 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
451 /*IgnoreResultAssign*/ true);
452 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
453 CGF, NumThreads, NumThreadsClause->getLocStart());
454 }
455 const Expr *IfCond = nullptr;
456 if (auto C = S.getSingleClause(OMPC_if)) {
457 IfCond = cast<OMPIfClause>(C)->getCondition();
458 }
459 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
460 CapturedStruct, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000461}
462
463void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
464 LexicalScope Scope(*this, S.getSourceRange());
465 // Emit parallel region as a standalone region.
466 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
467 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000468 bool Copyins = CGF.EmitOMPCopyinClause(S);
469 bool Firstprivates = CGF.EmitOMPFirstprivateClause(S, PrivateScope);
470 if (Copyins || Firstprivates) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000471 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000472 // initialization of firstprivate variables or propagation master's thread
473 // values of threadprivate variables to local instances of that variables
474 // of all other implicit threads.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000475 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
476 OMPD_unknown);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000477 }
478 CGF.EmitOMPPrivateClause(S, PrivateScope);
479 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
480 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000481 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000482 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000483 // Emit implicit barrier at the end of the 'parallel' directive.
484 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
485 OMPD_unknown);
486 };
487 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +0000488}
Alexander Musman515ad8c2014-05-22 08:54:05 +0000489
Alexander Musmand196ef22014-10-07 08:57:09 +0000490void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &S,
Alexander Musmana5f070a2014-10-01 06:03:56 +0000491 bool SeparateIter) {
492 RunCleanupsScope BodyScope(*this);
493 // Update counters values on current iteration.
494 for (auto I : S.updates()) {
495 EmitIgnoredExpr(I);
496 }
Alexander Musman3276a272015-03-21 10:12:56 +0000497 // Update the linear variables.
498 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
499 for (auto U : C->updates()) {
500 EmitIgnoredExpr(U);
501 }
502 }
503
Alexander Musmana5f070a2014-10-01 06:03:56 +0000504 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +0000505 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000506 BreakContinueStack.push_back(BreakContinue(JumpDest(), Continue));
507 // Emit loop body.
508 EmitStmt(S.getBody());
509 // The end (updates/cleanups).
510 EmitBlock(Continue.getBlock());
511 BreakContinueStack.pop_back();
512 if (SeparateIter) {
513 // TODO: Update lastprivates if the SeparateIter flag is true.
514 // This will be implemented in a follow-up OMPLastprivateClause patch, but
515 // result should be still correct without it, as we do not make these
516 // variables private yet.
517 }
518}
519
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000520void CodeGenFunction::EmitOMPInnerLoop(
521 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
522 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000523 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
524 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +0000525 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000526
527 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +0000528 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000529 EmitBlock(CondBlock);
530 LoopStack.push(CondBlock);
531
532 // If there are any cleanups between here and the loop-exit scope,
533 // create a block to stage a loop exit along.
534 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +0000535 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +0000536 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000537
Alexander Musmand196ef22014-10-07 08:57:09 +0000538 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000539
Alexey Bataev2df54a02015-03-12 08:53:29 +0000540 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +0000541 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000542 if (ExitBlock != LoopExit.getBlock()) {
543 EmitBlock(ExitBlock);
544 EmitBranchThroughCleanup(LoopExit);
545 }
546
547 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +0000548 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000549
550 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +0000551 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000552 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
553
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000554 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000555
556 // Emit "IV = IV + 1" and a back-edge to the condition block.
557 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +0000558 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000559 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000560 BreakContinueStack.pop_back();
561 EmitBranch(CondBlock);
562 LoopStack.pop();
563 // Emit the fall-through block.
564 EmitBlock(LoopExit.getBlock());
565}
566
567void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &S) {
568 auto IC = S.counters().begin();
569 for (auto F : S.finals()) {
570 if (LocalDeclMap.lookup(cast<DeclRefExpr>((*IC))->getDecl())) {
571 EmitIgnoredExpr(F);
572 }
573 ++IC;
574 }
Alexander Musman3276a272015-03-21 10:12:56 +0000575 // Emit the final values of the linear variables.
576 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
577 for (auto F : C->finals()) {
578 EmitIgnoredExpr(F);
579 }
580 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000581}
582
Alexander Musman09184fe2014-09-30 05:29:28 +0000583static void EmitOMPAlignedClause(CodeGenFunction &CGF, CodeGenModule &CGM,
584 const OMPAlignedClause &Clause) {
585 unsigned ClauseAlignment = 0;
586 if (auto AlignmentExpr = Clause.getAlignment()) {
587 auto AlignmentCI =
588 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
589 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
590 }
591 for (auto E : Clause.varlists()) {
592 unsigned Alignment = ClauseAlignment;
593 if (Alignment == 0) {
594 // OpenMP [2.8.1, Description]
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000595 // If no optional parameter is specified, implementation-defined default
Alexander Musman09184fe2014-09-30 05:29:28 +0000596 // alignments for SIMD instructions on the target platforms are assumed.
597 Alignment = CGM.getTargetCodeGenInfo().getOpenMPSimdDefaultAlignment(
598 E->getType());
599 }
600 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
601 "alignment is not power of 2");
602 if (Alignment != 0) {
603 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
604 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
605 }
606 }
607}
608
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000609static void EmitPrivateLoopCounters(CodeGenFunction &CGF,
610 CodeGenFunction::OMPPrivateScope &LoopScope,
611 ArrayRef<Expr *> Counters) {
612 for (auto *E : Counters) {
613 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
614 bool IsRegistered = LoopScope.addPrivate(VD, [&]() -> llvm::Value * {
615 // Emit var without initialization.
616 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
617 CGF.EmitAutoVarCleanups(VarEmission);
618 return VarEmission.getAllocatedAddress();
619 });
620 assert(IsRegistered && "counter already registered as private");
621 // Silence the warning about unused variable.
622 (void)IsRegistered;
623 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000624}
625
Alexey Bataev62dbb972015-04-22 11:59:37 +0000626static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
627 const Expr *Cond, llvm::BasicBlock *TrueBlock,
628 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
629 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
630 EmitPrivateLoopCounters(CGF, PreCondScope, S.counters());
631 const VarDecl *IVDecl =
632 cast<VarDecl>(cast<DeclRefExpr>(S.getIterationVariable())->getDecl());
633 bool IsRegistered = PreCondScope.addPrivate(IVDecl, [&]() -> llvm::Value *{
634 // Emit var without initialization.
635 auto VarEmission = CGF.EmitAutoVarAlloca(*IVDecl);
636 CGF.EmitAutoVarCleanups(VarEmission);
637 return VarEmission.getAllocatedAddress();
638 });
639 assert(IsRegistered && "counter already registered as private");
640 // Silence the warning about unused variable.
641 (void)IsRegistered;
642 (void)PreCondScope.Privatize();
643 // Initialize internal counter to 0 to calculate initial values of real
644 // counters.
645 LValue IV = CGF.EmitLValue(S.getIterationVariable());
646 CGF.EmitStoreOfScalar(
647 llvm::ConstantInt::getNullValue(
648 IV.getAddress()->getType()->getPointerElementType()),
649 CGF.EmitLValue(S.getIterationVariable()), /*isInit=*/true);
650 // Get initial values of real counters.
651 for (auto I : S.updates()) {
652 CGF.EmitIgnoredExpr(I);
653 }
654 // Check that loop is executed at least one time.
655 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
656}
657
Alexander Musman3276a272015-03-21 10:12:56 +0000658static void
659EmitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
660 CodeGenFunction::OMPPrivateScope &PrivateScope) {
661 for (auto Clause : OMPExecutableDirective::linear_filter(D.clauses())) {
662 for (auto *E : Clause->varlists()) {
663 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
664 bool IsRegistered = PrivateScope.addPrivate(VD, [&]()->llvm::Value * {
665 // Emit var without initialization.
666 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
667 CGF.EmitAutoVarCleanups(VarEmission);
668 return VarEmission.getAllocatedAddress();
669 });
670 assert(IsRegistered && "linear var already registered as private");
671 // Silence the warning about unused variable.
672 (void)IsRegistered;
673 }
674 }
675}
676
Alexander Musman515ad8c2014-05-22 08:54:05 +0000677void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000678 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
679 // Pragma 'simd' code depends on presence of 'lastprivate'.
680 // If present, we have to separate last iteration of the loop:
681 //
Alexey Bataev62dbb972015-04-22 11:59:37 +0000682 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000683 // for (IV in 0..LastIteration-1) BODY;
684 // BODY with updates of lastprivate vars;
685 // <Final counter/linear vars updates>;
686 // }
687 //
688 // otherwise (when there's no lastprivate):
689 //
Alexey Bataev62dbb972015-04-22 11:59:37 +0000690 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000691 // for (IV in 0..LastIteration) BODY;
692 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000693 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000694 //
Alexander Musmana5f070a2014-10-01 06:03:56 +0000695
Alexey Bataev62dbb972015-04-22 11:59:37 +0000696 // Emit: if (PreCond) - begin.
697 // If the condition constant folds and can be elided, avoid emitting the
698 // whole loop.
699 bool CondConstant;
700 llvm::BasicBlock *ContBlock = nullptr;
701 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
702 if (!CondConstant)
703 return;
704 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000705 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
706 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +0000707 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
708 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +0000709 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +0000710 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000711 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000712 // Walk clauses and process safelen/lastprivate.
713 bool SeparateIter = false;
714 CGF.LoopStack.setParallel();
715 CGF.LoopStack.setVectorizerEnable(true);
716 for (auto C : S.clauses()) {
717 switch (C->getClauseKind()) {
718 case OMPC_safelen: {
719 RValue Len = CGF.EmitAnyExpr(cast<OMPSafelenClause>(C)->getSafelen(),
720 AggValueSlot::ignored(), true);
721 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
722 CGF.LoopStack.setVectorizerWidth(Val->getZExtValue());
723 // In presence of finite 'safelen', it may be unsafe to mark all
724 // the memory instructions parallel, because loop-carried
725 // dependences of 'safelen' iterations are possible.
726 CGF.LoopStack.setParallel(false);
727 break;
Alexander Musman3276a272015-03-21 10:12:56 +0000728 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000729 case OMPC_aligned:
730 EmitOMPAlignedClause(CGF, CGF.CGM, cast<OMPAlignedClause>(*C));
731 break;
732 case OMPC_lastprivate:
733 SeparateIter = true;
734 break;
735 default:
736 // Not handled yet
737 ;
738 }
739 }
Alexander Musman3276a272015-03-21 10:12:56 +0000740
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000741 // Emit inits for the linear variables.
742 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
743 for (auto Init : C->inits()) {
744 auto *D = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
745 CGF.EmitVarDecl(*D);
746 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000747 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000748
749 // Emit the loop iteration variable.
750 const Expr *IVExpr = S.getIterationVariable();
751 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
752 CGF.EmitVarDecl(*IVDecl);
753 CGF.EmitIgnoredExpr(S.getInit());
754
755 // Emit the iterations count variable.
756 // If it is not a variable, Sema decided to calculate iterations count on
757 // each
758 // iteration (e.g., it is foldable into a constant).
759 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
760 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
761 // Emit calculation of the iterations count.
762 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000763 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000764
765 // Emit the linear steps for the linear clauses.
766 // If a step is not constant, it is pre-calculated before the loop.
767 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
768 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
769 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
770 CGF.EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
771 // Emit calculation of the linear step.
772 CGF.EmitIgnoredExpr(CS);
773 }
774 }
775
Alexey Bataev62dbb972015-04-22 11:59:37 +0000776 {
777 OMPPrivateScope LoopScope(CGF);
778 EmitPrivateLoopCounters(CGF, LoopScope, S.counters());
779 EmitPrivateLinearVars(CGF, S, LoopScope);
780 CGF.EmitOMPPrivateClause(S, LoopScope);
781 (void)LoopScope.Privatize();
782 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
783 S.getCond(SeparateIter), S.getInc(),
784 [&S](CodeGenFunction &CGF) {
785 CGF.EmitOMPLoopBody(S);
786 CGF.EmitStopPoint(&S);
787 },
788 [](CodeGenFunction &) {});
789 if (SeparateIter) {
790 CGF.EmitOMPLoopBody(S, /*SeparateIter=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000791 }
Alexey Bataev62dbb972015-04-22 11:59:37 +0000792 }
793 CGF.EmitOMPSimdFinal(S);
794 // Emit: if (PreCond) - end.
795 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000796 CGF.EmitBranch(ContBlock);
797 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000798 }
799 };
800 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +0000801}
802
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000803void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
804 const OMPLoopDirective &S,
805 OMPPrivateScope &LoopScope,
806 llvm::Value *LB, llvm::Value *UB,
807 llvm::Value *ST, llvm::Value *IL,
808 llvm::Value *Chunk) {
809 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000810
811 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
812 const bool Dynamic = RT.isDynamic(ScheduleKind);
813
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000814 assert(!RT.isStaticNonchunked(ScheduleKind, /* Chunked */ Chunk != nullptr) &&
815 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000816
817 // Emit outer loop.
818 //
819 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +0000820 // When schedule(dynamic,chunk_size) is specified, the iterations are
821 // distributed to threads in the team in chunks as the threads request them.
822 // Each thread executes a chunk of iterations, then requests another chunk,
823 // until no chunks remain to be distributed. Each chunk contains chunk_size
824 // iterations, except for the last chunk to be distributed, which may have
825 // fewer iterations. When no chunk_size is specified, it defaults to 1.
826 //
827 // When schedule(guided,chunk_size) is specified, the iterations are assigned
828 // to threads in the team in chunks as the executing threads request them.
829 // Each thread executes a chunk of iterations, then requests another chunk,
830 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
831 // each chunk is proportional to the number of unassigned iterations divided
832 // by the number of threads in the team, decreasing to 1. For a chunk_size
833 // with value k (greater than 1), the size of each chunk is determined in the
834 // same way, with the restriction that the chunks do not contain fewer than k
835 // iterations (except for the last chunk to be assigned, which may have fewer
836 // than k iterations).
837 //
838 // When schedule(auto) is specified, the decision regarding scheduling is
839 // delegated to the compiler and/or runtime system. The programmer gives the
840 // implementation the freedom to choose any possible mapping of iterations to
841 // threads in the team.
842 //
843 // When schedule(runtime) is specified, the decision regarding scheduling is
844 // deferred until run time, and the schedule and chunk size are taken from the
845 // run-sched-var ICV. If the ICV is set to auto, the schedule is
846 // implementation defined
847 //
848 // while(__kmpc_dispatch_next(&LB, &UB)) {
849 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000850 // while (idx <= UB) { BODY; ++idx;
851 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
852 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +0000853 // }
854 //
855 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000856 // When schedule(static, chunk_size) is specified, iterations are divided into
857 // chunks of size chunk_size, and the chunks are assigned to the threads in
858 // the team in a round-robin fashion in the order of the thread number.
859 //
860 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
861 // while (idx <= UB) { BODY; ++idx; } // inner loop
862 // LB = LB + ST;
863 // UB = UB + ST;
864 // }
865 //
Alexander Musman92bdaab2015-03-12 13:37:50 +0000866
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000867 const Expr *IVExpr = S.getIterationVariable();
868 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
869 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
870
Alexander Musman92bdaab2015-03-12 13:37:50 +0000871 RT.emitForInit(
872 *this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, IL, LB,
873 (Dynamic ? EmitAnyExpr(S.getLastIteration()).getScalarVal() : UB), ST,
874 Chunk);
875
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000876 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
877
878 // Start the loop with a block that tests the condition.
879 auto CondBlock = createBasicBlock("omp.dispatch.cond");
880 EmitBlock(CondBlock);
881 LoopStack.push(CondBlock);
882
883 llvm::Value *BoolCondVal = nullptr;
Alexander Musman92bdaab2015-03-12 13:37:50 +0000884 if (!Dynamic) {
885 // UB = min(UB, GlobalUB)
886 EmitIgnoredExpr(S.getEnsureUpperBound());
887 // IV = LB
888 EmitIgnoredExpr(S.getInit());
889 // IV < UB
890 BoolCondVal = EvaluateExprAsBool(S.getCond(false));
891 } else {
892 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
893 IL, LB, UB, ST);
894 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000895
896 // If there are any cleanups between here and the loop-exit scope,
897 // create a block to stage a loop exit along.
898 auto ExitBlock = LoopExit.getBlock();
899 if (LoopScope.requiresCleanups())
900 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
901
902 auto LoopBody = createBasicBlock("omp.dispatch.body");
903 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
904 if (ExitBlock != LoopExit.getBlock()) {
905 EmitBlock(ExitBlock);
906 EmitBranchThroughCleanup(LoopExit);
907 }
908 EmitBlock(LoopBody);
909
Alexander Musman92bdaab2015-03-12 13:37:50 +0000910 // Emit "IV = LB" (in case of static schedule, we have already calculated new
911 // LB for loop condition and emitted it above).
912 if (Dynamic)
913 EmitIgnoredExpr(S.getInit());
914
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000915 // Create a block for the increment.
916 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
917 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
918
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000919 bool DynamicWithOrderedClause =
920 Dynamic && S.getSingleClause(OMPC_ordered) != nullptr;
921 SourceLocation Loc = S.getLocStart();
922 EmitOMPInnerLoop(
923 S, LoopScope.requiresCleanups(), S.getCond(/*SeparateIter=*/false),
924 S.getInc(),
925 [&S](CodeGenFunction &CGF) {
926 CGF.EmitOMPLoopBody(S);
927 CGF.EmitStopPoint(&S);
928 },
929 [DynamicWithOrderedClause, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
930 if (DynamicWithOrderedClause) {
931 CGF.CGM.getOpenMPRuntime().emitForOrderedDynamicIterationEnd(
932 CGF, Loc, IVSize, IVSigned);
933 }
934 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000935
936 EmitBlock(Continue.getBlock());
937 BreakContinueStack.pop_back();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000938 if (!Dynamic) {
939 // Emit "LB = LB + Stride", "UB = UB + Stride".
940 EmitIgnoredExpr(S.getNextLowerBound());
941 EmitIgnoredExpr(S.getNextUpperBound());
942 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000943
944 EmitBranch(CondBlock);
945 LoopStack.pop();
946 // Emit the fall-through block.
947 EmitBlock(LoopExit.getBlock());
948
949 // Tell the runtime we are done.
Alexander Musman92bdaab2015-03-12 13:37:50 +0000950 if (!Dynamic)
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000951 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000952}
953
Alexander Musmanc6388682014-12-15 07:07:06 +0000954/// \brief Emit a helper variable and return corresponding lvalue.
955static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
956 const DeclRefExpr *Helper) {
957 auto VDecl = cast<VarDecl>(Helper->getDecl());
958 CGF.EmitVarDecl(*VDecl);
959 return CGF.EmitLValue(Helper);
960}
961
Alexey Bataev38e89532015-04-16 04:54:05 +0000962bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +0000963 // Emit the loop iteration variable.
964 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
965 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
966 EmitVarDecl(*IVDecl);
967
968 // Emit the iterations count variable.
969 // If it is not a variable, Sema decided to calculate iterations count on each
970 // iteration (e.g., it is foldable into a constant).
971 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
972 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
973 // Emit calculation of the iterations count.
974 EmitIgnoredExpr(S.getCalcLastIteration());
975 }
976
977 auto &RT = CGM.getOpenMPRuntime();
978
Alexey Bataev38e89532015-04-16 04:54:05 +0000979 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +0000980 // Check pre-condition.
981 {
982 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +0000983 // If the condition constant folds and can be elided, avoid emitting the
984 // whole loop.
985 bool CondConstant;
986 llvm::BasicBlock *ContBlock = nullptr;
987 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
988 if (!CondConstant)
989 return false;
990 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000991 auto *ThenBlock = createBasicBlock("omp.precond.then");
992 ContBlock = createBasicBlock("omp.precond.end");
993 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +0000994 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +0000995 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +0000996 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000997 }
Alexander Musmanc6388682014-12-15 07:07:06 +0000998 // Emit 'then' code.
999 {
1000 // Emit helper vars inits.
1001 LValue LB =
1002 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1003 LValue UB =
1004 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1005 LValue ST =
1006 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1007 LValue IL =
1008 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1009
1010 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001011 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1012 // Emit implicit barrier to synchronize threads and avoid data races on
1013 // initialization of firstprivate variables.
1014 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1015 OMPD_unknown);
1016 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001017 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001018 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001019 EmitOMPReductionClauseInit(S, LoopScope);
Alexander Musmanc6388682014-12-15 07:07:06 +00001020 EmitPrivateLoopCounters(*this, LoopScope, S.counters());
Alexander Musman7931b982015-03-16 07:14:41 +00001021 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001022
1023 // Detect the loop schedule kind and chunk.
1024 auto ScheduleKind = OMPC_SCHEDULE_unknown;
1025 llvm::Value *Chunk = nullptr;
1026 if (auto C = cast_or_null<OMPScheduleClause>(
1027 S.getSingleClause(OMPC_schedule))) {
1028 ScheduleKind = C->getScheduleKind();
1029 if (auto Ch = C->getChunkSize()) {
1030 Chunk = EmitScalarExpr(Ch);
1031 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
1032 S.getIterationVariable()->getType());
1033 }
1034 }
1035 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1036 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1037 if (RT.isStaticNonchunked(ScheduleKind,
1038 /* Chunked */ Chunk != nullptr)) {
1039 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1040 // When no chunk_size is specified, the iteration space is divided into
1041 // chunks that are approximately equal in size, and at most one chunk is
1042 // distributed to each thread. Note that the size of the chunks is
1043 // unspecified in this case.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001044 RT.emitForInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
1045 IL.getAddress(), LB.getAddress(), UB.getAddress(),
1046 ST.getAddress());
Alexander Musmanc6388682014-12-15 07:07:06 +00001047 // UB = min(UB, GlobalUB);
1048 EmitIgnoredExpr(S.getEnsureUpperBound());
1049 // IV = LB;
1050 EmitIgnoredExpr(S.getInit());
1051 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001052 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
1053 S.getCond(/*SeparateIter=*/false), S.getInc(),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001054 [&S](CodeGenFunction &CGF) {
1055 CGF.EmitOMPLoopBody(S);
1056 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001057 },
1058 [](CodeGenFunction &) {});
Alexander Musmanc6388682014-12-15 07:07:06 +00001059 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001060 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001061 } else {
1062 // Emit the outer loop, which requests its work chunk [LB..UB] from
1063 // runtime and runs the inner loop to process it.
1064 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, LB.getAddress(),
1065 UB.getAddress(), ST.getAddress(), IL.getAddress(),
1066 Chunk);
1067 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001068 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001069 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1070 if (HasLastprivateClause)
1071 EmitOMPLastprivateClauseFinal(
1072 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001073 }
1074 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001075 if (ContBlock) {
1076 EmitBranch(ContBlock);
1077 EmitBlock(ContBlock, true);
1078 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001079 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001080 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001081}
1082
1083void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001084 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev38e89532015-04-16 04:54:05 +00001085 bool HasLastprivates = false;
1086 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1087 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1088 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001089 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musmanc6388682014-12-15 07:07:06 +00001090
1091 // Emit an implicit barrier at the end.
Alexey Bataev38e89532015-04-16 04:54:05 +00001092 if (!S.getSingleClause(OMPC_nowait) || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001093 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1094 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001095}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001096
Alexander Musmanf82886e2014-09-18 05:12:34 +00001097void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &) {
1098 llvm_unreachable("CodeGen for 'omp for simd' is not supported yet.");
1099}
1100
Alexey Bataev2df54a02015-03-12 08:53:29 +00001101static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1102 const Twine &Name,
1103 llvm::Value *Init = nullptr) {
1104 auto LVal = CGF.MakeNaturalAlignAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
1105 if (Init)
1106 CGF.EmitScalarInit(Init, LVal);
1107 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001108}
1109
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001110static OpenMPDirectiveKind emitSections(CodeGenFunction &CGF,
1111 const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001112 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1113 auto *CS = dyn_cast<CompoundStmt>(Stmt);
1114 if (CS && CS->size() > 1) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001115 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF) {
1116 auto &C = CGF.CGM.getContext();
1117 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1118 // Emit helper vars inits.
1119 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1120 CGF.Builder.getInt32(0));
1121 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
1122 LValue UB =
1123 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1124 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1125 CGF.Builder.getInt32(1));
1126 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1127 CGF.Builder.getInt32(0));
1128 // Loop counter.
1129 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1130 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001131 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001132 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001133 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001134 // Generate condition for loop.
1135 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1136 OK_Ordinary, S.getLocStart(),
1137 /*fpContractable=*/false);
1138 // Increment for loop counter.
1139 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
1140 OK_Ordinary, S.getLocStart());
1141 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
1142 // Iterate through all sections and emit a switch construct:
1143 // switch (IV) {
1144 // case 0:
1145 // <SectionStmt[0]>;
1146 // break;
1147 // ...
1148 // case <NumSection> - 1:
1149 // <SectionStmt[<NumSection> - 1]>;
1150 // break;
1151 // }
1152 // .omp.sections.exit:
1153 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1154 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1155 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1156 CS->size());
1157 unsigned CaseNumber = 0;
1158 for (auto C = CS->children(); C; ++C, ++CaseNumber) {
1159 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1160 CGF.EmitBlock(CaseBB);
1161 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
1162 CGF.EmitStmt(*C);
1163 CGF.EmitBranch(ExitBB);
1164 }
1165 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1166 };
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001167
1168 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1169 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
1170 // Emit implicit barrier to synchronize threads and avoid data races on
1171 // initialization of firstprivate variables.
1172 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1173 OMPD_unknown);
1174 }
1175 (void)LoopScope.Privatize();
1176
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001177 // Emit static non-chunked loop.
1178 CGF.CGM.getOpenMPRuntime().emitForInit(
1179 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
1180 /*IVSigned=*/true, IL.getAddress(), LB.getAddress(), UB.getAddress(),
1181 ST.getAddress());
1182 // UB = min(UB, GlobalUB);
1183 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1184 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1185 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1186 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1187 // IV = LB;
1188 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1189 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001190 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1191 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001192 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001193 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001194 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001195
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001196 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, CodeGen);
1197 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001198 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001199 // If only one section is found - no need to generate loop, emit as a single
1200 // region.
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001201 bool HasFirstprivates;
1202 auto &&CodeGen = [Stmt, &S, &HasFirstprivates](CodeGenFunction &CGF) {
1203 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1204 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
1205 (void)SingleScope.Privatize();
1206
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001207 CGF.EmitStmt(Stmt);
1208 CGF.EnsureInsertPoint();
1209 };
1210 CGF.CGM.getOpenMPRuntime().emitSingleRegion(CGF, CodeGen, S.getLocStart(),
1211 llvm::None, llvm::None,
1212 llvm::None, llvm::None);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001213 // Emit barrier for firstprivates only if 'sections' directive has 'nowait'
1214 // clause. Otherwise the barrier will be generated by the codegen for the
1215 // directive.
1216 if (HasFirstprivates && S.getSingleClause(OMPC_nowait)) {
1217 // Emit implicit barrier to synchronize threads and avoid data races on
1218 // initialization of firstprivate variables.
1219 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1220 OMPD_unknown);
1221 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001222 return OMPD_single;
1223}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001224
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001225void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1226 LexicalScope Scope(*this, S.getSourceRange());
1227 OpenMPDirectiveKind EmittedAs = emitSections(*this, S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001228 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001229 if (!S.getSingleClause(OMPC_nowait)) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001230 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001231 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001232}
1233
1234void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001235 LexicalScope Scope(*this, S.getSourceRange());
1236 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1237 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1238 CGF.EnsureInsertPoint();
1239 };
1240 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001241}
1242
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001243void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001244 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001245 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001246 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001247 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001248 // Check if there are any 'copyprivate' clauses associated with this
1249 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001250 // construct.
1251 auto CopyprivateFilter = [](const OMPClause *C) -> bool {
1252 return C->getClauseKind() == OMPC_copyprivate;
1253 };
1254 // Build a list of copyprivate variables along with helper expressions
1255 // (<source>, <destination>, <destination>=<source> expressions)
1256 typedef OMPExecutableDirective::filtered_clause_iterator<decltype(
1257 CopyprivateFilter)> CopyprivateIter;
1258 for (CopyprivateIter I(S.clauses(), CopyprivateFilter); I; ++I) {
1259 auto *C = cast<OMPCopyprivateClause>(*I);
1260 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001261 DestExprs.append(C->destination_exprs().begin(),
1262 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001263 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001264 AssignmentOps.append(C->assignment_ops().begin(),
1265 C->assignment_ops().end());
1266 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001267 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001268 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev5521d782015-04-24 04:21:15 +00001269 bool HasFirstprivates;
1270 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) {
1271 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1272 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev59c654a2015-04-27 03:48:52 +00001273 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev5521d782015-04-24 04:21:15 +00001274 (void)SingleScope.Privatize();
1275
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001276 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1277 CGF.EnsureInsertPoint();
1278 };
1279 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001280 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001281 AssignmentOps);
Alexey Bataev5521d782015-04-24 04:21:15 +00001282 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1283 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
1284 if ((!S.getSingleClause(OMPC_nowait) || HasFirstprivates) &&
1285 CopyprivateVars.empty()) {
1286 CGM.getOpenMPRuntime().emitBarrierCall(
1287 *this, S.getLocStart(),
1288 S.getSingleClause(OMPC_nowait) ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001289 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001290}
1291
Alexey Bataev8d690652014-12-04 07:23:53 +00001292void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001293 LexicalScope Scope(*this, S.getSourceRange());
1294 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1295 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1296 CGF.EnsureInsertPoint();
1297 };
1298 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001299}
1300
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001301void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001302 LexicalScope Scope(*this, S.getSourceRange());
1303 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1304 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1305 CGF.EnsureInsertPoint();
1306 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001307 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001308 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001309}
1310
Alexey Bataev671605e2015-04-13 05:28:11 +00001311void CodeGenFunction::EmitOMPParallelForDirective(
1312 const OMPParallelForDirective &S) {
1313 // Emit directive as a combined directive that consists of two implicit
1314 // directives: 'parallel' with 'for' directive.
1315 LexicalScope Scope(*this, S.getSourceRange());
1316 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1317 CGF.EmitOMPWorksharingLoop(S);
1318 // Emit implicit barrier at the end of parallel region, but this barrier
1319 // is at the end of 'for' directive, so emit it as the implicit barrier for
1320 // this 'for' directive.
1321 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1322 OMPD_parallel);
1323 };
1324 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001325}
1326
Alexander Musmane4e893b2014-09-23 09:33:00 +00001327void CodeGenFunction::EmitOMPParallelForSimdDirective(
1328 const OMPParallelForSimdDirective &) {
1329 llvm_unreachable("CodeGen for 'omp parallel for simd' is not supported yet.");
1330}
1331
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001332void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001333 const OMPParallelSectionsDirective &S) {
1334 // Emit directive as a combined directive that consists of two implicit
1335 // directives: 'parallel' with 'sections' directive.
1336 LexicalScope Scope(*this, S.getSourceRange());
1337 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1338 (void)emitSections(CGF, S);
1339 // Emit implicit barrier at the end of parallel region.
1340 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1341 OMPD_parallel);
1342 };
1343 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001344}
1345
Alexey Bataev62b63b12015-03-10 07:28:44 +00001346void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1347 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001348 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001349 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1350 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1351 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001352 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001353 // The first function argument for tasks is a thread id, the second one is a
1354 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001355 auto &&CodeGen = [PartId, &S](CodeGenFunction &CGF) {
1356 if (*PartId) {
1357 // TODO: emit code for untied tasks.
1358 }
1359 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1360 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00001361 auto OutlinedFn =
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001362 CGM.getOpenMPRuntime().emitTaskOutlinedFunction(S, *I, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001363 // Check if we should emit tied or untied task.
1364 bool Tied = !S.getSingleClause(OMPC_untied);
1365 // Check if the task is final
1366 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
1367 if (auto *Clause = S.getSingleClause(OMPC_final)) {
1368 // If the condition constant folds and can be elided, try to avoid emitting
1369 // the condition and the dead arm of the if/else.
1370 auto *Cond = cast<OMPFinalClause>(Clause)->getCondition();
1371 bool CondConstant;
1372 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1373 Final.setInt(CondConstant);
1374 else
1375 Final.setPointer(EvaluateExprAsBool(Cond));
1376 } else {
1377 // By default the task is not final.
1378 Final.setInt(/*IntVal=*/false);
1379 }
1380 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00001381 const Expr *IfCond = nullptr;
1382 if (auto C = S.getSingleClause(OMPC_if)) {
1383 IfCond = cast<OMPIfClause>(C)->getCondition();
1384 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001385 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getLocStart(), Tied, Final,
Alexey Bataev1d677132015-04-22 13:57:31 +00001386 OutlinedFn, SharedsTy, CapturedStruct,
1387 IfCond);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001388}
1389
Alexey Bataev9f797f32015-02-05 05:57:51 +00001390void CodeGenFunction::EmitOMPTaskyieldDirective(
1391 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001392 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001393}
1394
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001395void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001396 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001397}
1398
Alexey Bataev2df347a2014-07-18 10:17:07 +00001399void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &) {
1400 llvm_unreachable("CodeGen for 'omp taskwait' is not supported yet.");
1401}
1402
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001403void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001404 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
1405 if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) {
1406 auto FlushClause = cast<OMPFlushClause>(C);
1407 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1408 FlushClause->varlist_end());
1409 }
1410 return llvm::None;
1411 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00001412}
1413
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001414void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
1415 LexicalScope Scope(*this, S.getSourceRange());
1416 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1417 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1418 CGF.EnsureInsertPoint();
1419 };
1420 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001421}
1422
Alexey Bataevb57056f2015-01-22 06:17:56 +00001423static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
1424 QualType SrcType, QualType DestType) {
1425 assert(CGF.hasScalarEvaluationKind(DestType) &&
1426 "DestType must have scalar evaluation kind.");
1427 assert(!Val.isAggregate() && "Must be a scalar or complex.");
1428 return Val.isScalar()
1429 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType)
1430 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
1431 DestType);
1432}
1433
1434static CodeGenFunction::ComplexPairTy
1435convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
1436 QualType DestType) {
1437 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
1438 "DestType must have complex evaluation kind.");
1439 CodeGenFunction::ComplexPairTy ComplexVal;
1440 if (Val.isScalar()) {
1441 // Convert the input element to the element type of the complex.
1442 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1443 auto ScalarVal =
1444 CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestElementType);
1445 ComplexVal = CodeGenFunction::ComplexPairTy(
1446 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
1447 } else {
1448 assert(Val.isComplex() && "Must be a scalar or complex.");
1449 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
1450 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1451 ComplexVal.first = CGF.EmitScalarConversion(
1452 Val.getComplexVal().first, SrcElementType, DestElementType);
1453 ComplexVal.second = CGF.EmitScalarConversion(
1454 Val.getComplexVal().second, SrcElementType, DestElementType);
1455 }
1456 return ComplexVal;
1457}
1458
Alexey Bataev5e018f92015-04-23 06:35:10 +00001459static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
1460 LValue LVal, RValue RVal) {
1461 if (LVal.isGlobalReg()) {
1462 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
1463 } else {
1464 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
1465 : llvm::Monotonic,
1466 LVal.isVolatile(), /*IsInit=*/false);
1467 }
1468}
1469
1470static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal,
1471 QualType RValTy) {
1472 switch (CGF.getEvaluationKind(LVal.getType())) {
1473 case TEK_Scalar:
1474 CGF.EmitStoreThroughLValue(
1475 RValue::get(convertToScalarValue(CGF, RVal, RValTy, LVal.getType())),
1476 LVal);
1477 break;
1478 case TEK_Complex:
1479 CGF.EmitStoreOfComplex(
1480 convertToComplexValue(CGF, RVal, RValTy, LVal.getType()), LVal,
1481 /*isInit=*/false);
1482 break;
1483 case TEK_Aggregate:
1484 llvm_unreachable("Must be a scalar or complex.");
1485 }
1486}
1487
Alexey Bataevb57056f2015-01-22 06:17:56 +00001488static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
1489 const Expr *X, const Expr *V,
1490 SourceLocation Loc) {
1491 // v = x;
1492 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
1493 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
1494 LValue XLValue = CGF.EmitLValue(X);
1495 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00001496 RValue Res = XLValue.isGlobalReg()
1497 ? CGF.EmitLoadOfLValue(XLValue, Loc)
1498 : CGF.EmitAtomicLoad(XLValue, Loc,
1499 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00001500 : llvm::Monotonic,
1501 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001502 // OpenMP, 2.12.6, atomic Construct
1503 // Any atomic construct with a seq_cst clause forces the atomically
1504 // performed operation to include an implicit flush operation without a
1505 // list.
1506 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001507 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001508 emitSimpleStore(CGF,VLValue, Res, X->getType().getNonReferenceType());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001509}
1510
Alexey Bataevb8329262015-02-27 06:33:30 +00001511static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
1512 const Expr *X, const Expr *E,
1513 SourceLocation Loc) {
1514 // x = expr;
1515 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00001516 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00001517 // OpenMP, 2.12.6, atomic Construct
1518 // Any atomic construct with a seq_cst clause forces the atomically
1519 // performed operation to include an implicit flush operation without a
1520 // list.
1521 if (IsSeqCst)
1522 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1523}
1524
Alexey Bataev5e018f92015-04-23 06:35:10 +00001525std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
1526 RValue Update, BinaryOperatorKind BO,
1527 llvm::AtomicOrdering AO,
1528 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001529 auto &Context = CGF.CGM.getContext();
1530 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00001531 // expression is simple and atomic is allowed for the given type for the
1532 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001533 if (BO == BO_Comma || !Update.isScalar() ||
1534 !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() ||
1535 (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
1536 (Update.getScalarVal()->getType() !=
1537 X.getAddress()->getType()->getPointerElementType())) ||
1538 !Context.getTargetInfo().hasBuiltinAtomic(
1539 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00001540 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001541
1542 llvm::AtomicRMWInst::BinOp RMWOp;
1543 switch (BO) {
1544 case BO_Add:
1545 RMWOp = llvm::AtomicRMWInst::Add;
1546 break;
1547 case BO_Sub:
1548 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00001549 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001550 RMWOp = llvm::AtomicRMWInst::Sub;
1551 break;
1552 case BO_And:
1553 RMWOp = llvm::AtomicRMWInst::And;
1554 break;
1555 case BO_Or:
1556 RMWOp = llvm::AtomicRMWInst::Or;
1557 break;
1558 case BO_Xor:
1559 RMWOp = llvm::AtomicRMWInst::Xor;
1560 break;
1561 case BO_LT:
1562 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1563 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
1564 : llvm::AtomicRMWInst::Max)
1565 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
1566 : llvm::AtomicRMWInst::UMax);
1567 break;
1568 case BO_GT:
1569 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1570 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
1571 : llvm::AtomicRMWInst::Min)
1572 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
1573 : llvm::AtomicRMWInst::UMin);
1574 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001575 case BO_Assign:
1576 RMWOp = llvm::AtomicRMWInst::Xchg;
1577 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001578 case BO_Mul:
1579 case BO_Div:
1580 case BO_Rem:
1581 case BO_Shl:
1582 case BO_Shr:
1583 case BO_LAnd:
1584 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001585 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001586 case BO_PtrMemD:
1587 case BO_PtrMemI:
1588 case BO_LE:
1589 case BO_GE:
1590 case BO_EQ:
1591 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001592 case BO_AddAssign:
1593 case BO_SubAssign:
1594 case BO_AndAssign:
1595 case BO_OrAssign:
1596 case BO_XorAssign:
1597 case BO_MulAssign:
1598 case BO_DivAssign:
1599 case BO_RemAssign:
1600 case BO_ShlAssign:
1601 case BO_ShrAssign:
1602 case BO_Comma:
1603 llvm_unreachable("Unsupported atomic update operation");
1604 }
1605 auto *UpdateVal = Update.getScalarVal();
1606 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
1607 UpdateVal = CGF.Builder.CreateIntCast(
1608 IC, X.getAddress()->getType()->getPointerElementType(),
1609 X.getType()->hasSignedIntegerRepresentation());
1610 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001611 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getAddress(), UpdateVal, AO);
1612 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001613}
1614
Alexey Bataev5e018f92015-04-23 06:35:10 +00001615std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001616 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
1617 llvm::AtomicOrdering AO, SourceLocation Loc,
1618 const llvm::function_ref<RValue(RValue)> &CommonGen) {
1619 // Update expressions are allowed to have the following forms:
1620 // x binop= expr; -> xrval + expr;
1621 // x++, ++x -> xrval + 1;
1622 // x--, --x -> xrval - 1;
1623 // x = x binop expr; -> xrval binop expr
1624 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001625 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
1626 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001627 if (X.isGlobalReg()) {
1628 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
1629 // 'xrval'.
1630 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
1631 } else {
1632 // Perform compare-and-swap procedure.
1633 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00001634 }
1635 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001636 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001637}
1638
1639static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
1640 const Expr *X, const Expr *E,
1641 const Expr *UE, bool IsXLHSInRHSPart,
1642 SourceLocation Loc) {
1643 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1644 "Update expr in 'atomic update' must be a binary operator.");
1645 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1646 // Update expressions are allowed to have the following forms:
1647 // x binop= expr; -> xrval + expr;
1648 // x++, ++x -> xrval + 1;
1649 // x--, --x -> xrval - 1;
1650 // x = x binop expr; -> xrval binop expr
1651 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001652 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00001653 LValue XLValue = CGF.EmitLValue(X);
1654 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001655 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001656 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1657 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1658 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1659 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1660 auto Gen =
1661 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
1662 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1663 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1664 return CGF.EmitAnyExpr(UE);
1665 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00001666 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
1667 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1668 // OpenMP, 2.12.6, atomic Construct
1669 // Any atomic construct with a seq_cst clause forces the atomically
1670 // performed operation to include an implicit flush operation without a
1671 // list.
1672 if (IsSeqCst)
1673 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1674}
1675
1676static RValue convertToType(CodeGenFunction &CGF, RValue Value,
1677 QualType SourceType, QualType ResType) {
1678 switch (CGF.getEvaluationKind(ResType)) {
1679 case TEK_Scalar:
1680 return RValue::get(convertToScalarValue(CGF, Value, SourceType, ResType));
1681 case TEK_Complex: {
1682 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType);
1683 return RValue::getComplex(Res.first, Res.second);
1684 }
1685 case TEK_Aggregate:
1686 break;
1687 }
1688 llvm_unreachable("Must be a scalar or complex.");
1689}
1690
1691static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
1692 bool IsPostfixUpdate, const Expr *V,
1693 const Expr *X, const Expr *E,
1694 const Expr *UE, bool IsXLHSInRHSPart,
1695 SourceLocation Loc) {
1696 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
1697 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
1698 RValue NewVVal;
1699 LValue VLValue = CGF.EmitLValue(V);
1700 LValue XLValue = CGF.EmitLValue(X);
1701 RValue ExprRValue = CGF.EmitAnyExpr(E);
1702 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
1703 QualType NewVValType;
1704 if (UE) {
1705 // 'x' is updated with some additional value.
1706 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1707 "Update expr in 'atomic capture' must be a binary operator.");
1708 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1709 // Update expressions are allowed to have the following forms:
1710 // x binop= expr; -> xrval + expr;
1711 // x++, ++x -> xrval + 1;
1712 // x--, --x -> xrval - 1;
1713 // x = x binop expr; -> xrval binop expr
1714 // x = expr Op x; - > expr binop xrval;
1715 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1716 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1717 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1718 NewVValType = XRValExpr->getType();
1719 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1720 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
1721 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
1722 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1723 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1724 RValue Res = CGF.EmitAnyExpr(UE);
1725 NewVVal = IsPostfixUpdate ? XRValue : Res;
1726 return Res;
1727 };
1728 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1729 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1730 if (Res.first) {
1731 // 'atomicrmw' instruction was generated.
1732 if (IsPostfixUpdate) {
1733 // Use old value from 'atomicrmw'.
1734 NewVVal = Res.second;
1735 } else {
1736 // 'atomicrmw' does not provide new value, so evaluate it using old
1737 // value of 'x'.
1738 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1739 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
1740 NewVVal = CGF.EmitAnyExpr(UE);
1741 }
1742 }
1743 } else {
1744 // 'x' is simply rewritten with some 'expr'.
1745 NewVValType = X->getType().getNonReferenceType();
1746 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
1747 X->getType().getNonReferenceType());
1748 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
1749 NewVVal = XRValue;
1750 return ExprRValue;
1751 };
1752 // Try to perform atomicrmw xchg, otherwise simple exchange.
1753 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1754 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
1755 Loc, Gen);
1756 if (Res.first) {
1757 // 'atomicrmw' instruction was generated.
1758 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
1759 }
1760 }
1761 // Emit post-update store to 'v' of old/new 'x' value.
1762 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001763 // OpenMP, 2.12.6, atomic Construct
1764 // Any atomic construct with a seq_cst clause forces the atomically
1765 // performed operation to include an implicit flush operation without a
1766 // list.
1767 if (IsSeqCst)
1768 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1769}
1770
Alexey Bataevb57056f2015-01-22 06:17:56 +00001771static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00001772 bool IsSeqCst, bool IsPostfixUpdate,
1773 const Expr *X, const Expr *V, const Expr *E,
1774 const Expr *UE, bool IsXLHSInRHSPart,
1775 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001776 switch (Kind) {
1777 case OMPC_read:
1778 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
1779 break;
1780 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00001781 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
1782 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001783 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001784 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00001785 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
1786 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001787 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001788 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
1789 IsXLHSInRHSPart, Loc);
1790 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001791 case OMPC_if:
1792 case OMPC_final:
1793 case OMPC_num_threads:
1794 case OMPC_private:
1795 case OMPC_firstprivate:
1796 case OMPC_lastprivate:
1797 case OMPC_reduction:
1798 case OMPC_safelen:
1799 case OMPC_collapse:
1800 case OMPC_default:
1801 case OMPC_seq_cst:
1802 case OMPC_shared:
1803 case OMPC_linear:
1804 case OMPC_aligned:
1805 case OMPC_copyin:
1806 case OMPC_copyprivate:
1807 case OMPC_flush:
1808 case OMPC_proc_bind:
1809 case OMPC_schedule:
1810 case OMPC_ordered:
1811 case OMPC_nowait:
1812 case OMPC_untied:
1813 case OMPC_threadprivate:
1814 case OMPC_mergeable:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001815 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
1816 }
1817}
1818
1819void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
1820 bool IsSeqCst = S.getSingleClause(/*K=*/OMPC_seq_cst);
1821 OpenMPClauseKind Kind = OMPC_unknown;
1822 for (auto *C : S.clauses()) {
1823 // Find first clause (skip seq_cst clause, if it is first).
1824 if (C->getClauseKind() != OMPC_seq_cst) {
1825 Kind = C->getClauseKind();
1826 break;
1827 }
1828 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001829
1830 const auto *CS =
1831 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001832 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00001833 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001834 }
1835 // Processing for statements under 'atomic capture'.
1836 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
1837 for (const auto *C : Compound->body()) {
1838 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
1839 enterFullExpression(EWC);
1840 }
1841 }
1842 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001843
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001844 LexicalScope Scope(*this, S.getSourceRange());
1845 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00001846 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
1847 S.getV(), S.getExpr(), S.getUpdateExpr(),
1848 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001849 };
1850 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00001851}
1852
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001853void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) {
1854 llvm_unreachable("CodeGen for 'omp target' is not supported yet.");
1855}
1856
Alexey Bataev13314bf2014-10-09 04:18:56 +00001857void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
1858 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
1859}