blob: fd475ba590da9f27e49b0a4bc878ca09e3047498 [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 Bataevd74d0602014-10-13 06:02:40 +000026/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
27/// function. Here is the logic:
28/// if (Cond) {
29/// CodeGen(true);
30/// } else {
31/// CodeGen(false);
32/// }
33static void EmitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
34 const std::function<void(bool)> &CodeGen) {
35 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
36
37 // If the condition constant folds and can be elided, try to avoid emitting
38 // the condition and the dead arm of the if/else.
39 bool CondConstant;
40 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
41 CodeGen(CondConstant);
42 return;
43 }
44
45 // Otherwise, the condition did not fold, or we couldn't elide it. Just
46 // emit the conditional branch.
47 auto ThenBlock = CGF.createBasicBlock(/*name*/ "omp_if.then");
48 auto ElseBlock = CGF.createBasicBlock(/*name*/ "omp_if.else");
49 auto ContBlock = CGF.createBasicBlock(/*name*/ "omp_if.end");
50 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount*/ 0);
51
52 // Emit the 'then' code.
53 CGF.EmitBlock(ThenBlock);
54 CodeGen(/*ThenBlock*/ true);
55 CGF.EmitBranch(ContBlock);
56 // Emit the 'else' code if present.
57 {
58 // There is no need to emit line number for unconditional branch.
Adrian Prantl95b24e92015-02-03 20:00:54 +000059 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd74d0602014-10-13 06:02:40 +000060 CGF.EmitBlock(ElseBlock);
61 }
62 CodeGen(/*ThenBlock*/ false);
63 {
64 // There is no need to emit line number for unconditional branch.
Adrian Prantl95b24e92015-02-03 20:00:54 +000065 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd74d0602014-10-13 06:02:40 +000066 CGF.EmitBranch(ContBlock);
67 }
68 // Emit the continuation block for code after the if.
69 CGF.EmitBlock(ContBlock, /*IsFinished*/ true);
70}
71
Alexey Bataev4a5bb772014-10-08 14:01:46 +000072void CodeGenFunction::EmitOMPAggregateAssign(LValue OriginalAddr,
73 llvm::Value *PrivateAddr,
74 const Expr *AssignExpr,
75 QualType OriginalType,
76 const VarDecl *VDInit) {
77 EmitBlock(createBasicBlock(".omp.assign.begin."));
78 if (!isa<CXXConstructExpr>(AssignExpr) || isTrivialInitializer(AssignExpr)) {
79 // Perform simple memcpy.
80 EmitAggregateAssign(PrivateAddr, OriginalAddr.getAddress(),
81 AssignExpr->getType());
82 } else {
83 // Perform element-by-element initialization.
84 QualType ElementTy;
85 auto SrcBegin = OriginalAddr.getAddress();
86 auto DestBegin = PrivateAddr;
87 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
88 auto SrcNumElements = emitArrayLength(ArrayTy, ElementTy, SrcBegin);
89 auto DestNumElements = emitArrayLength(ArrayTy, ElementTy, DestBegin);
90 auto SrcEnd = Builder.CreateGEP(SrcBegin, SrcNumElements);
91 auto DestEnd = Builder.CreateGEP(DestBegin, DestNumElements);
92 // The basic structure here is a do-while loop, because we don't
93 // need to check for the zero-element case.
94 auto BodyBB = createBasicBlock("omp.arraycpy.body");
95 auto DoneBB = createBasicBlock("omp.arraycpy.done");
96 auto IsEmpty =
97 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
98 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
99
100 // Enter the loop body, making that address the current address.
101 auto EntryBB = Builder.GetInsertBlock();
102 EmitBlock(BodyBB);
103 auto SrcElementPast = Builder.CreatePHI(SrcBegin->getType(), 2,
104 "omp.arraycpy.srcElementPast");
105 SrcElementPast->addIncoming(SrcEnd, EntryBB);
106 auto DestElementPast = Builder.CreatePHI(DestBegin->getType(), 2,
107 "omp.arraycpy.destElementPast");
108 DestElementPast->addIncoming(DestEnd, EntryBB);
109
110 // Shift the address back by one element.
111 auto NegativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
112 auto DestElement = Builder.CreateGEP(DestElementPast, NegativeOne,
113 "omp.arraycpy.dest.element");
114 auto SrcElement = Builder.CreateGEP(SrcElementPast, NegativeOne,
115 "omp.arraycpy.src.element");
116 {
117 // Create RunCleanScope to cleanup possible temps.
118 CodeGenFunction::RunCleanupsScope Init(*this);
119 // Emit initialization for single element.
120 LocalDeclMap[VDInit] = SrcElement;
121 EmitAnyExprToMem(AssignExpr, DestElement,
122 AssignExpr->getType().getQualifiers(),
123 /*IsInitializer*/ false);
124 LocalDeclMap.erase(VDInit);
125 }
126
127 // Check whether we've reached the end.
128 auto Done =
129 Builder.CreateICmpEQ(DestElement, DestBegin, "omp.arraycpy.done");
130 Builder.CreateCondBr(Done, DoneBB, BodyBB);
131 DestElementPast->addIncoming(DestElement, Builder.GetInsertBlock());
132 SrcElementPast->addIncoming(SrcElement, Builder.GetInsertBlock());
133
134 // Done.
135 EmitBlock(DoneBB, true);
136 }
137 EmitBlock(createBasicBlock(".omp.assign.end."));
138}
139
140void CodeGenFunction::EmitOMPFirstprivateClause(
141 const OMPExecutableDirective &D,
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000142 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000143 auto PrivateFilter = [](const OMPClause *C) -> bool {
144 return C->getClauseKind() == OMPC_firstprivate;
145 };
146 for (OMPExecutableDirective::filtered_clause_iterator<decltype(PrivateFilter)>
147 I(D.clauses(), PrivateFilter); I; ++I) {
148 auto *C = cast<OMPFirstprivateClause>(*I);
149 auto IRef = C->varlist_begin();
150 auto InitsRef = C->inits().begin();
151 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000152 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
153 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
154 bool IsRegistered;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000155 if (*InitsRef != nullptr) {
156 // Emit VarDecl with copy init for arrays.
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000157 auto *FD = CapturedStmtInfo->lookup(OrigVD);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000158 LValue Base = MakeNaturalAlignAddrLValue(
159 CapturedStmtInfo->getContextValue(),
160 getContext().getTagDeclType(FD->getParent()));
161 auto OriginalAddr = EmitLValueForField(Base, FD);
162 auto VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000163 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value * {
164 auto Emission = EmitAutoVarAlloca(*VD);
165 // Emit initialization of aggregate firstprivate vars.
166 EmitOMPAggregateAssign(OriginalAddr, Emission.getAllocatedAddress(),
167 VD->getInit(), (*IRef)->getType(), VDInit);
168 EmitAutoVarCleanups(Emission);
169 return Emission.getAllocatedAddress();
170 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000171 } else
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000172 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value * {
173 // Emit private VarDecl with copy init.
174 EmitDecl(*VD);
175 return GetAddrOfLocalVar(VD);
176 });
Alexander Musman7931b982015-03-16 07:14:41 +0000177 assert(IsRegistered && "firstprivate var already registered as private");
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000178 // Silence the warning about unused variable.
179 (void)IsRegistered;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000180 ++IRef, ++InitsRef;
181 }
182 }
183}
184
Alexey Bataev03b340a2014-10-21 03:16:40 +0000185void CodeGenFunction::EmitOMPPrivateClause(
186 const OMPExecutableDirective &D,
187 CodeGenFunction::OMPPrivateScope &PrivateScope) {
188 auto PrivateFilter = [](const OMPClause *C) -> bool {
189 return C->getClauseKind() == OMPC_private;
190 };
191 for (OMPExecutableDirective::filtered_clause_iterator<decltype(PrivateFilter)>
192 I(D.clauses(), PrivateFilter); I; ++I) {
193 auto *C = cast<OMPPrivateClause>(*I);
194 auto IRef = C->varlist_begin();
195 for (auto IInit : C->private_copies()) {
196 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
197 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
198 bool IsRegistered =
199 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value * {
200 // Emit private VarDecl with copy init.
201 EmitDecl(*VD);
202 return GetAddrOfLocalVar(VD);
203 });
Alexander Musman7931b982015-03-16 07:14:41 +0000204 assert(IsRegistered && "private var already registered as private");
Alexey Bataev03b340a2014-10-21 03:16:40 +0000205 // Silence the warning about unused variable.
206 (void)IsRegistered;
207 ++IRef;
208 }
209 }
210}
211
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000212void CodeGenFunction::EmitOMPReductionClauseInit(
213 const OMPExecutableDirective &D,
214 CodeGenFunction::OMPPrivateScope &PrivateScope) {
215 auto ReductionFilter = [](const OMPClause *C) -> bool {
216 return C->getClauseKind() == OMPC_reduction;
217 };
218 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
219 ReductionFilter)> I(D.clauses(), ReductionFilter);
220 I; ++I) {
221 auto *C = cast<OMPReductionClause>(*I);
222 auto ILHS = C->lhs_exprs().begin();
223 auto IRHS = C->rhs_exprs().begin();
224 for (auto IRef : C->varlists()) {
225 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
226 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
227 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
228 // Store the address of the original variable associated with the LHS
229 // implicit variable.
230 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> llvm::Value *{
231 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
232 CapturedStmtInfo->lookup(OrigVD) != nullptr,
233 IRef->getType(), VK_LValue, IRef->getExprLoc());
234 return EmitLValue(&DRE).getAddress();
235 });
236 // Emit reduction copy.
237 bool IsRegistered =
238 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> llvm::Value *{
239 // Emit private VarDecl with reduction init.
240 EmitDecl(*PrivateVD);
241 return GetAddrOfLocalVar(PrivateVD);
242 });
243 assert(IsRegistered && "private var already registered as private");
244 // Silence the warning about unused variable.
245 (void)IsRegistered;
246 ++ILHS, ++IRHS;
247 }
248 }
249}
250
251void CodeGenFunction::EmitOMPReductionClauseFinal(
252 const OMPExecutableDirective &D) {
253 llvm::SmallVector<const Expr *, 8> LHSExprs;
254 llvm::SmallVector<const Expr *, 8> RHSExprs;
255 llvm::SmallVector<const Expr *, 8> ReductionOps;
256 auto ReductionFilter = [](const OMPClause *C) -> bool {
257 return C->getClauseKind() == OMPC_reduction;
258 };
259 bool HasAtLeastOneReduction = false;
260 for (OMPExecutableDirective::filtered_clause_iterator<decltype(
261 ReductionFilter)> I(D.clauses(), ReductionFilter);
262 I; ++I) {
263 HasAtLeastOneReduction = true;
264 auto *C = cast<OMPReductionClause>(*I);
265 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
266 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
267 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
268 }
269 if (HasAtLeastOneReduction) {
270 // Emit nowait reduction if nowait clause is present or directive is a
271 // parallel directive (it always has implicit barrier).
272 CGM.getOpenMPRuntime().emitReduction(
273 *this, D.getLocEnd(), LHSExprs, RHSExprs, ReductionOps,
274 D.getSingleClause(OMPC_nowait) ||
275 isOpenMPParallelDirective(D.getDirectiveKind()));
276 }
277}
278
Alexey Bataevb2059782014-10-13 08:23:51 +0000279/// \brief Emits code for OpenMP parallel directive in the parallel region.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000280static void emitOMPParallelCall(CodeGenFunction &CGF,
281 const OMPExecutableDirective &S,
Alexey Bataevb2059782014-10-13 08:23:51 +0000282 llvm::Value *OutlinedFn,
283 llvm::Value *CapturedStruct) {
284 if (auto C = S.getSingleClause(/*K*/ OMPC_num_threads)) {
285 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
286 auto NumThreadsClause = cast<OMPNumThreadsClause>(C);
287 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
288 /*IgnoreResultAssign*/ true);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000289 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
Alexey Bataevb2059782014-10-13 08:23:51 +0000290 CGF, NumThreads, NumThreadsClause->getLocStart());
291 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000292 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
293 CapturedStruct);
Alexey Bataevb2059782014-10-13 08:23:51 +0000294}
295
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000296static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
297 const OMPExecutableDirective &S,
298 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000299 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000300 auto CapturedStruct = CGF.GenerateCapturedStmtArgument(*CS);
301 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
302 S, *CS->getCapturedDecl()->param_begin(), CodeGen);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000303 if (auto C = S.getSingleClause(/*K*/ OMPC_if)) {
304 auto Cond = cast<OMPIfClause>(C)->getCondition();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000305 EmitOMPIfClause(CGF, Cond, [&](bool ThenBlock) {
Alexey Bataevd74d0602014-10-13 06:02:40 +0000306 if (ThenBlock)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000307 emitOMPParallelCall(CGF, S, OutlinedFn, CapturedStruct);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000308 else
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000309 CGF.CGM.getOpenMPRuntime().emitSerialCall(CGF, S.getLocStart(),
310 OutlinedFn, CapturedStruct);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000311 });
Alexey Bataevb2059782014-10-13 08:23:51 +0000312 } else
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000313 emitOMPParallelCall(CGF, S, OutlinedFn, CapturedStruct);
314}
315
316void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
317 LexicalScope Scope(*this, S.getSourceRange());
318 // Emit parallel region as a standalone region.
319 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
320 OMPPrivateScope PrivateScope(CGF);
321 CGF.EmitOMPPrivateClause(S, PrivateScope);
322 CGF.EmitOMPFirstprivateClause(S, PrivateScope);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000323 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000324 if (PrivateScope.Privatize())
325 // Emit implicit barrier to synchronize threads and avoid data races.
326 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
327 OMPD_unknown);
328 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000329 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000330 // Emit implicit barrier at the end of the 'parallel' directive.
331 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
332 OMPD_unknown);
333 };
334 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +0000335}
Alexander Musman515ad8c2014-05-22 08:54:05 +0000336
Alexander Musmand196ef22014-10-07 08:57:09 +0000337void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &S,
Alexander Musmana5f070a2014-10-01 06:03:56 +0000338 bool SeparateIter) {
339 RunCleanupsScope BodyScope(*this);
340 // Update counters values on current iteration.
341 for (auto I : S.updates()) {
342 EmitIgnoredExpr(I);
343 }
Alexander Musman3276a272015-03-21 10:12:56 +0000344 // Update the linear variables.
345 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
346 for (auto U : C->updates()) {
347 EmitIgnoredExpr(U);
348 }
349 }
350
Alexander Musmana5f070a2014-10-01 06:03:56 +0000351 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +0000352 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000353 BreakContinueStack.push_back(BreakContinue(JumpDest(), Continue));
354 // Emit loop body.
355 EmitStmt(S.getBody());
356 // The end (updates/cleanups).
357 EmitBlock(Continue.getBlock());
358 BreakContinueStack.pop_back();
359 if (SeparateIter) {
360 // TODO: Update lastprivates if the SeparateIter flag is true.
361 // This will be implemented in a follow-up OMPLastprivateClause patch, but
362 // result should be still correct without it, as we do not make these
363 // variables private yet.
364 }
365}
366
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000367void CodeGenFunction::EmitOMPInnerLoop(
368 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
369 const Expr *IncExpr,
370 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +0000371 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000372 auto Cnt = getPGORegionCounter(&S);
373
374 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +0000375 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000376 EmitBlock(CondBlock);
377 LoopStack.push(CondBlock);
378
379 // If there are any cleanups between here and the loop-exit scope,
380 // create a block to stage a loop exit along.
381 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +0000382 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +0000383 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000384
Alexander Musmand196ef22014-10-07 08:57:09 +0000385 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000386
Alexey Bataev2df54a02015-03-12 08:53:29 +0000387 // Emit condition.
388 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, Cnt.getCount());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000389 if (ExitBlock != LoopExit.getBlock()) {
390 EmitBlock(ExitBlock);
391 EmitBranchThroughCleanup(LoopExit);
392 }
393
394 EmitBlock(LoopBody);
395 Cnt.beginRegion(Builder);
396
397 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +0000398 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000399 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
400
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000401 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000402
403 // Emit "IV = IV + 1" and a back-edge to the condition block.
404 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +0000405 EmitIgnoredExpr(IncExpr);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000406 BreakContinueStack.pop_back();
407 EmitBranch(CondBlock);
408 LoopStack.pop();
409 // Emit the fall-through block.
410 EmitBlock(LoopExit.getBlock());
411}
412
413void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &S) {
414 auto IC = S.counters().begin();
415 for (auto F : S.finals()) {
416 if (LocalDeclMap.lookup(cast<DeclRefExpr>((*IC))->getDecl())) {
417 EmitIgnoredExpr(F);
418 }
419 ++IC;
420 }
Alexander Musman3276a272015-03-21 10:12:56 +0000421 // Emit the final values of the linear variables.
422 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
423 for (auto F : C->finals()) {
424 EmitIgnoredExpr(F);
425 }
426 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000427}
428
Alexander Musman09184fe2014-09-30 05:29:28 +0000429static void EmitOMPAlignedClause(CodeGenFunction &CGF, CodeGenModule &CGM,
430 const OMPAlignedClause &Clause) {
431 unsigned ClauseAlignment = 0;
432 if (auto AlignmentExpr = Clause.getAlignment()) {
433 auto AlignmentCI =
434 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
435 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
436 }
437 for (auto E : Clause.varlists()) {
438 unsigned Alignment = ClauseAlignment;
439 if (Alignment == 0) {
440 // OpenMP [2.8.1, Description]
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000441 // If no optional parameter is specified, implementation-defined default
Alexander Musman09184fe2014-09-30 05:29:28 +0000442 // alignments for SIMD instructions on the target platforms are assumed.
443 Alignment = CGM.getTargetCodeGenInfo().getOpenMPSimdDefaultAlignment(
444 E->getType());
445 }
446 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
447 "alignment is not power of 2");
448 if (Alignment != 0) {
449 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
450 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
451 }
452 }
453}
454
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000455static void EmitPrivateLoopCounters(CodeGenFunction &CGF,
456 CodeGenFunction::OMPPrivateScope &LoopScope,
457 ArrayRef<Expr *> Counters) {
458 for (auto *E : Counters) {
459 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
460 bool IsRegistered = LoopScope.addPrivate(VD, [&]() -> llvm::Value * {
461 // Emit var without initialization.
462 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
463 CGF.EmitAutoVarCleanups(VarEmission);
464 return VarEmission.getAllocatedAddress();
465 });
466 assert(IsRegistered && "counter already registered as private");
467 // Silence the warning about unused variable.
468 (void)IsRegistered;
469 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000470}
471
Alexander Musman3276a272015-03-21 10:12:56 +0000472static void
473EmitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
474 CodeGenFunction::OMPPrivateScope &PrivateScope) {
475 for (auto Clause : OMPExecutableDirective::linear_filter(D.clauses())) {
476 for (auto *E : Clause->varlists()) {
477 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
478 bool IsRegistered = PrivateScope.addPrivate(VD, [&]()->llvm::Value * {
479 // Emit var without initialization.
480 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
481 CGF.EmitAutoVarCleanups(VarEmission);
482 return VarEmission.getAllocatedAddress();
483 });
484 assert(IsRegistered && "linear var already registered as private");
485 // Silence the warning about unused variable.
486 (void)IsRegistered;
487 }
488 }
489}
490
Alexander Musman515ad8c2014-05-22 08:54:05 +0000491void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000492 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
493 // Pragma 'simd' code depends on presence of 'lastprivate'.
494 // If present, we have to separate last iteration of the loop:
495 //
496 // if (LastIteration != 0) {
497 // for (IV in 0..LastIteration-1) BODY;
498 // BODY with updates of lastprivate vars;
499 // <Final counter/linear vars updates>;
500 // }
501 //
502 // otherwise (when there's no lastprivate):
503 //
504 // for (IV in 0..LastIteration) BODY;
505 // <Final counter/linear vars updates>;
506 //
Alexander Musmana5f070a2014-10-01 06:03:56 +0000507
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000508 // Walk clauses and process safelen/lastprivate.
509 bool SeparateIter = false;
510 CGF.LoopStack.setParallel();
511 CGF.LoopStack.setVectorizerEnable(true);
512 for (auto C : S.clauses()) {
513 switch (C->getClauseKind()) {
514 case OMPC_safelen: {
515 RValue Len = CGF.EmitAnyExpr(cast<OMPSafelenClause>(C)->getSafelen(),
516 AggValueSlot::ignored(), true);
517 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
518 CGF.LoopStack.setVectorizerWidth(Val->getZExtValue());
519 // In presence of finite 'safelen', it may be unsafe to mark all
520 // the memory instructions parallel, because loop-carried
521 // dependences of 'safelen' iterations are possible.
522 CGF.LoopStack.setParallel(false);
523 break;
Alexander Musman3276a272015-03-21 10:12:56 +0000524 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000525 case OMPC_aligned:
526 EmitOMPAlignedClause(CGF, CGF.CGM, cast<OMPAlignedClause>(*C));
527 break;
528 case OMPC_lastprivate:
529 SeparateIter = true;
530 break;
531 default:
532 // Not handled yet
533 ;
534 }
535 }
Alexander Musman3276a272015-03-21 10:12:56 +0000536
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000537 // Emit inits for the linear variables.
538 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
539 for (auto Init : C->inits()) {
540 auto *D = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
541 CGF.EmitVarDecl(*D);
542 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000543 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000544
545 // Emit the loop iteration variable.
546 const Expr *IVExpr = S.getIterationVariable();
547 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
548 CGF.EmitVarDecl(*IVDecl);
549 CGF.EmitIgnoredExpr(S.getInit());
550
551 // Emit the iterations count variable.
552 // If it is not a variable, Sema decided to calculate iterations count on
553 // each
554 // iteration (e.g., it is foldable into a constant).
555 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
556 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
557 // Emit calculation of the iterations count.
558 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000559 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000560
561 // Emit the linear steps for the linear clauses.
562 // If a step is not constant, it is pre-calculated before the loop.
563 for (auto C : OMPExecutableDirective::linear_filter(S.clauses())) {
564 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
565 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
566 CGF.EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
567 // Emit calculation of the linear step.
568 CGF.EmitIgnoredExpr(CS);
569 }
570 }
571
572 if (SeparateIter) {
573 // Emit: if (LastIteration > 0) - begin.
574 RegionCounter Cnt = CGF.getPGORegionCounter(&S);
575 auto ThenBlock = CGF.createBasicBlock("simd.if.then");
576 auto ContBlock = CGF.createBasicBlock("simd.if.end");
577 CGF.EmitBranchOnBoolExpr(S.getPreCond(), ThenBlock, ContBlock,
578 Cnt.getCount());
579 CGF.EmitBlock(ThenBlock);
580 Cnt.beginRegion(CGF.Builder);
581 // Emit 'then' code.
582 {
583 OMPPrivateScope LoopScope(CGF);
584 EmitPrivateLoopCounters(CGF, LoopScope, S.counters());
585 EmitPrivateLinearVars(CGF, S, LoopScope);
586 CGF.EmitOMPPrivateClause(S, LoopScope);
587 (void)LoopScope.Privatize();
588 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
589 S.getCond(/*SeparateIter=*/true), S.getInc(),
590 [&S](CodeGenFunction &CGF) {
591 CGF.EmitOMPLoopBody(S);
592 CGF.EmitStopPoint(&S);
593 });
594 CGF.EmitOMPLoopBody(S, /* SeparateIter */ true);
595 }
596 CGF.EmitOMPSimdFinal(S);
597 // Emit: if (LastIteration != 0) - end.
598 CGF.EmitBranch(ContBlock);
599 CGF.EmitBlock(ContBlock, true);
600 } else {
601 {
602 OMPPrivateScope LoopScope(CGF);
603 EmitPrivateLoopCounters(CGF, LoopScope, S.counters());
604 EmitPrivateLinearVars(CGF, S, LoopScope);
605 CGF.EmitOMPPrivateClause(S, LoopScope);
606 (void)LoopScope.Privatize();
607 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
608 S.getCond(/*SeparateIter=*/false), S.getInc(),
609 [&S](CodeGenFunction &CGF) {
610 CGF.EmitOMPLoopBody(S);
611 CGF.EmitStopPoint(&S);
612 });
613 }
614 CGF.EmitOMPSimdFinal(S);
615 }
616 };
617 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +0000618}
619
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000620void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
621 const OMPLoopDirective &S,
622 OMPPrivateScope &LoopScope,
623 llvm::Value *LB, llvm::Value *UB,
624 llvm::Value *ST, llvm::Value *IL,
625 llvm::Value *Chunk) {
626 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000627
628 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
629 const bool Dynamic = RT.isDynamic(ScheduleKind);
630
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000631 assert(!RT.isStaticNonchunked(ScheduleKind, /* Chunked */ Chunk != nullptr) &&
632 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000633
634 // Emit outer loop.
635 //
636 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +0000637 // When schedule(dynamic,chunk_size) is specified, the iterations are
638 // distributed to threads in the team in chunks as the threads request them.
639 // Each thread executes a chunk of iterations, then requests another chunk,
640 // until no chunks remain to be distributed. Each chunk contains chunk_size
641 // iterations, except for the last chunk to be distributed, which may have
642 // fewer iterations. When no chunk_size is specified, it defaults to 1.
643 //
644 // When schedule(guided,chunk_size) is specified, the iterations are assigned
645 // to threads in the team in chunks as the executing threads request them.
646 // Each thread executes a chunk of iterations, then requests another chunk,
647 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
648 // each chunk is proportional to the number of unassigned iterations divided
649 // by the number of threads in the team, decreasing to 1. For a chunk_size
650 // with value k (greater than 1), the size of each chunk is determined in the
651 // same way, with the restriction that the chunks do not contain fewer than k
652 // iterations (except for the last chunk to be assigned, which may have fewer
653 // than k iterations).
654 //
655 // When schedule(auto) is specified, the decision regarding scheduling is
656 // delegated to the compiler and/or runtime system. The programmer gives the
657 // implementation the freedom to choose any possible mapping of iterations to
658 // threads in the team.
659 //
660 // When schedule(runtime) is specified, the decision regarding scheduling is
661 // deferred until run time, and the schedule and chunk size are taken from the
662 // run-sched-var ICV. If the ICV is set to auto, the schedule is
663 // implementation defined
664 //
665 // while(__kmpc_dispatch_next(&LB, &UB)) {
666 // idx = LB;
667 // while (idx <= UB) { BODY; ++idx; } // inner loop
668 // }
669 //
670 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000671 // When schedule(static, chunk_size) is specified, iterations are divided into
672 // chunks of size chunk_size, and the chunks are assigned to the threads in
673 // the team in a round-robin fashion in the order of the thread number.
674 //
675 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
676 // while (idx <= UB) { BODY; ++idx; } // inner loop
677 // LB = LB + ST;
678 // UB = UB + ST;
679 // }
680 //
Alexander Musman92bdaab2015-03-12 13:37:50 +0000681
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000682 const Expr *IVExpr = S.getIterationVariable();
683 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
684 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
685
Alexander Musman92bdaab2015-03-12 13:37:50 +0000686 RT.emitForInit(
687 *this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, IL, LB,
688 (Dynamic ? EmitAnyExpr(S.getLastIteration()).getScalarVal() : UB), ST,
689 Chunk);
690
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000691 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
692
693 // Start the loop with a block that tests the condition.
694 auto CondBlock = createBasicBlock("omp.dispatch.cond");
695 EmitBlock(CondBlock);
696 LoopStack.push(CondBlock);
697
698 llvm::Value *BoolCondVal = nullptr;
Alexander Musman92bdaab2015-03-12 13:37:50 +0000699 if (!Dynamic) {
700 // UB = min(UB, GlobalUB)
701 EmitIgnoredExpr(S.getEnsureUpperBound());
702 // IV = LB
703 EmitIgnoredExpr(S.getInit());
704 // IV < UB
705 BoolCondVal = EvaluateExprAsBool(S.getCond(false));
706 } else {
707 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
708 IL, LB, UB, ST);
709 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000710
711 // If there are any cleanups between here and the loop-exit scope,
712 // create a block to stage a loop exit along.
713 auto ExitBlock = LoopExit.getBlock();
714 if (LoopScope.requiresCleanups())
715 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
716
717 auto LoopBody = createBasicBlock("omp.dispatch.body");
718 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
719 if (ExitBlock != LoopExit.getBlock()) {
720 EmitBlock(ExitBlock);
721 EmitBranchThroughCleanup(LoopExit);
722 }
723 EmitBlock(LoopBody);
724
Alexander Musman92bdaab2015-03-12 13:37:50 +0000725 // Emit "IV = LB" (in case of static schedule, we have already calculated new
726 // LB for loop condition and emitted it above).
727 if (Dynamic)
728 EmitIgnoredExpr(S.getInit());
729
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000730 // Create a block for the increment.
731 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
732 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
733
Alexey Bataev2df54a02015-03-12 08:53:29 +0000734 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000735 S.getCond(/*SeparateIter=*/false), S.getInc(),
736 [&S](CodeGenFunction &CGF) {
737 CGF.EmitOMPLoopBody(S);
738 CGF.EmitStopPoint(&S);
Alexey Bataev2df54a02015-03-12 08:53:29 +0000739 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000740
741 EmitBlock(Continue.getBlock());
742 BreakContinueStack.pop_back();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000743 if (!Dynamic) {
744 // Emit "LB = LB + Stride", "UB = UB + Stride".
745 EmitIgnoredExpr(S.getNextLowerBound());
746 EmitIgnoredExpr(S.getNextUpperBound());
747 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000748
749 EmitBranch(CondBlock);
750 LoopStack.pop();
751 // Emit the fall-through block.
752 EmitBlock(LoopExit.getBlock());
753
754 // Tell the runtime we are done.
Alexander Musman92bdaab2015-03-12 13:37:50 +0000755 // FIXME: Also call fini for ordered loops with dynamic scheduling.
756 if (!Dynamic)
757 RT.emitForFinish(*this, S.getLocStart(), ScheduleKind);
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000758}
759
Alexander Musmanc6388682014-12-15 07:07:06 +0000760/// \brief Emit a helper variable and return corresponding lvalue.
761static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
762 const DeclRefExpr *Helper) {
763 auto VDecl = cast<VarDecl>(Helper->getDecl());
764 CGF.EmitVarDecl(*VDecl);
765 return CGF.EmitLValue(Helper);
766}
767
768void CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
769 // Emit the loop iteration variable.
770 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
771 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
772 EmitVarDecl(*IVDecl);
773
774 // Emit the iterations count variable.
775 // If it is not a variable, Sema decided to calculate iterations count on each
776 // iteration (e.g., it is foldable into a constant).
777 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
778 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
779 // Emit calculation of the iterations count.
780 EmitIgnoredExpr(S.getCalcLastIteration());
781 }
782
783 auto &RT = CGM.getOpenMPRuntime();
784
785 // Check pre-condition.
786 {
787 // Skip the entire loop if we don't meet the precondition.
788 RegionCounter Cnt = getPGORegionCounter(&S);
789 auto ThenBlock = createBasicBlock("omp.precond.then");
790 auto ContBlock = createBasicBlock("omp.precond.end");
791 EmitBranchOnBoolExpr(S.getPreCond(), ThenBlock, ContBlock, Cnt.getCount());
792 EmitBlock(ThenBlock);
793 Cnt.beginRegion(Builder);
794 // Emit 'then' code.
795 {
796 // Emit helper vars inits.
797 LValue LB =
798 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
799 LValue UB =
800 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
801 LValue ST =
802 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
803 LValue IL =
804 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
805
806 OMPPrivateScope LoopScope(*this);
807 EmitPrivateLoopCounters(*this, LoopScope, S.counters());
Alexander Musman7931b982015-03-16 07:14:41 +0000808 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +0000809
810 // Detect the loop schedule kind and chunk.
811 auto ScheduleKind = OMPC_SCHEDULE_unknown;
812 llvm::Value *Chunk = nullptr;
813 if (auto C = cast_or_null<OMPScheduleClause>(
814 S.getSingleClause(OMPC_schedule))) {
815 ScheduleKind = C->getScheduleKind();
816 if (auto Ch = C->getChunkSize()) {
817 Chunk = EmitScalarExpr(Ch);
818 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
819 S.getIterationVariable()->getType());
820 }
821 }
822 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
823 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
824 if (RT.isStaticNonchunked(ScheduleKind,
825 /* Chunked */ Chunk != nullptr)) {
826 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
827 // When no chunk_size is specified, the iteration space is divided into
828 // chunks that are approximately equal in size, and at most one chunk is
829 // distributed to each thread. Note that the size of the chunks is
830 // unspecified in this case.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000831 RT.emitForInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
832 IL.getAddress(), LB.getAddress(), UB.getAddress(),
833 ST.getAddress());
Alexander Musmanc6388682014-12-15 07:07:06 +0000834 // UB = min(UB, GlobalUB);
835 EmitIgnoredExpr(S.getEnsureUpperBound());
836 // IV = LB;
837 EmitIgnoredExpr(S.getInit());
838 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev2df54a02015-03-12 08:53:29 +0000839 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
840 S.getCond(/*SeparateIter=*/false), S.getInc(),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000841 [&S](CodeGenFunction &CGF) {
842 CGF.EmitOMPLoopBody(S);
843 CGF.EmitStopPoint(&S);
Alexey Bataev2df54a02015-03-12 08:53:29 +0000844 });
Alexander Musmanc6388682014-12-15 07:07:06 +0000845 // Tell the runtime we are done.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000846 RT.emitForFinish(*this, S.getLocStart(), ScheduleKind);
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000847 } else {
848 // Emit the outer loop, which requests its work chunk [LB..UB] from
849 // runtime and runs the inner loop to process it.
850 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, LB.getAddress(),
851 UB.getAddress(), ST.getAddress(), IL.getAddress(),
852 Chunk);
853 }
Alexander Musmanc6388682014-12-15 07:07:06 +0000854 }
855 // We're now done with the loop, so jump to the continuation block.
856 EmitBranch(ContBlock);
857 EmitBlock(ContBlock, true);
858 }
859}
860
861void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000862 LexicalScope Scope(*this, S.getSourceRange());
863 auto &&CodeGen =
864 [&S](CodeGenFunction &CGF) { CGF.EmitOMPWorksharingLoop(S); };
865 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musmanc6388682014-12-15 07:07:06 +0000866
867 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +0000868 if (!S.getSingleClause(OMPC_nowait)) {
869 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
870 }
Alexey Bataevf29276e2014-06-18 04:14:57 +0000871}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +0000872
Alexander Musmanf82886e2014-09-18 05:12:34 +0000873void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &) {
874 llvm_unreachable("CodeGen for 'omp for simd' is not supported yet.");
875}
876
Alexey Bataev2df54a02015-03-12 08:53:29 +0000877static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
878 const Twine &Name,
879 llvm::Value *Init = nullptr) {
880 auto LVal = CGF.MakeNaturalAlignAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
881 if (Init)
882 CGF.EmitScalarInit(Init, LVal);
883 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +0000884}
885
Alexey Bataev68adb7d2015-04-14 03:29:22 +0000886static OpenMPDirectiveKind emitSections(CodeGenFunction &CGF,
887 const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +0000888 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
889 auto *CS = dyn_cast<CompoundStmt>(Stmt);
890 if (CS && CS->size() > 1) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000891 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF) {
892 auto &C = CGF.CGM.getContext();
893 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
894 // Emit helper vars inits.
895 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
896 CGF.Builder.getInt32(0));
897 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
898 LValue UB =
899 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
900 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
901 CGF.Builder.getInt32(1));
902 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
903 CGF.Builder.getInt32(0));
904 // Loop counter.
905 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
906 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +0000907 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000908 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +0000909 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000910 // Generate condition for loop.
911 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
912 OK_Ordinary, S.getLocStart(),
913 /*fpContractable=*/false);
914 // Increment for loop counter.
915 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
916 OK_Ordinary, S.getLocStart());
917 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
918 // Iterate through all sections and emit a switch construct:
919 // switch (IV) {
920 // case 0:
921 // <SectionStmt[0]>;
922 // break;
923 // ...
924 // case <NumSection> - 1:
925 // <SectionStmt[<NumSection> - 1]>;
926 // break;
927 // }
928 // .omp.sections.exit:
929 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
930 auto *SwitchStmt = CGF.Builder.CreateSwitch(
931 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
932 CS->size());
933 unsigned CaseNumber = 0;
934 for (auto C = CS->children(); C; ++C, ++CaseNumber) {
935 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
936 CGF.EmitBlock(CaseBB);
937 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
938 CGF.EmitStmt(*C);
939 CGF.EmitBranch(ExitBB);
940 }
941 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
942 };
943 // Emit static non-chunked loop.
944 CGF.CGM.getOpenMPRuntime().emitForInit(
945 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
946 /*IVSigned=*/true, IL.getAddress(), LB.getAddress(), UB.getAddress(),
947 ST.getAddress());
948 // UB = min(UB, GlobalUB);
949 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
950 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
951 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
952 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
953 // IV = LB;
954 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
955 // while (idx <= UB) { BODY; ++idx; }
956 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen);
957 // Tell the runtime we are done.
958 CGF.CGM.getOpenMPRuntime().emitForFinish(CGF, S.getLocStart(),
959 OMPC_SCHEDULE_static);
Alexey Bataev2df54a02015-03-12 08:53:29 +0000960 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000961
Alexey Bataev68adb7d2015-04-14 03:29:22 +0000962 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, CodeGen);
963 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +0000964 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +0000965 // If only one section is found - no need to generate loop, emit as a single
966 // region.
967 auto &&CodeGen = [Stmt](CodeGenFunction &CGF) {
968 CGF.EmitStmt(Stmt);
969 CGF.EnsureInsertPoint();
970 };
971 CGF.CGM.getOpenMPRuntime().emitSingleRegion(CGF, CodeGen, S.getLocStart(),
972 llvm::None, llvm::None,
973 llvm::None, llvm::None);
974 return OMPD_single;
975}
Alexey Bataev2df54a02015-03-12 08:53:29 +0000976
Alexey Bataev68adb7d2015-04-14 03:29:22 +0000977void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
978 LexicalScope Scope(*this, S.getSourceRange());
979 OpenMPDirectiveKind EmittedAs = emitSections(*this, S);
Alexey Bataev2df54a02015-03-12 08:53:29 +0000980 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +0000981 if (!S.getSingleClause(OMPC_nowait)) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +0000982 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +0000983 }
Alexey Bataev2df54a02015-03-12 08:53:29 +0000984}
985
986void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000987 LexicalScope Scope(*this, S.getSourceRange());
988 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
989 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
990 CGF.EnsureInsertPoint();
991 };
992 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev1e0498a2014-06-26 08:21:58 +0000993}
994
Alexey Bataev6956e2e2015-02-05 06:35:41 +0000995void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +0000996 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
997 llvm::SmallVector<const Expr *, 8> SrcExprs;
998 llvm::SmallVector<const Expr *, 8> DstExprs;
999 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001000 // Check if there are any 'copyprivate' clauses associated with this
1001 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001002 // construct.
1003 auto CopyprivateFilter = [](const OMPClause *C) -> bool {
1004 return C->getClauseKind() == OMPC_copyprivate;
1005 };
1006 // Build a list of copyprivate variables along with helper expressions
1007 // (<source>, <destination>, <destination>=<source> expressions)
1008 typedef OMPExecutableDirective::filtered_clause_iterator<decltype(
1009 CopyprivateFilter)> CopyprivateIter;
1010 for (CopyprivateIter I(S.clauses(), CopyprivateFilter); I; ++I) {
1011 auto *C = cast<OMPCopyprivateClause>(*I);
1012 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
1013 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
1014 DstExprs.append(C->destination_exprs().begin(),
1015 C->destination_exprs().end());
1016 AssignmentOps.append(C->assignment_ops().begin(),
1017 C->assignment_ops().end());
1018 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001019 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001020 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001021 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1022 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1023 CGF.EnsureInsertPoint();
1024 };
1025 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
1026 CopyprivateVars, SrcExprs, DstExprs,
1027 AssignmentOps);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001028 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001029 if (!S.getSingleClause(OMPC_nowait)) {
1030 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_single);
1031 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001032}
1033
Alexey Bataev8d690652014-12-04 07:23:53 +00001034void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001035 LexicalScope Scope(*this, S.getSourceRange());
1036 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1037 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1038 CGF.EnsureInsertPoint();
1039 };
1040 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001041}
1042
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001043void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001044 LexicalScope Scope(*this, S.getSourceRange());
1045 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1046 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1047 CGF.EnsureInsertPoint();
1048 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001049 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001050 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001051}
1052
Alexey Bataev671605e2015-04-13 05:28:11 +00001053void CodeGenFunction::EmitOMPParallelForDirective(
1054 const OMPParallelForDirective &S) {
1055 // Emit directive as a combined directive that consists of two implicit
1056 // directives: 'parallel' with 'for' directive.
1057 LexicalScope Scope(*this, S.getSourceRange());
1058 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1059 CGF.EmitOMPWorksharingLoop(S);
1060 // Emit implicit barrier at the end of parallel region, but this barrier
1061 // is at the end of 'for' directive, so emit it as the implicit barrier for
1062 // this 'for' directive.
1063 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1064 OMPD_parallel);
1065 };
1066 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001067}
1068
Alexander Musmane4e893b2014-09-23 09:33:00 +00001069void CodeGenFunction::EmitOMPParallelForSimdDirective(
1070 const OMPParallelForSimdDirective &) {
1071 llvm_unreachable("CodeGen for 'omp parallel for simd' is not supported yet.");
1072}
1073
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001074void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001075 const OMPParallelSectionsDirective &S) {
1076 // Emit directive as a combined directive that consists of two implicit
1077 // directives: 'parallel' with 'sections' directive.
1078 LexicalScope Scope(*this, S.getSourceRange());
1079 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1080 (void)emitSections(CGF, S);
1081 // Emit implicit barrier at the end of parallel region.
1082 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1083 OMPD_parallel);
1084 };
1085 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001086}
1087
Alexey Bataev62b63b12015-03-10 07:28:44 +00001088void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1089 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001090 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001091 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1092 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1093 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001094 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001095 // The first function argument for tasks is a thread id, the second one is a
1096 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001097 auto &&CodeGen = [PartId, &S](CodeGenFunction &CGF) {
1098 if (*PartId) {
1099 // TODO: emit code for untied tasks.
1100 }
1101 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1102 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00001103 auto OutlinedFn =
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001104 CGM.getOpenMPRuntime().emitTaskOutlinedFunction(S, *I, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001105 // Check if we should emit tied or untied task.
1106 bool Tied = !S.getSingleClause(OMPC_untied);
1107 // Check if the task is final
1108 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
1109 if (auto *Clause = S.getSingleClause(OMPC_final)) {
1110 // If the condition constant folds and can be elided, try to avoid emitting
1111 // the condition and the dead arm of the if/else.
1112 auto *Cond = cast<OMPFinalClause>(Clause)->getCondition();
1113 bool CondConstant;
1114 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1115 Final.setInt(CondConstant);
1116 else
1117 Final.setPointer(EvaluateExprAsBool(Cond));
1118 } else {
1119 // By default the task is not final.
1120 Final.setInt(/*IntVal=*/false);
1121 }
1122 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
1123 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getLocStart(), Tied, Final,
1124 OutlinedFn, SharedsTy, CapturedStruct);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001125}
1126
Alexey Bataev9f797f32015-02-05 05:57:51 +00001127void CodeGenFunction::EmitOMPTaskyieldDirective(
1128 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001129 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001130}
1131
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001132void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001133 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001134}
1135
Alexey Bataev2df347a2014-07-18 10:17:07 +00001136void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &) {
1137 llvm_unreachable("CodeGen for 'omp taskwait' is not supported yet.");
1138}
1139
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001140void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001141 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
1142 if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) {
1143 auto FlushClause = cast<OMPFlushClause>(C);
1144 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1145 FlushClause->varlist_end());
1146 }
1147 return llvm::None;
1148 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00001149}
1150
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001151void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &) {
1152 llvm_unreachable("CodeGen for 'omp ordered' is not supported yet.");
1153}
1154
Alexey Bataevb57056f2015-01-22 06:17:56 +00001155static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
1156 QualType SrcType, QualType DestType) {
1157 assert(CGF.hasScalarEvaluationKind(DestType) &&
1158 "DestType must have scalar evaluation kind.");
1159 assert(!Val.isAggregate() && "Must be a scalar or complex.");
1160 return Val.isScalar()
1161 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType)
1162 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
1163 DestType);
1164}
1165
1166static CodeGenFunction::ComplexPairTy
1167convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
1168 QualType DestType) {
1169 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
1170 "DestType must have complex evaluation kind.");
1171 CodeGenFunction::ComplexPairTy ComplexVal;
1172 if (Val.isScalar()) {
1173 // Convert the input element to the element type of the complex.
1174 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1175 auto ScalarVal =
1176 CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestElementType);
1177 ComplexVal = CodeGenFunction::ComplexPairTy(
1178 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
1179 } else {
1180 assert(Val.isComplex() && "Must be a scalar or complex.");
1181 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
1182 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1183 ComplexVal.first = CGF.EmitScalarConversion(
1184 Val.getComplexVal().first, SrcElementType, DestElementType);
1185 ComplexVal.second = CGF.EmitScalarConversion(
1186 Val.getComplexVal().second, SrcElementType, DestElementType);
1187 }
1188 return ComplexVal;
1189}
1190
1191static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
1192 const Expr *X, const Expr *V,
1193 SourceLocation Loc) {
1194 // v = x;
1195 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
1196 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
1197 LValue XLValue = CGF.EmitLValue(X);
1198 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00001199 RValue Res = XLValue.isGlobalReg()
1200 ? CGF.EmitLoadOfLValue(XLValue, Loc)
1201 : CGF.EmitAtomicLoad(XLValue, Loc,
1202 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00001203 : llvm::Monotonic,
1204 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001205 // OpenMP, 2.12.6, atomic Construct
1206 // Any atomic construct with a seq_cst clause forces the atomically
1207 // performed operation to include an implicit flush operation without a
1208 // list.
1209 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001210 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001211 switch (CGF.getEvaluationKind(V->getType())) {
1212 case TEK_Scalar:
1213 CGF.EmitStoreOfScalar(
1214 convertToScalarValue(CGF, Res, X->getType(), V->getType()), VLValue);
1215 break;
1216 case TEK_Complex:
1217 CGF.EmitStoreOfComplex(
1218 convertToComplexValue(CGF, Res, X->getType(), V->getType()), VLValue,
1219 /*isInit=*/false);
1220 break;
1221 case TEK_Aggregate:
1222 llvm_unreachable("Must be a scalar or complex.");
1223 }
1224}
1225
Alexey Bataevb8329262015-02-27 06:33:30 +00001226static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
1227 const Expr *X, const Expr *E,
1228 SourceLocation Loc) {
1229 // x = expr;
1230 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
1231 LValue XLValue = CGF.EmitLValue(X);
1232 RValue ExprRValue = CGF.EmitAnyExpr(E);
1233 if (XLValue.isGlobalReg())
1234 CGF.EmitStoreThroughGlobalRegLValue(ExprRValue, XLValue);
1235 else
1236 CGF.EmitAtomicStore(ExprRValue, XLValue,
1237 IsSeqCst ? llvm::SequentiallyConsistent
1238 : llvm::Monotonic,
1239 XLValue.isVolatile(), /*IsInit=*/false);
1240 // OpenMP, 2.12.6, atomic Construct
1241 // Any atomic construct with a seq_cst clause forces the atomically
1242 // performed operation to include an implicit flush operation without a
1243 // list.
1244 if (IsSeqCst)
1245 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1246}
1247
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001248bool emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X, RValue Update,
1249 BinaryOperatorKind BO, llvm::AtomicOrdering AO,
1250 bool IsXLHSInRHSPart) {
1251 auto &Context = CGF.CGM.getContext();
1252 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00001253 // expression is simple and atomic is allowed for the given type for the
1254 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001255 if (BO == BO_Comma || !Update.isScalar() ||
1256 !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() ||
1257 (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
1258 (Update.getScalarVal()->getType() !=
1259 X.getAddress()->getType()->getPointerElementType())) ||
1260 !Context.getTargetInfo().hasBuiltinAtomic(
1261 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
1262 return false;
1263
1264 llvm::AtomicRMWInst::BinOp RMWOp;
1265 switch (BO) {
1266 case BO_Add:
1267 RMWOp = llvm::AtomicRMWInst::Add;
1268 break;
1269 case BO_Sub:
1270 if (!IsXLHSInRHSPart)
1271 return false;
1272 RMWOp = llvm::AtomicRMWInst::Sub;
1273 break;
1274 case BO_And:
1275 RMWOp = llvm::AtomicRMWInst::And;
1276 break;
1277 case BO_Or:
1278 RMWOp = llvm::AtomicRMWInst::Or;
1279 break;
1280 case BO_Xor:
1281 RMWOp = llvm::AtomicRMWInst::Xor;
1282 break;
1283 case BO_LT:
1284 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1285 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
1286 : llvm::AtomicRMWInst::Max)
1287 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
1288 : llvm::AtomicRMWInst::UMax);
1289 break;
1290 case BO_GT:
1291 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1292 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
1293 : llvm::AtomicRMWInst::Min)
1294 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
1295 : llvm::AtomicRMWInst::UMin);
1296 break;
1297 case BO_Mul:
1298 case BO_Div:
1299 case BO_Rem:
1300 case BO_Shl:
1301 case BO_Shr:
1302 case BO_LAnd:
1303 case BO_LOr:
1304 return false;
1305 case BO_PtrMemD:
1306 case BO_PtrMemI:
1307 case BO_LE:
1308 case BO_GE:
1309 case BO_EQ:
1310 case BO_NE:
1311 case BO_Assign:
1312 case BO_AddAssign:
1313 case BO_SubAssign:
1314 case BO_AndAssign:
1315 case BO_OrAssign:
1316 case BO_XorAssign:
1317 case BO_MulAssign:
1318 case BO_DivAssign:
1319 case BO_RemAssign:
1320 case BO_ShlAssign:
1321 case BO_ShrAssign:
1322 case BO_Comma:
1323 llvm_unreachable("Unsupported atomic update operation");
1324 }
1325 auto *UpdateVal = Update.getScalarVal();
1326 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
1327 UpdateVal = CGF.Builder.CreateIntCast(
1328 IC, X.getAddress()->getType()->getPointerElementType(),
1329 X.getType()->hasSignedIntegerRepresentation());
1330 }
1331 CGF.Builder.CreateAtomicRMW(RMWOp, X.getAddress(), UpdateVal, AO);
1332 return true;
1333}
1334
1335void CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
1336 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
1337 llvm::AtomicOrdering AO, SourceLocation Loc,
1338 const llvm::function_ref<RValue(RValue)> &CommonGen) {
1339 // Update expressions are allowed to have the following forms:
1340 // x binop= expr; -> xrval + expr;
1341 // x++, ++x -> xrval + 1;
1342 // x--, --x -> xrval - 1;
1343 // x = x binop expr; -> xrval binop expr
1344 // x = expr Op x; - > expr binop xrval;
1345 if (!emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart)) {
1346 if (X.isGlobalReg()) {
1347 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
1348 // 'xrval'.
1349 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
1350 } else {
1351 // Perform compare-and-swap procedure.
1352 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00001353 }
1354 }
Alexey Bataevb4505a72015-03-30 05:20:59 +00001355}
1356
1357static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
1358 const Expr *X, const Expr *E,
1359 const Expr *UE, bool IsXLHSInRHSPart,
1360 SourceLocation Loc) {
1361 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1362 "Update expr in 'atomic update' must be a binary operator.");
1363 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1364 // Update expressions are allowed to have the following forms:
1365 // x binop= expr; -> xrval + expr;
1366 // x++, ++x -> xrval + 1;
1367 // x--, --x -> xrval - 1;
1368 // x = x binop expr; -> xrval binop expr
1369 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001370 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00001371 LValue XLValue = CGF.EmitLValue(X);
1372 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001373 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001374 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1375 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1376 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1377 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1378 auto Gen =
1379 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
1380 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1381 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1382 return CGF.EmitAnyExpr(UE);
1383 };
1384 CGF.EmitOMPAtomicSimpleUpdateExpr(XLValue, ExprRValue, BOUE->getOpcode(),
1385 IsXLHSInRHSPart, AO, Loc, Gen);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001386 // OpenMP, 2.12.6, atomic Construct
1387 // Any atomic construct with a seq_cst clause forces the atomically
1388 // performed operation to include an implicit flush operation without a
1389 // list.
1390 if (IsSeqCst)
1391 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1392}
1393
Alexey Bataevb57056f2015-01-22 06:17:56 +00001394static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
1395 bool IsSeqCst, const Expr *X, const Expr *V,
Alexey Bataevb4505a72015-03-30 05:20:59 +00001396 const Expr *E, const Expr *UE,
1397 bool IsXLHSInRHSPart, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001398 switch (Kind) {
1399 case OMPC_read:
1400 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
1401 break;
1402 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00001403 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
1404 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001405 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001406 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00001407 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
1408 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001409 case OMPC_capture:
1410 llvm_unreachable("CodeGen for 'omp atomic clause' is not supported yet.");
1411 case OMPC_if:
1412 case OMPC_final:
1413 case OMPC_num_threads:
1414 case OMPC_private:
1415 case OMPC_firstprivate:
1416 case OMPC_lastprivate:
1417 case OMPC_reduction:
1418 case OMPC_safelen:
1419 case OMPC_collapse:
1420 case OMPC_default:
1421 case OMPC_seq_cst:
1422 case OMPC_shared:
1423 case OMPC_linear:
1424 case OMPC_aligned:
1425 case OMPC_copyin:
1426 case OMPC_copyprivate:
1427 case OMPC_flush:
1428 case OMPC_proc_bind:
1429 case OMPC_schedule:
1430 case OMPC_ordered:
1431 case OMPC_nowait:
1432 case OMPC_untied:
1433 case OMPC_threadprivate:
1434 case OMPC_mergeable:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001435 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
1436 }
1437}
1438
1439void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
1440 bool IsSeqCst = S.getSingleClause(/*K=*/OMPC_seq_cst);
1441 OpenMPClauseKind Kind = OMPC_unknown;
1442 for (auto *C : S.clauses()) {
1443 // Find first clause (skip seq_cst clause, if it is first).
1444 if (C->getClauseKind() != OMPC_seq_cst) {
1445 Kind = C->getClauseKind();
1446 break;
1447 }
1448 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001449
1450 const auto *CS =
1451 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
1452 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS))
1453 enterFullExpression(EWC);
Alexey Bataev10fec572015-03-11 04:48:56 +00001454
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001455 LexicalScope Scope(*this, S.getSourceRange());
1456 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
1457 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.getX(), S.getV(), S.getExpr(),
1458 S.getUpdateExpr(), S.isXLHSInRHSPart(), S.getLocStart());
1459 };
1460 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00001461}
1462
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001463void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) {
1464 llvm_unreachable("CodeGen for 'omp target' is not supported yet.");
1465}
1466
Alexey Bataev13314bf2014-10-09 04:18:56 +00001467void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
1468 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
1469}
1470