blob: 62fe4bcd1f2495eff82dd7f3e8a804b69729e895 [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 Bataev9efc03b2015-04-27 04:34:03 +00001115 bool HasLastprivates = false;
1116 auto &&CodeGen = [&S, CS, &HasLastprivates](CodeGenFunction &CGF) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001117 auto &C = CGF.CGM.getContext();
1118 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1119 // Emit helper vars inits.
1120 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1121 CGF.Builder.getInt32(0));
1122 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
1123 LValue UB =
1124 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1125 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1126 CGF.Builder.getInt32(1));
1127 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1128 CGF.Builder.getInt32(0));
1129 // Loop counter.
1130 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1131 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001132 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001133 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001134 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001135 // Generate condition for loop.
1136 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1137 OK_Ordinary, S.getLocStart(),
1138 /*fpContractable=*/false);
1139 // Increment for loop counter.
1140 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
1141 OK_Ordinary, S.getLocStart());
1142 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
1143 // Iterate through all sections and emit a switch construct:
1144 // switch (IV) {
1145 // case 0:
1146 // <SectionStmt[0]>;
1147 // break;
1148 // ...
1149 // case <NumSection> - 1:
1150 // <SectionStmt[<NumSection> - 1]>;
1151 // break;
1152 // }
1153 // .omp.sections.exit:
1154 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1155 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1156 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1157 CS->size());
1158 unsigned CaseNumber = 0;
1159 for (auto C = CS->children(); C; ++C, ++CaseNumber) {
1160 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1161 CGF.EmitBlock(CaseBB);
1162 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
1163 CGF.EmitStmt(*C);
1164 CGF.EmitBranch(ExitBB);
1165 }
1166 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1167 };
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001168
1169 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1170 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
1171 // Emit implicit barrier to synchronize threads and avoid data races on
1172 // initialization of firstprivate variables.
1173 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1174 OMPD_unknown);
1175 }
Alexey Bataev73870832015-04-27 04:12:12 +00001176 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001177 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001178 (void)LoopScope.Privatize();
1179
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001180 // Emit static non-chunked loop.
1181 CGF.CGM.getOpenMPRuntime().emitForInit(
1182 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
1183 /*IVSigned=*/true, IL.getAddress(), LB.getAddress(), UB.getAddress(),
1184 ST.getAddress());
1185 // UB = min(UB, GlobalUB);
1186 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1187 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1188 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1189 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1190 // IV = LB;
1191 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1192 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001193 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1194 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001195 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001196 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001197
1198 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1199 if (HasLastprivates)
1200 CGF.EmitOMPLastprivateClauseFinal(
1201 S, CGF.Builder.CreateIsNotNull(
1202 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev2df54a02015-03-12 08:53:29 +00001203 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001204
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001205 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, CodeGen);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001206 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1207 // clause. Otherwise the barrier will be generated by the codegen for the
1208 // directive.
1209 if (HasLastprivates && S.getSingleClause(OMPC_nowait)) {
1210 // Emit implicit barrier to synchronize threads and avoid data races on
1211 // initialization of firstprivate variables.
1212 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1213 OMPD_unknown);
1214 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001215 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001216 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001217 // If only one section is found - no need to generate loop, emit as a single
1218 // region.
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001219 bool HasFirstprivates;
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001220 // No need to generate lastprivates for sections with single section region,
1221 // we can use original shared variable for all calculations with barrier at
1222 // the end of the sections.
1223 auto LastprivateFilter = [](const OMPClause *C) -> bool {
1224 return C->getClauseKind() == OMPC_lastprivate;
1225 };
1226 OMPExecutableDirective::filtered_clause_iterator<decltype(LastprivateFilter)>
1227 I(S.clauses(), LastprivateFilter);
1228 bool HasLastprivates = I;
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001229 auto &&CodeGen = [Stmt, &S, &HasFirstprivates](CodeGenFunction &CGF) {
1230 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1231 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev73870832015-04-27 04:12:12 +00001232 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001233 (void)SingleScope.Privatize();
1234
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001235 CGF.EmitStmt(Stmt);
1236 CGF.EnsureInsertPoint();
1237 };
1238 CGF.CGM.getOpenMPRuntime().emitSingleRegion(CGF, CodeGen, S.getLocStart(),
1239 llvm::None, llvm::None,
1240 llvm::None, llvm::None);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001241 // Emit barrier for firstprivates or lastprivates only if 'sections' directive
1242 // has 'nowait' clause. Otherwise the barrier will be generated by the codegen
1243 // for the directive.
1244 if ((HasFirstprivates || HasLastprivates) && S.getSingleClause(OMPC_nowait)) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001245 // Emit implicit barrier to synchronize threads and avoid data races on
1246 // initialization of firstprivate variables.
1247 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1248 OMPD_unknown);
1249 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001250 return OMPD_single;
1251}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001252
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001253void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1254 LexicalScope Scope(*this, S.getSourceRange());
1255 OpenMPDirectiveKind EmittedAs = emitSections(*this, S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001256 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001257 if (!S.getSingleClause(OMPC_nowait)) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001258 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001259 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001260}
1261
1262void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001263 LexicalScope Scope(*this, S.getSourceRange());
1264 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1265 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1266 CGF.EnsureInsertPoint();
1267 };
1268 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001269}
1270
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001271void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001272 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001273 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001274 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001275 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001276 // Check if there are any 'copyprivate' clauses associated with this
1277 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001278 // construct.
1279 auto CopyprivateFilter = [](const OMPClause *C) -> bool {
1280 return C->getClauseKind() == OMPC_copyprivate;
1281 };
1282 // Build a list of copyprivate variables along with helper expressions
1283 // (<source>, <destination>, <destination>=<source> expressions)
1284 typedef OMPExecutableDirective::filtered_clause_iterator<decltype(
1285 CopyprivateFilter)> CopyprivateIter;
1286 for (CopyprivateIter I(S.clauses(), CopyprivateFilter); I; ++I) {
1287 auto *C = cast<OMPCopyprivateClause>(*I);
1288 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001289 DestExprs.append(C->destination_exprs().begin(),
1290 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001291 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001292 AssignmentOps.append(C->assignment_ops().begin(),
1293 C->assignment_ops().end());
1294 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001295 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001296 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev5521d782015-04-24 04:21:15 +00001297 bool HasFirstprivates;
1298 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) {
1299 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1300 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev59c654a2015-04-27 03:48:52 +00001301 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev5521d782015-04-24 04:21:15 +00001302 (void)SingleScope.Privatize();
1303
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001304 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1305 CGF.EnsureInsertPoint();
1306 };
1307 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001308 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001309 AssignmentOps);
Alexey Bataev5521d782015-04-24 04:21:15 +00001310 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1311 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
1312 if ((!S.getSingleClause(OMPC_nowait) || HasFirstprivates) &&
1313 CopyprivateVars.empty()) {
1314 CGM.getOpenMPRuntime().emitBarrierCall(
1315 *this, S.getLocStart(),
1316 S.getSingleClause(OMPC_nowait) ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001317 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001318}
1319
Alexey Bataev8d690652014-12-04 07:23:53 +00001320void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001321 LexicalScope Scope(*this, S.getSourceRange());
1322 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1323 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1324 CGF.EnsureInsertPoint();
1325 };
1326 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001327}
1328
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001329void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001330 LexicalScope Scope(*this, S.getSourceRange());
1331 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1332 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1333 CGF.EnsureInsertPoint();
1334 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001335 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001336 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001337}
1338
Alexey Bataev671605e2015-04-13 05:28:11 +00001339void CodeGenFunction::EmitOMPParallelForDirective(
1340 const OMPParallelForDirective &S) {
1341 // Emit directive as a combined directive that consists of two implicit
1342 // directives: 'parallel' with 'for' directive.
1343 LexicalScope Scope(*this, S.getSourceRange());
1344 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1345 CGF.EmitOMPWorksharingLoop(S);
1346 // Emit implicit barrier at the end of parallel region, but this barrier
1347 // is at the end of 'for' directive, so emit it as the implicit barrier for
1348 // this 'for' directive.
1349 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1350 OMPD_parallel);
1351 };
1352 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001353}
1354
Alexander Musmane4e893b2014-09-23 09:33:00 +00001355void CodeGenFunction::EmitOMPParallelForSimdDirective(
1356 const OMPParallelForSimdDirective &) {
1357 llvm_unreachable("CodeGen for 'omp parallel for simd' is not supported yet.");
1358}
1359
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001360void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001361 const OMPParallelSectionsDirective &S) {
1362 // Emit directive as a combined directive that consists of two implicit
1363 // directives: 'parallel' with 'sections' directive.
1364 LexicalScope Scope(*this, S.getSourceRange());
1365 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1366 (void)emitSections(CGF, S);
1367 // Emit implicit barrier at the end of parallel region.
1368 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1369 OMPD_parallel);
1370 };
1371 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001372}
1373
Alexey Bataev62b63b12015-03-10 07:28:44 +00001374void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1375 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001376 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001377 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1378 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1379 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001380 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001381 // The first function argument for tasks is a thread id, the second one is a
1382 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001383 auto &&CodeGen = [PartId, &S](CodeGenFunction &CGF) {
1384 if (*PartId) {
1385 // TODO: emit code for untied tasks.
1386 }
1387 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1388 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00001389 auto OutlinedFn =
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001390 CGM.getOpenMPRuntime().emitTaskOutlinedFunction(S, *I, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001391 // Check if we should emit tied or untied task.
1392 bool Tied = !S.getSingleClause(OMPC_untied);
1393 // Check if the task is final
1394 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
1395 if (auto *Clause = S.getSingleClause(OMPC_final)) {
1396 // If the condition constant folds and can be elided, try to avoid emitting
1397 // the condition and the dead arm of the if/else.
1398 auto *Cond = cast<OMPFinalClause>(Clause)->getCondition();
1399 bool CondConstant;
1400 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1401 Final.setInt(CondConstant);
1402 else
1403 Final.setPointer(EvaluateExprAsBool(Cond));
1404 } else {
1405 // By default the task is not final.
1406 Final.setInt(/*IntVal=*/false);
1407 }
1408 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00001409 const Expr *IfCond = nullptr;
1410 if (auto C = S.getSingleClause(OMPC_if)) {
1411 IfCond = cast<OMPIfClause>(C)->getCondition();
1412 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001413 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getLocStart(), Tied, Final,
Alexey Bataev1d677132015-04-22 13:57:31 +00001414 OutlinedFn, SharedsTy, CapturedStruct,
1415 IfCond);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001416}
1417
Alexey Bataev9f797f32015-02-05 05:57:51 +00001418void CodeGenFunction::EmitOMPTaskyieldDirective(
1419 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001420 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001421}
1422
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001423void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001424 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001425}
1426
Alexey Bataev2df347a2014-07-18 10:17:07 +00001427void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &) {
1428 llvm_unreachable("CodeGen for 'omp taskwait' is not supported yet.");
1429}
1430
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001431void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001432 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
1433 if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) {
1434 auto FlushClause = cast<OMPFlushClause>(C);
1435 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1436 FlushClause->varlist_end());
1437 }
1438 return llvm::None;
1439 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00001440}
1441
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001442void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
1443 LexicalScope Scope(*this, S.getSourceRange());
1444 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1445 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1446 CGF.EnsureInsertPoint();
1447 };
1448 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001449}
1450
Alexey Bataevb57056f2015-01-22 06:17:56 +00001451static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
1452 QualType SrcType, QualType DestType) {
1453 assert(CGF.hasScalarEvaluationKind(DestType) &&
1454 "DestType must have scalar evaluation kind.");
1455 assert(!Val.isAggregate() && "Must be a scalar or complex.");
1456 return Val.isScalar()
1457 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType)
1458 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
1459 DestType);
1460}
1461
1462static CodeGenFunction::ComplexPairTy
1463convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
1464 QualType DestType) {
1465 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
1466 "DestType must have complex evaluation kind.");
1467 CodeGenFunction::ComplexPairTy ComplexVal;
1468 if (Val.isScalar()) {
1469 // Convert the input element to the element type of the complex.
1470 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1471 auto ScalarVal =
1472 CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestElementType);
1473 ComplexVal = CodeGenFunction::ComplexPairTy(
1474 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
1475 } else {
1476 assert(Val.isComplex() && "Must be a scalar or complex.");
1477 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
1478 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1479 ComplexVal.first = CGF.EmitScalarConversion(
1480 Val.getComplexVal().first, SrcElementType, DestElementType);
1481 ComplexVal.second = CGF.EmitScalarConversion(
1482 Val.getComplexVal().second, SrcElementType, DestElementType);
1483 }
1484 return ComplexVal;
1485}
1486
Alexey Bataev5e018f92015-04-23 06:35:10 +00001487static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
1488 LValue LVal, RValue RVal) {
1489 if (LVal.isGlobalReg()) {
1490 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
1491 } else {
1492 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
1493 : llvm::Monotonic,
1494 LVal.isVolatile(), /*IsInit=*/false);
1495 }
1496}
1497
1498static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal,
1499 QualType RValTy) {
1500 switch (CGF.getEvaluationKind(LVal.getType())) {
1501 case TEK_Scalar:
1502 CGF.EmitStoreThroughLValue(
1503 RValue::get(convertToScalarValue(CGF, RVal, RValTy, LVal.getType())),
1504 LVal);
1505 break;
1506 case TEK_Complex:
1507 CGF.EmitStoreOfComplex(
1508 convertToComplexValue(CGF, RVal, RValTy, LVal.getType()), LVal,
1509 /*isInit=*/false);
1510 break;
1511 case TEK_Aggregate:
1512 llvm_unreachable("Must be a scalar or complex.");
1513 }
1514}
1515
Alexey Bataevb57056f2015-01-22 06:17:56 +00001516static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
1517 const Expr *X, const Expr *V,
1518 SourceLocation Loc) {
1519 // v = x;
1520 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
1521 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
1522 LValue XLValue = CGF.EmitLValue(X);
1523 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00001524 RValue Res = XLValue.isGlobalReg()
1525 ? CGF.EmitLoadOfLValue(XLValue, Loc)
1526 : CGF.EmitAtomicLoad(XLValue, Loc,
1527 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00001528 : llvm::Monotonic,
1529 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001530 // OpenMP, 2.12.6, atomic Construct
1531 // Any atomic construct with a seq_cst clause forces the atomically
1532 // performed operation to include an implicit flush operation without a
1533 // list.
1534 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001535 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001536 emitSimpleStore(CGF,VLValue, Res, X->getType().getNonReferenceType());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001537}
1538
Alexey Bataevb8329262015-02-27 06:33:30 +00001539static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
1540 const Expr *X, const Expr *E,
1541 SourceLocation Loc) {
1542 // x = expr;
1543 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00001544 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00001545 // OpenMP, 2.12.6, atomic Construct
1546 // Any atomic construct with a seq_cst clause forces the atomically
1547 // performed operation to include an implicit flush operation without a
1548 // list.
1549 if (IsSeqCst)
1550 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1551}
1552
Alexey Bataev5e018f92015-04-23 06:35:10 +00001553std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
1554 RValue Update, BinaryOperatorKind BO,
1555 llvm::AtomicOrdering AO,
1556 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001557 auto &Context = CGF.CGM.getContext();
1558 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00001559 // expression is simple and atomic is allowed for the given type for the
1560 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001561 if (BO == BO_Comma || !Update.isScalar() ||
1562 !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() ||
1563 (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
1564 (Update.getScalarVal()->getType() !=
1565 X.getAddress()->getType()->getPointerElementType())) ||
1566 !Context.getTargetInfo().hasBuiltinAtomic(
1567 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00001568 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001569
1570 llvm::AtomicRMWInst::BinOp RMWOp;
1571 switch (BO) {
1572 case BO_Add:
1573 RMWOp = llvm::AtomicRMWInst::Add;
1574 break;
1575 case BO_Sub:
1576 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00001577 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001578 RMWOp = llvm::AtomicRMWInst::Sub;
1579 break;
1580 case BO_And:
1581 RMWOp = llvm::AtomicRMWInst::And;
1582 break;
1583 case BO_Or:
1584 RMWOp = llvm::AtomicRMWInst::Or;
1585 break;
1586 case BO_Xor:
1587 RMWOp = llvm::AtomicRMWInst::Xor;
1588 break;
1589 case BO_LT:
1590 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1591 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
1592 : llvm::AtomicRMWInst::Max)
1593 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
1594 : llvm::AtomicRMWInst::UMax);
1595 break;
1596 case BO_GT:
1597 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1598 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
1599 : llvm::AtomicRMWInst::Min)
1600 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
1601 : llvm::AtomicRMWInst::UMin);
1602 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001603 case BO_Assign:
1604 RMWOp = llvm::AtomicRMWInst::Xchg;
1605 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001606 case BO_Mul:
1607 case BO_Div:
1608 case BO_Rem:
1609 case BO_Shl:
1610 case BO_Shr:
1611 case BO_LAnd:
1612 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001613 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001614 case BO_PtrMemD:
1615 case BO_PtrMemI:
1616 case BO_LE:
1617 case BO_GE:
1618 case BO_EQ:
1619 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001620 case BO_AddAssign:
1621 case BO_SubAssign:
1622 case BO_AndAssign:
1623 case BO_OrAssign:
1624 case BO_XorAssign:
1625 case BO_MulAssign:
1626 case BO_DivAssign:
1627 case BO_RemAssign:
1628 case BO_ShlAssign:
1629 case BO_ShrAssign:
1630 case BO_Comma:
1631 llvm_unreachable("Unsupported atomic update operation");
1632 }
1633 auto *UpdateVal = Update.getScalarVal();
1634 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
1635 UpdateVal = CGF.Builder.CreateIntCast(
1636 IC, X.getAddress()->getType()->getPointerElementType(),
1637 X.getType()->hasSignedIntegerRepresentation());
1638 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001639 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getAddress(), UpdateVal, AO);
1640 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001641}
1642
Alexey Bataev5e018f92015-04-23 06:35:10 +00001643std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001644 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
1645 llvm::AtomicOrdering AO, SourceLocation Loc,
1646 const llvm::function_ref<RValue(RValue)> &CommonGen) {
1647 // Update expressions are allowed to have the following forms:
1648 // x binop= expr; -> xrval + expr;
1649 // x++, ++x -> xrval + 1;
1650 // x--, --x -> xrval - 1;
1651 // x = x binop expr; -> xrval binop expr
1652 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001653 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
1654 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001655 if (X.isGlobalReg()) {
1656 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
1657 // 'xrval'.
1658 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
1659 } else {
1660 // Perform compare-and-swap procedure.
1661 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00001662 }
1663 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001664 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001665}
1666
1667static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
1668 const Expr *X, const Expr *E,
1669 const Expr *UE, bool IsXLHSInRHSPart,
1670 SourceLocation Loc) {
1671 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1672 "Update expr in 'atomic update' must be a binary operator.");
1673 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1674 // Update expressions are allowed to have the following forms:
1675 // x binop= expr; -> xrval + expr;
1676 // x++, ++x -> xrval + 1;
1677 // x--, --x -> xrval - 1;
1678 // x = x binop expr; -> xrval binop expr
1679 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001680 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00001681 LValue XLValue = CGF.EmitLValue(X);
1682 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001683 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001684 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1685 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1686 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1687 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1688 auto Gen =
1689 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
1690 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1691 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1692 return CGF.EmitAnyExpr(UE);
1693 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00001694 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
1695 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1696 // OpenMP, 2.12.6, atomic Construct
1697 // Any atomic construct with a seq_cst clause forces the atomically
1698 // performed operation to include an implicit flush operation without a
1699 // list.
1700 if (IsSeqCst)
1701 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1702}
1703
1704static RValue convertToType(CodeGenFunction &CGF, RValue Value,
1705 QualType SourceType, QualType ResType) {
1706 switch (CGF.getEvaluationKind(ResType)) {
1707 case TEK_Scalar:
1708 return RValue::get(convertToScalarValue(CGF, Value, SourceType, ResType));
1709 case TEK_Complex: {
1710 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType);
1711 return RValue::getComplex(Res.first, Res.second);
1712 }
1713 case TEK_Aggregate:
1714 break;
1715 }
1716 llvm_unreachable("Must be a scalar or complex.");
1717}
1718
1719static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
1720 bool IsPostfixUpdate, const Expr *V,
1721 const Expr *X, const Expr *E,
1722 const Expr *UE, bool IsXLHSInRHSPart,
1723 SourceLocation Loc) {
1724 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
1725 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
1726 RValue NewVVal;
1727 LValue VLValue = CGF.EmitLValue(V);
1728 LValue XLValue = CGF.EmitLValue(X);
1729 RValue ExprRValue = CGF.EmitAnyExpr(E);
1730 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
1731 QualType NewVValType;
1732 if (UE) {
1733 // 'x' is updated with some additional value.
1734 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1735 "Update expr in 'atomic capture' must be a binary operator.");
1736 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1737 // Update expressions are allowed to have the following forms:
1738 // x binop= expr; -> xrval + expr;
1739 // x++, ++x -> xrval + 1;
1740 // x--, --x -> xrval - 1;
1741 // x = x binop expr; -> xrval binop expr
1742 // x = expr Op x; - > expr binop xrval;
1743 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1744 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1745 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1746 NewVValType = XRValExpr->getType();
1747 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1748 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
1749 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
1750 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1751 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1752 RValue Res = CGF.EmitAnyExpr(UE);
1753 NewVVal = IsPostfixUpdate ? XRValue : Res;
1754 return Res;
1755 };
1756 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1757 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1758 if (Res.first) {
1759 // 'atomicrmw' instruction was generated.
1760 if (IsPostfixUpdate) {
1761 // Use old value from 'atomicrmw'.
1762 NewVVal = Res.second;
1763 } else {
1764 // 'atomicrmw' does not provide new value, so evaluate it using old
1765 // value of 'x'.
1766 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1767 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
1768 NewVVal = CGF.EmitAnyExpr(UE);
1769 }
1770 }
1771 } else {
1772 // 'x' is simply rewritten with some 'expr'.
1773 NewVValType = X->getType().getNonReferenceType();
1774 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
1775 X->getType().getNonReferenceType());
1776 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
1777 NewVVal = XRValue;
1778 return ExprRValue;
1779 };
1780 // Try to perform atomicrmw xchg, otherwise simple exchange.
1781 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1782 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
1783 Loc, Gen);
1784 if (Res.first) {
1785 // 'atomicrmw' instruction was generated.
1786 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
1787 }
1788 }
1789 // Emit post-update store to 'v' of old/new 'x' value.
1790 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001791 // OpenMP, 2.12.6, atomic Construct
1792 // Any atomic construct with a seq_cst clause forces the atomically
1793 // performed operation to include an implicit flush operation without a
1794 // list.
1795 if (IsSeqCst)
1796 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1797}
1798
Alexey Bataevb57056f2015-01-22 06:17:56 +00001799static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00001800 bool IsSeqCst, bool IsPostfixUpdate,
1801 const Expr *X, const Expr *V, const Expr *E,
1802 const Expr *UE, bool IsXLHSInRHSPart,
1803 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001804 switch (Kind) {
1805 case OMPC_read:
1806 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
1807 break;
1808 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00001809 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
1810 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001811 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001812 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00001813 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
1814 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001815 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001816 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
1817 IsXLHSInRHSPart, Loc);
1818 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001819 case OMPC_if:
1820 case OMPC_final:
1821 case OMPC_num_threads:
1822 case OMPC_private:
1823 case OMPC_firstprivate:
1824 case OMPC_lastprivate:
1825 case OMPC_reduction:
1826 case OMPC_safelen:
1827 case OMPC_collapse:
1828 case OMPC_default:
1829 case OMPC_seq_cst:
1830 case OMPC_shared:
1831 case OMPC_linear:
1832 case OMPC_aligned:
1833 case OMPC_copyin:
1834 case OMPC_copyprivate:
1835 case OMPC_flush:
1836 case OMPC_proc_bind:
1837 case OMPC_schedule:
1838 case OMPC_ordered:
1839 case OMPC_nowait:
1840 case OMPC_untied:
1841 case OMPC_threadprivate:
1842 case OMPC_mergeable:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001843 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
1844 }
1845}
1846
1847void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
1848 bool IsSeqCst = S.getSingleClause(/*K=*/OMPC_seq_cst);
1849 OpenMPClauseKind Kind = OMPC_unknown;
1850 for (auto *C : S.clauses()) {
1851 // Find first clause (skip seq_cst clause, if it is first).
1852 if (C->getClauseKind() != OMPC_seq_cst) {
1853 Kind = C->getClauseKind();
1854 break;
1855 }
1856 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001857
1858 const auto *CS =
1859 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001860 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00001861 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001862 }
1863 // Processing for statements under 'atomic capture'.
1864 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
1865 for (const auto *C : Compound->body()) {
1866 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
1867 enterFullExpression(EWC);
1868 }
1869 }
1870 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001871
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001872 LexicalScope Scope(*this, S.getSourceRange());
1873 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00001874 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
1875 S.getV(), S.getExpr(), S.getUpdateExpr(),
1876 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001877 };
1878 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00001879}
1880
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001881void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) {
1882 llvm_unreachable("CodeGen for 'omp target' is not supported yet.");
1883}
1884
Alexey Bataev13314bf2014-10-09 04:18:56 +00001885void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
1886 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
1887}