blob: c701263198995fd6a69413be866805ac4881bd44 [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 };
1167 // Emit static non-chunked loop.
1168 CGF.CGM.getOpenMPRuntime().emitForInit(
1169 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
1170 /*IVSigned=*/true, IL.getAddress(), LB.getAddress(), UB.getAddress(),
1171 ST.getAddress());
1172 // UB = min(UB, GlobalUB);
1173 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1174 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1175 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1176 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1177 // IV = LB;
1178 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1179 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001180 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1181 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001182 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001183 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataev2df54a02015-03-12 08:53:29 +00001184 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001185
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001186 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, CodeGen);
1187 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001188 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001189 // If only one section is found - no need to generate loop, emit as a single
1190 // region.
1191 auto &&CodeGen = [Stmt](CodeGenFunction &CGF) {
1192 CGF.EmitStmt(Stmt);
1193 CGF.EnsureInsertPoint();
1194 };
1195 CGF.CGM.getOpenMPRuntime().emitSingleRegion(CGF, CodeGen, S.getLocStart(),
1196 llvm::None, llvm::None,
1197 llvm::None, llvm::None);
1198 return OMPD_single;
1199}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001200
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001201void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1202 LexicalScope Scope(*this, S.getSourceRange());
1203 OpenMPDirectiveKind EmittedAs = emitSections(*this, S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001204 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001205 if (!S.getSingleClause(OMPC_nowait)) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001206 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001207 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001208}
1209
1210void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001211 LexicalScope Scope(*this, S.getSourceRange());
1212 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1213 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1214 CGF.EnsureInsertPoint();
1215 };
1216 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001217}
1218
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001219void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001220 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001221 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001222 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001223 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001224 // Check if there are any 'copyprivate' clauses associated with this
1225 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001226 // construct.
1227 auto CopyprivateFilter = [](const OMPClause *C) -> bool {
1228 return C->getClauseKind() == OMPC_copyprivate;
1229 };
1230 // Build a list of copyprivate variables along with helper expressions
1231 // (<source>, <destination>, <destination>=<source> expressions)
1232 typedef OMPExecutableDirective::filtered_clause_iterator<decltype(
1233 CopyprivateFilter)> CopyprivateIter;
1234 for (CopyprivateIter I(S.clauses(), CopyprivateFilter); I; ++I) {
1235 auto *C = cast<OMPCopyprivateClause>(*I);
1236 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001237 DestExprs.append(C->destination_exprs().begin(),
1238 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001239 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001240 AssignmentOps.append(C->assignment_ops().begin(),
1241 C->assignment_ops().end());
1242 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001243 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001244 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001245 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1246 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1247 CGF.EnsureInsertPoint();
1248 };
1249 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001250 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001251 AssignmentOps);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001252 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001253 if (!S.getSingleClause(OMPC_nowait)) {
1254 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_single);
1255 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001256}
1257
Alexey Bataev8d690652014-12-04 07:23:53 +00001258void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001259 LexicalScope Scope(*this, S.getSourceRange());
1260 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1261 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1262 CGF.EnsureInsertPoint();
1263 };
1264 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001265}
1266
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001267void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001268 LexicalScope Scope(*this, S.getSourceRange());
1269 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1270 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1271 CGF.EnsureInsertPoint();
1272 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001273 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001274 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001275}
1276
Alexey Bataev671605e2015-04-13 05:28:11 +00001277void CodeGenFunction::EmitOMPParallelForDirective(
1278 const OMPParallelForDirective &S) {
1279 // Emit directive as a combined directive that consists of two implicit
1280 // directives: 'parallel' with 'for' directive.
1281 LexicalScope Scope(*this, S.getSourceRange());
1282 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1283 CGF.EmitOMPWorksharingLoop(S);
1284 // Emit implicit barrier at the end of parallel region, but this barrier
1285 // is at the end of 'for' directive, so emit it as the implicit barrier for
1286 // this 'for' directive.
1287 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1288 OMPD_parallel);
1289 };
1290 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001291}
1292
Alexander Musmane4e893b2014-09-23 09:33:00 +00001293void CodeGenFunction::EmitOMPParallelForSimdDirective(
1294 const OMPParallelForSimdDirective &) {
1295 llvm_unreachable("CodeGen for 'omp parallel for simd' is not supported yet.");
1296}
1297
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001298void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001299 const OMPParallelSectionsDirective &S) {
1300 // Emit directive as a combined directive that consists of two implicit
1301 // directives: 'parallel' with 'sections' directive.
1302 LexicalScope Scope(*this, S.getSourceRange());
1303 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1304 (void)emitSections(CGF, S);
1305 // Emit implicit barrier at the end of parallel region.
1306 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1307 OMPD_parallel);
1308 };
1309 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001310}
1311
Alexey Bataev62b63b12015-03-10 07:28:44 +00001312void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1313 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001314 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001315 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1316 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1317 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001318 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001319 // The first function argument for tasks is a thread id, the second one is a
1320 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001321 auto &&CodeGen = [PartId, &S](CodeGenFunction &CGF) {
1322 if (*PartId) {
1323 // TODO: emit code for untied tasks.
1324 }
1325 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1326 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00001327 auto OutlinedFn =
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001328 CGM.getOpenMPRuntime().emitTaskOutlinedFunction(S, *I, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001329 // Check if we should emit tied or untied task.
1330 bool Tied = !S.getSingleClause(OMPC_untied);
1331 // Check if the task is final
1332 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
1333 if (auto *Clause = S.getSingleClause(OMPC_final)) {
1334 // If the condition constant folds and can be elided, try to avoid emitting
1335 // the condition and the dead arm of the if/else.
1336 auto *Cond = cast<OMPFinalClause>(Clause)->getCondition();
1337 bool CondConstant;
1338 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1339 Final.setInt(CondConstant);
1340 else
1341 Final.setPointer(EvaluateExprAsBool(Cond));
1342 } else {
1343 // By default the task is not final.
1344 Final.setInt(/*IntVal=*/false);
1345 }
1346 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00001347 const Expr *IfCond = nullptr;
1348 if (auto C = S.getSingleClause(OMPC_if)) {
1349 IfCond = cast<OMPIfClause>(C)->getCondition();
1350 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001351 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getLocStart(), Tied, Final,
Alexey Bataev1d677132015-04-22 13:57:31 +00001352 OutlinedFn, SharedsTy, CapturedStruct,
1353 IfCond);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001354}
1355
Alexey Bataev9f797f32015-02-05 05:57:51 +00001356void CodeGenFunction::EmitOMPTaskyieldDirective(
1357 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001358 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001359}
1360
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001361void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001362 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001363}
1364
Alexey Bataev2df347a2014-07-18 10:17:07 +00001365void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &) {
1366 llvm_unreachable("CodeGen for 'omp taskwait' is not supported yet.");
1367}
1368
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001369void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001370 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
1371 if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) {
1372 auto FlushClause = cast<OMPFlushClause>(C);
1373 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1374 FlushClause->varlist_end());
1375 }
1376 return llvm::None;
1377 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00001378}
1379
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001380void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
1381 LexicalScope Scope(*this, S.getSourceRange());
1382 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1383 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1384 CGF.EnsureInsertPoint();
1385 };
1386 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001387}
1388
Alexey Bataevb57056f2015-01-22 06:17:56 +00001389static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
1390 QualType SrcType, QualType DestType) {
1391 assert(CGF.hasScalarEvaluationKind(DestType) &&
1392 "DestType must have scalar evaluation kind.");
1393 assert(!Val.isAggregate() && "Must be a scalar or complex.");
1394 return Val.isScalar()
1395 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType)
1396 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
1397 DestType);
1398}
1399
1400static CodeGenFunction::ComplexPairTy
1401convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
1402 QualType DestType) {
1403 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
1404 "DestType must have complex evaluation kind.");
1405 CodeGenFunction::ComplexPairTy ComplexVal;
1406 if (Val.isScalar()) {
1407 // Convert the input element to the element type of the complex.
1408 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1409 auto ScalarVal =
1410 CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestElementType);
1411 ComplexVal = CodeGenFunction::ComplexPairTy(
1412 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
1413 } else {
1414 assert(Val.isComplex() && "Must be a scalar or complex.");
1415 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
1416 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1417 ComplexVal.first = CGF.EmitScalarConversion(
1418 Val.getComplexVal().first, SrcElementType, DestElementType);
1419 ComplexVal.second = CGF.EmitScalarConversion(
1420 Val.getComplexVal().second, SrcElementType, DestElementType);
1421 }
1422 return ComplexVal;
1423}
1424
Alexey Bataev5e018f92015-04-23 06:35:10 +00001425static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
1426 LValue LVal, RValue RVal) {
1427 if (LVal.isGlobalReg()) {
1428 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
1429 } else {
1430 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
1431 : llvm::Monotonic,
1432 LVal.isVolatile(), /*IsInit=*/false);
1433 }
1434}
1435
1436static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal,
1437 QualType RValTy) {
1438 switch (CGF.getEvaluationKind(LVal.getType())) {
1439 case TEK_Scalar:
1440 CGF.EmitStoreThroughLValue(
1441 RValue::get(convertToScalarValue(CGF, RVal, RValTy, LVal.getType())),
1442 LVal);
1443 break;
1444 case TEK_Complex:
1445 CGF.EmitStoreOfComplex(
1446 convertToComplexValue(CGF, RVal, RValTy, LVal.getType()), LVal,
1447 /*isInit=*/false);
1448 break;
1449 case TEK_Aggregate:
1450 llvm_unreachable("Must be a scalar or complex.");
1451 }
1452}
1453
Alexey Bataevb57056f2015-01-22 06:17:56 +00001454static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
1455 const Expr *X, const Expr *V,
1456 SourceLocation Loc) {
1457 // v = x;
1458 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
1459 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
1460 LValue XLValue = CGF.EmitLValue(X);
1461 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00001462 RValue Res = XLValue.isGlobalReg()
1463 ? CGF.EmitLoadOfLValue(XLValue, Loc)
1464 : CGF.EmitAtomicLoad(XLValue, Loc,
1465 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00001466 : llvm::Monotonic,
1467 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001468 // OpenMP, 2.12.6, atomic Construct
1469 // Any atomic construct with a seq_cst clause forces the atomically
1470 // performed operation to include an implicit flush operation without a
1471 // list.
1472 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001473 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001474 emitSimpleStore(CGF,VLValue, Res, X->getType().getNonReferenceType());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001475}
1476
Alexey Bataevb8329262015-02-27 06:33:30 +00001477static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
1478 const Expr *X, const Expr *E,
1479 SourceLocation Loc) {
1480 // x = expr;
1481 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00001482 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00001483 // OpenMP, 2.12.6, atomic Construct
1484 // Any atomic construct with a seq_cst clause forces the atomically
1485 // performed operation to include an implicit flush operation without a
1486 // list.
1487 if (IsSeqCst)
1488 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1489}
1490
Alexey Bataev5e018f92015-04-23 06:35:10 +00001491std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
1492 RValue Update, BinaryOperatorKind BO,
1493 llvm::AtomicOrdering AO,
1494 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001495 auto &Context = CGF.CGM.getContext();
1496 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00001497 // expression is simple and atomic is allowed for the given type for the
1498 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001499 if (BO == BO_Comma || !Update.isScalar() ||
1500 !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() ||
1501 (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
1502 (Update.getScalarVal()->getType() !=
1503 X.getAddress()->getType()->getPointerElementType())) ||
1504 !Context.getTargetInfo().hasBuiltinAtomic(
1505 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00001506 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001507
1508 llvm::AtomicRMWInst::BinOp RMWOp;
1509 switch (BO) {
1510 case BO_Add:
1511 RMWOp = llvm::AtomicRMWInst::Add;
1512 break;
1513 case BO_Sub:
1514 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00001515 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001516 RMWOp = llvm::AtomicRMWInst::Sub;
1517 break;
1518 case BO_And:
1519 RMWOp = llvm::AtomicRMWInst::And;
1520 break;
1521 case BO_Or:
1522 RMWOp = llvm::AtomicRMWInst::Or;
1523 break;
1524 case BO_Xor:
1525 RMWOp = llvm::AtomicRMWInst::Xor;
1526 break;
1527 case BO_LT:
1528 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1529 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
1530 : llvm::AtomicRMWInst::Max)
1531 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
1532 : llvm::AtomicRMWInst::UMax);
1533 break;
1534 case BO_GT:
1535 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1536 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
1537 : llvm::AtomicRMWInst::Min)
1538 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
1539 : llvm::AtomicRMWInst::UMin);
1540 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001541 case BO_Assign:
1542 RMWOp = llvm::AtomicRMWInst::Xchg;
1543 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001544 case BO_Mul:
1545 case BO_Div:
1546 case BO_Rem:
1547 case BO_Shl:
1548 case BO_Shr:
1549 case BO_LAnd:
1550 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001551 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001552 case BO_PtrMemD:
1553 case BO_PtrMemI:
1554 case BO_LE:
1555 case BO_GE:
1556 case BO_EQ:
1557 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001558 case BO_AddAssign:
1559 case BO_SubAssign:
1560 case BO_AndAssign:
1561 case BO_OrAssign:
1562 case BO_XorAssign:
1563 case BO_MulAssign:
1564 case BO_DivAssign:
1565 case BO_RemAssign:
1566 case BO_ShlAssign:
1567 case BO_ShrAssign:
1568 case BO_Comma:
1569 llvm_unreachable("Unsupported atomic update operation");
1570 }
1571 auto *UpdateVal = Update.getScalarVal();
1572 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
1573 UpdateVal = CGF.Builder.CreateIntCast(
1574 IC, X.getAddress()->getType()->getPointerElementType(),
1575 X.getType()->hasSignedIntegerRepresentation());
1576 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001577 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getAddress(), UpdateVal, AO);
1578 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001579}
1580
Alexey Bataev5e018f92015-04-23 06:35:10 +00001581std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001582 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
1583 llvm::AtomicOrdering AO, SourceLocation Loc,
1584 const llvm::function_ref<RValue(RValue)> &CommonGen) {
1585 // Update expressions are allowed to have the following forms:
1586 // x binop= expr; -> xrval + expr;
1587 // x++, ++x -> xrval + 1;
1588 // x--, --x -> xrval - 1;
1589 // x = x binop expr; -> xrval binop expr
1590 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001591 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
1592 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001593 if (X.isGlobalReg()) {
1594 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
1595 // 'xrval'.
1596 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
1597 } else {
1598 // Perform compare-and-swap procedure.
1599 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00001600 }
1601 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001602 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001603}
1604
1605static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
1606 const Expr *X, const Expr *E,
1607 const Expr *UE, bool IsXLHSInRHSPart,
1608 SourceLocation Loc) {
1609 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1610 "Update expr in 'atomic update' must be a binary operator.");
1611 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1612 // Update expressions are allowed to have the following forms:
1613 // x binop= expr; -> xrval + expr;
1614 // x++, ++x -> xrval + 1;
1615 // x--, --x -> xrval - 1;
1616 // x = x binop expr; -> xrval binop expr
1617 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001618 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00001619 LValue XLValue = CGF.EmitLValue(X);
1620 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001621 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001622 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1623 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1624 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1625 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1626 auto Gen =
1627 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
1628 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1629 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1630 return CGF.EmitAnyExpr(UE);
1631 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00001632 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
1633 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1634 // OpenMP, 2.12.6, atomic Construct
1635 // Any atomic construct with a seq_cst clause forces the atomically
1636 // performed operation to include an implicit flush operation without a
1637 // list.
1638 if (IsSeqCst)
1639 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1640}
1641
1642static RValue convertToType(CodeGenFunction &CGF, RValue Value,
1643 QualType SourceType, QualType ResType) {
1644 switch (CGF.getEvaluationKind(ResType)) {
1645 case TEK_Scalar:
1646 return RValue::get(convertToScalarValue(CGF, Value, SourceType, ResType));
1647 case TEK_Complex: {
1648 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType);
1649 return RValue::getComplex(Res.first, Res.second);
1650 }
1651 case TEK_Aggregate:
1652 break;
1653 }
1654 llvm_unreachable("Must be a scalar or complex.");
1655}
1656
1657static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
1658 bool IsPostfixUpdate, const Expr *V,
1659 const Expr *X, const Expr *E,
1660 const Expr *UE, bool IsXLHSInRHSPart,
1661 SourceLocation Loc) {
1662 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
1663 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
1664 RValue NewVVal;
1665 LValue VLValue = CGF.EmitLValue(V);
1666 LValue XLValue = CGF.EmitLValue(X);
1667 RValue ExprRValue = CGF.EmitAnyExpr(E);
1668 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
1669 QualType NewVValType;
1670 if (UE) {
1671 // 'x' is updated with some additional value.
1672 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1673 "Update expr in 'atomic capture' must be a binary operator.");
1674 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1675 // Update expressions are allowed to have the following forms:
1676 // x binop= expr; -> xrval + expr;
1677 // x++, ++x -> xrval + 1;
1678 // x--, --x -> xrval - 1;
1679 // x = x binop expr; -> xrval binop expr
1680 // x = expr Op x; - > expr binop xrval;
1681 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1682 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1683 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1684 NewVValType = XRValExpr->getType();
1685 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1686 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
1687 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
1688 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1689 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1690 RValue Res = CGF.EmitAnyExpr(UE);
1691 NewVVal = IsPostfixUpdate ? XRValue : Res;
1692 return Res;
1693 };
1694 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1695 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1696 if (Res.first) {
1697 // 'atomicrmw' instruction was generated.
1698 if (IsPostfixUpdate) {
1699 // Use old value from 'atomicrmw'.
1700 NewVVal = Res.second;
1701 } else {
1702 // 'atomicrmw' does not provide new value, so evaluate it using old
1703 // value of 'x'.
1704 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1705 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
1706 NewVVal = CGF.EmitAnyExpr(UE);
1707 }
1708 }
1709 } else {
1710 // 'x' is simply rewritten with some 'expr'.
1711 NewVValType = X->getType().getNonReferenceType();
1712 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
1713 X->getType().getNonReferenceType());
1714 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
1715 NewVVal = XRValue;
1716 return ExprRValue;
1717 };
1718 // Try to perform atomicrmw xchg, otherwise simple exchange.
1719 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1720 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
1721 Loc, Gen);
1722 if (Res.first) {
1723 // 'atomicrmw' instruction was generated.
1724 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
1725 }
1726 }
1727 // Emit post-update store to 'v' of old/new 'x' value.
1728 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001729 // OpenMP, 2.12.6, atomic Construct
1730 // Any atomic construct with a seq_cst clause forces the atomically
1731 // performed operation to include an implicit flush operation without a
1732 // list.
1733 if (IsSeqCst)
1734 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1735}
1736
Alexey Bataevb57056f2015-01-22 06:17:56 +00001737static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00001738 bool IsSeqCst, bool IsPostfixUpdate,
1739 const Expr *X, const Expr *V, const Expr *E,
1740 const Expr *UE, bool IsXLHSInRHSPart,
1741 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001742 switch (Kind) {
1743 case OMPC_read:
1744 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
1745 break;
1746 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00001747 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
1748 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001749 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001750 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00001751 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
1752 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001753 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001754 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
1755 IsXLHSInRHSPart, Loc);
1756 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001757 case OMPC_if:
1758 case OMPC_final:
1759 case OMPC_num_threads:
1760 case OMPC_private:
1761 case OMPC_firstprivate:
1762 case OMPC_lastprivate:
1763 case OMPC_reduction:
1764 case OMPC_safelen:
1765 case OMPC_collapse:
1766 case OMPC_default:
1767 case OMPC_seq_cst:
1768 case OMPC_shared:
1769 case OMPC_linear:
1770 case OMPC_aligned:
1771 case OMPC_copyin:
1772 case OMPC_copyprivate:
1773 case OMPC_flush:
1774 case OMPC_proc_bind:
1775 case OMPC_schedule:
1776 case OMPC_ordered:
1777 case OMPC_nowait:
1778 case OMPC_untied:
1779 case OMPC_threadprivate:
1780 case OMPC_mergeable:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001781 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
1782 }
1783}
1784
1785void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
1786 bool IsSeqCst = S.getSingleClause(/*K=*/OMPC_seq_cst);
1787 OpenMPClauseKind Kind = OMPC_unknown;
1788 for (auto *C : S.clauses()) {
1789 // Find first clause (skip seq_cst clause, if it is first).
1790 if (C->getClauseKind() != OMPC_seq_cst) {
1791 Kind = C->getClauseKind();
1792 break;
1793 }
1794 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001795
1796 const auto *CS =
1797 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001798 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00001799 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001800 }
1801 // Processing for statements under 'atomic capture'.
1802 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
1803 for (const auto *C : Compound->body()) {
1804 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
1805 enterFullExpression(EWC);
1806 }
1807 }
1808 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001809
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001810 LexicalScope Scope(*this, S.getSourceRange());
1811 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00001812 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
1813 S.getV(), S.getExpr(), S.getUpdateExpr(),
1814 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001815 };
1816 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00001817}
1818
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001819void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) {
1820 llvm_unreachable("CodeGen for 'omp target' is not supported yet.");
1821}
1822
Alexey Bataev13314bf2014-10-09 04:18:56 +00001823void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
1824 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
1825}