blob: 07fc6e966af6d1d2deebacfb520990d22dae1663 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit OpenMP nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGOpenMPRuntime.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000017#include "TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000018#include "clang/AST/Stmt.h"
19#include "clang/AST/StmtOpenMP.h"
20using namespace clang;
21using namespace CodeGen;
22
23//===----------------------------------------------------------------------===//
24// OpenMP Directive Emission
25//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +000026void CodeGenFunction::EmitOMPAggregateAssign(
27 llvm::Value *DestAddr, llvm::Value *SrcAddr, QualType OriginalType,
28 const llvm::function_ref<void(llvm::Value *, llvm::Value *)> &CopyGen) {
29 // Perform element-by-element initialization.
30 QualType ElementTy;
31 auto SrcBegin = SrcAddr;
32 auto DestBegin = DestAddr;
33 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
34 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestBegin);
35 // Cast from pointer to array type to pointer to single element.
36 SrcBegin = Builder.CreatePointerBitCastOrAddrSpaceCast(SrcBegin,
37 DestBegin->getType());
38 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
39 // The basic structure here is a while-do loop.
40 auto BodyBB = createBasicBlock("omp.arraycpy.body");
41 auto DoneBB = createBasicBlock("omp.arraycpy.done");
42 auto IsEmpty =
43 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
44 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000045
Alexey Bataev420d45b2015-04-14 05:11:24 +000046 // Enter the loop body, making that address the current address.
47 auto EntryBB = Builder.GetInsertBlock();
48 EmitBlock(BodyBB);
49 auto SrcElementCurrent =
50 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
51 SrcElementCurrent->addIncoming(SrcBegin, EntryBB);
52 auto DestElementCurrent = Builder.CreatePHI(DestBegin->getType(), 2,
53 "omp.arraycpy.destElementPast");
54 DestElementCurrent->addIncoming(DestBegin, EntryBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000055
Alexey Bataev420d45b2015-04-14 05:11:24 +000056 // Emit copy.
57 CopyGen(DestElementCurrent, SrcElementCurrent);
58
59 // Shift the address forward by one element.
60 auto DestElementNext = Builder.CreateConstGEP1_32(
61 DestElementCurrent, /*Idx0=*/1, "omp.arraycpy.dest.element");
62 auto SrcElementNext = Builder.CreateConstGEP1_32(
63 SrcElementCurrent, /*Idx0=*/1, "omp.arraycpy.src.element");
64 // Check whether we've reached the end.
65 auto Done =
66 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
67 Builder.CreateCondBr(Done, DoneBB, BodyBB);
68 DestElementCurrent->addIncoming(DestElementNext, Builder.GetInsertBlock());
69 SrcElementCurrent->addIncoming(SrcElementNext, Builder.GetInsertBlock());
70
71 // Done.
72 EmitBlock(DoneBB, /*IsFinished=*/true);
73}
74
75void CodeGenFunction::EmitOMPCopy(CodeGenFunction &CGF,
76 QualType OriginalType, llvm::Value *DestAddr,
77 llvm::Value *SrcAddr, const VarDecl *DestVD,
78 const VarDecl *SrcVD, const Expr *Copy) {
79 if (OriginalType->isArrayType()) {
80 auto *BO = dyn_cast<BinaryOperator>(Copy);
81 if (BO && BO->getOpcode() == BO_Assign) {
82 // Perform simple memcpy for simple copying.
83 CGF.EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
84 } else {
85 // For arrays with complex element types perform element by element
86 // copying.
87 CGF.EmitOMPAggregateAssign(
88 DestAddr, SrcAddr, OriginalType,
89 [&CGF, Copy, SrcVD, DestVD](llvm::Value *DestElement,
90 llvm::Value *SrcElement) {
91 // Working with the single array element, so have to remap
92 // destination and source variables to corresponding array
93 // elements.
94 CodeGenFunction::OMPPrivateScope Remap(CGF);
95 Remap.addPrivate(DestVD, [DestElement]() -> llvm::Value *{
96 return DestElement;
97 });
98 Remap.addPrivate(
99 SrcVD, [SrcElement]() -> llvm::Value *{ return SrcElement; });
100 (void)Remap.Privatize();
101 CGF.EmitIgnoredExpr(Copy);
102 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000103 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000104 } else {
105 // Remap pseudo source variable to private copy.
106 CodeGenFunction::OMPPrivateScope Remap(CGF);
107 Remap.addPrivate(SrcVD, [SrcAddr]() -> llvm::Value *{ return SrcAddr; });
108 Remap.addPrivate(DestVD, [DestAddr]() -> llvm::Value *{ return DestAddr; });
109 (void)Remap.Privatize();
110 // Emit copying of the whole variable.
111 CGF.EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000112 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000113}
114
Alexey Bataev69c62a92015-04-15 04:52:20 +0000115bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
116 OMPPrivateScope &PrivateScope) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000117 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000118 for (auto &&I = D.getClausesOfKind(OMPC_firstprivate); I; ++I) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000119 auto *C = cast<OMPFirstprivateClause>(*I);
120 auto IRef = C->varlist_begin();
121 auto InitsRef = C->inits().begin();
122 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000123 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000124 if (EmittedAsFirstprivate.count(OrigVD) == 0) {
125 EmittedAsFirstprivate.insert(OrigVD);
126 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
127 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
128 bool IsRegistered;
129 DeclRefExpr DRE(
130 const_cast<VarDecl *>(OrigVD),
131 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
132 OrigVD) != nullptr,
133 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
134 auto *OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000135 QualType Type = OrigVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000136 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000137 // Emit VarDecl with copy init for arrays.
138 // Get the address of the original variable captured in current
139 // captured region.
140 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
141 auto Emission = EmitAutoVarAlloca(*VD);
142 auto *Init = VD->getInit();
143 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
144 // Perform simple memcpy.
145 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000146 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000147 } else {
148 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000149 Emission.getAllocatedAddress(), OriginalAddr, Type,
Alexey Bataev69c62a92015-04-15 04:52:20 +0000150 [this, VDInit, Init](llvm::Value *DestElement,
151 llvm::Value *SrcElement) {
152 // Clean up any temporaries needed by the initialization.
153 RunCleanupsScope InitScope(*this);
154 // Emit initialization for single element.
155 LocalDeclMap[VDInit] = SrcElement;
156 EmitAnyExprToMem(Init, DestElement,
157 Init->getType().getQualifiers(),
158 /*IsInitializer*/ false);
159 LocalDeclMap.erase(VDInit);
160 });
161 }
162 EmitAutoVarCleanups(Emission);
163 return Emission.getAllocatedAddress();
164 });
165 } else {
166 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
167 // Emit private VarDecl with copy init.
168 // Remap temp VDInit variable to the address of the original
169 // variable
170 // (for proper handling of captured global variables).
171 LocalDeclMap[VDInit] = OriginalAddr;
172 EmitDecl(*VD);
173 LocalDeclMap.erase(VDInit);
174 return GetAddrOfLocalVar(VD);
175 });
176 }
177 assert(IsRegistered &&
178 "firstprivate var already registered as private");
179 // Silence the warning about unused variable.
180 (void)IsRegistered;
181 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000182 ++IRef, ++InitsRef;
183 }
184 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000185 return !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000186}
187
Alexey Bataev03b340a2014-10-21 03:16:40 +0000188void CodeGenFunction::EmitOMPPrivateClause(
189 const OMPExecutableDirective &D,
190 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev50a64582015-04-22 12:24:45 +0000191 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000192 for (auto &&I = D.getClausesOfKind(OMPC_private); I; ++I) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000193 auto *C = cast<OMPPrivateClause>(*I);
194 auto IRef = C->varlist_begin();
195 for (auto IInit : C->private_copies()) {
196 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000197 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
198 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
199 bool IsRegistered =
200 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
201 // Emit private VarDecl with copy init.
202 EmitDecl(*VD);
203 return GetAddrOfLocalVar(VD);
204 });
205 assert(IsRegistered && "private var already registered as private");
206 // Silence the warning about unused variable.
207 (void)IsRegistered;
208 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000209 ++IRef;
210 }
211 }
212}
213
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000214bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
215 // threadprivate_var1 = master_threadprivate_var1;
216 // operator=(threadprivate_var2, master_threadprivate_var2);
217 // ...
218 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000219 llvm::DenseSet<const VarDecl *> CopiedVars;
220 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000221 for (auto &&I = D.getClausesOfKind(OMPC_copyin); I; ++I) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000222 auto *C = cast<OMPCopyinClause>(*I);
223 auto IRef = C->varlist_begin();
224 auto ISrcRef = C->source_exprs().begin();
225 auto IDestRef = C->destination_exprs().begin();
226 for (auto *AssignOp : C->assignment_ops()) {
227 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000228 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000229 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
230 // Get the address of the master variable.
231 auto *MasterAddr = VD->isStaticLocal()
232 ? CGM.getStaticLocalDeclAddress(VD)
233 : CGM.GetAddrOfGlobal(VD);
234 // Get the address of the threadprivate variable.
235 auto *PrivateAddr = EmitLValue(*IRef).getAddress();
236 if (CopiedVars.size() == 1) {
237 // At first check if current thread is a master thread. If it is, no
238 // need to copy data.
239 CopyBegin = createBasicBlock("copyin.not.master");
240 CopyEnd = createBasicBlock("copyin.not.master.end");
241 Builder.CreateCondBr(
242 Builder.CreateICmpNE(
243 Builder.CreatePtrToInt(MasterAddr, CGM.IntPtrTy),
244 Builder.CreatePtrToInt(PrivateAddr, CGM.IntPtrTy)),
245 CopyBegin, CopyEnd);
246 EmitBlock(CopyBegin);
247 }
248 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
249 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000250 EmitOMPCopy(*this, Type, PrivateAddr, MasterAddr, DestVD, SrcVD,
251 AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000252 }
253 ++IRef;
254 ++ISrcRef;
255 ++IDestRef;
256 }
257 }
258 if (CopyEnd) {
259 // Exit out of copying procedure for non-master thread.
260 EmitBlock(CopyEnd, /*IsFinished=*/true);
261 return true;
262 }
263 return false;
264}
265
Alexey Bataev38e89532015-04-16 04:54:05 +0000266bool CodeGenFunction::EmitOMPLastprivateClauseInit(
267 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000268 bool HasAtLeastOneLastprivate = false;
269 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000270 for (auto &&I = D.getClausesOfKind(OMPC_lastprivate); I; ++I) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000271 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000272 auto *C = cast<OMPLastprivateClause>(*I);
273 auto IRef = C->varlist_begin();
274 auto IDestRef = C->destination_exprs().begin();
275 for (auto *IInit : C->private_copies()) {
276 // Keep the address of the original variable for future update at the end
277 // of the loop.
278 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
279 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
280 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
281 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> llvm::Value *{
282 DeclRefExpr DRE(
283 const_cast<VarDecl *>(OrigVD),
284 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
285 OrigVD) != nullptr,
286 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
287 return EmitLValue(&DRE).getAddress();
288 });
289 // Check if the variable is also a firstprivate: in this case IInit is
290 // not generated. Initialization of this variable will happen in codegen
291 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000292 if (IInit) {
293 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
294 bool IsRegistered =
295 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
296 // Emit private VarDecl with copy init.
297 EmitDecl(*VD);
298 return GetAddrOfLocalVar(VD);
299 });
300 assert(IsRegistered &&
301 "lastprivate var already registered as private");
302 (void)IsRegistered;
303 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000304 }
305 ++IRef, ++IDestRef;
306 }
307 }
308 return HasAtLeastOneLastprivate;
309}
310
311void CodeGenFunction::EmitOMPLastprivateClauseFinal(
312 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
313 // Emit following code:
314 // if (<IsLastIterCond>) {
315 // orig_var1 = private_orig_var1;
316 // ...
317 // orig_varn = private_orig_varn;
318 // }
319 auto *ThenBB = createBasicBlock(".omp.lastprivate.then");
320 auto *DoneBB = createBasicBlock(".omp.lastprivate.done");
321 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
322 EmitBlock(ThenBB);
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000323 llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
324 const Expr *LastIterVal = nullptr;
325 const Expr *IVExpr = nullptr;
326 const Expr *IncExpr = nullptr;
327 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
328 LastIterVal =
329 cast<VarDecl>(cast<DeclRefExpr>(LoopDirective->getUpperBoundVariable())
330 ->getDecl())
331 ->getAnyInitializer();
332 IVExpr = LoopDirective->getIterationVariable();
333 IncExpr = LoopDirective->getInc();
334 auto IUpdate = LoopDirective->updates().begin();
335 for (auto *E : LoopDirective->counters()) {
336 auto *D = cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
337 LoopCountersAndUpdates[D] = *IUpdate;
338 ++IUpdate;
339 }
340 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000341 {
Alexey Bataev38e89532015-04-16 04:54:05 +0000342 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000343 bool FirstLCV = true;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000344 for (auto &&I = D.getClausesOfKind(OMPC_lastprivate); I; ++I) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000345 auto *C = cast<OMPLastprivateClause>(*I);
346 auto IRef = C->varlist_begin();
347 auto ISrcRef = C->source_exprs().begin();
348 auto IDestRef = C->destination_exprs().begin();
349 for (auto *AssignOp : C->assignment_ops()) {
350 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000351 QualType Type = PrivateVD->getType();
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000352 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
353 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
354 // If lastprivate variable is a loop control variable for loop-based
355 // directive, update its value before copyin back to original
356 // variable.
357 if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD)) {
358 if (FirstLCV) {
359 EmitAnyExprToMem(LastIterVal, EmitLValue(IVExpr).getAddress(),
360 IVExpr->getType().getQualifiers(),
361 /*IsInitializer=*/false);
362 EmitIgnoredExpr(IncExpr);
363 FirstLCV = false;
364 }
365 EmitIgnoredExpr(UpExpr);
366 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000367 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
368 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
369 // Get the address of the original variable.
370 auto *OriginalAddr = GetAddrOfLocalVar(DestVD);
371 // Get the address of the private variable.
372 auto *PrivateAddr = GetAddrOfLocalVar(PrivateVD);
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000373 EmitOMPCopy(*this, Type, OriginalAddr, PrivateAddr, DestVD, SrcVD,
374 AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000375 }
376 ++IRef;
377 ++ISrcRef;
378 ++IDestRef;
379 }
380 }
381 }
382 EmitBlock(DoneBB, /*IsFinished=*/true);
383}
384
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000385void CodeGenFunction::EmitOMPReductionClauseInit(
386 const OMPExecutableDirective &D,
387 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataevc925aa32015-04-27 08:00:32 +0000388 for (auto &&I = D.getClausesOfKind(OMPC_reduction); I; ++I) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000389 auto *C = cast<OMPReductionClause>(*I);
390 auto ILHS = C->lhs_exprs().begin();
391 auto IRHS = C->rhs_exprs().begin();
392 for (auto IRef : C->varlists()) {
393 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
394 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
395 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
396 // Store the address of the original variable associated with the LHS
397 // implicit variable.
398 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> llvm::Value *{
399 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
400 CapturedStmtInfo->lookup(OrigVD) != nullptr,
401 IRef->getType(), VK_LValue, IRef->getExprLoc());
402 return EmitLValue(&DRE).getAddress();
403 });
404 // Emit reduction copy.
405 bool IsRegistered =
406 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> llvm::Value *{
407 // Emit private VarDecl with reduction init.
408 EmitDecl(*PrivateVD);
409 return GetAddrOfLocalVar(PrivateVD);
410 });
411 assert(IsRegistered && "private var already registered as private");
412 // Silence the warning about unused variable.
413 (void)IsRegistered;
414 ++ILHS, ++IRHS;
415 }
416 }
417}
418
419void CodeGenFunction::EmitOMPReductionClauseFinal(
420 const OMPExecutableDirective &D) {
421 llvm::SmallVector<const Expr *, 8> LHSExprs;
422 llvm::SmallVector<const Expr *, 8> RHSExprs;
423 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000424 bool HasAtLeastOneReduction = false;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000425 for (auto &&I = D.getClausesOfKind(OMPC_reduction); I; ++I) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000426 HasAtLeastOneReduction = true;
427 auto *C = cast<OMPReductionClause>(*I);
428 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
429 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
430 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
431 }
432 if (HasAtLeastOneReduction) {
433 // Emit nowait reduction if nowait clause is present or directive is a
434 // parallel directive (it always has implicit barrier).
435 CGM.getOpenMPRuntime().emitReduction(
436 *this, D.getLocEnd(), LHSExprs, RHSExprs, ReductionOps,
437 D.getSingleClause(OMPC_nowait) ||
438 isOpenMPParallelDirective(D.getDirectiveKind()));
439 }
440}
441
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000442static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
443 const OMPExecutableDirective &S,
444 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000445 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000446 auto CapturedStruct = CGF.GenerateCapturedStmtArgument(*CS);
447 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
448 S, *CS->getCapturedDecl()->param_begin(), CodeGen);
Alexey Bataev1d677132015-04-22 13:57:31 +0000449 if (auto C = S.getSingleClause(OMPC_num_threads)) {
450 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
451 auto NumThreadsClause = cast<OMPNumThreadsClause>(C);
452 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
453 /*IgnoreResultAssign*/ true);
454 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
455 CGF, NumThreads, NumThreadsClause->getLocStart());
456 }
457 const Expr *IfCond = nullptr;
458 if (auto C = S.getSingleClause(OMPC_if)) {
459 IfCond = cast<OMPIfClause>(C)->getCondition();
460 }
461 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
462 CapturedStruct, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000463}
464
465void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
466 LexicalScope Scope(*this, S.getSourceRange());
467 // Emit parallel region as a standalone region.
468 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
469 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000470 bool Copyins = CGF.EmitOMPCopyinClause(S);
471 bool Firstprivates = CGF.EmitOMPFirstprivateClause(S, PrivateScope);
472 if (Copyins || Firstprivates) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000473 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000474 // initialization of firstprivate variables or propagation master's thread
475 // values of threadprivate variables to local instances of that variables
476 // of all other implicit threads.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000477 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
478 OMPD_unknown);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000479 }
480 CGF.EmitOMPPrivateClause(S, PrivateScope);
481 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
482 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000483 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000484 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000485 // Emit implicit barrier at the end of the 'parallel' directive.
486 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
487 OMPD_unknown);
488 };
489 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +0000490}
Alexander Musman515ad8c2014-05-22 08:54:05 +0000491
Alexander Musmand196ef22014-10-07 08:57:09 +0000492void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &S,
Alexander Musmana5f070a2014-10-01 06:03:56 +0000493 bool SeparateIter) {
494 RunCleanupsScope BodyScope(*this);
495 // Update counters values on current iteration.
496 for (auto I : S.updates()) {
497 EmitIgnoredExpr(I);
498 }
Alexander Musman3276a272015-03-21 10:12:56 +0000499 // Update the linear variables.
Alexey Bataevc925aa32015-04-27 08:00:32 +0000500 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
501 auto *C = cast<OMPLinearClause>(*I);
Alexander Musman3276a272015-03-21 10:12:56 +0000502 for (auto U : C->updates()) {
503 EmitIgnoredExpr(U);
504 }
505 }
506
Alexander Musmana5f070a2014-10-01 06:03:56 +0000507 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +0000508 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000509 BreakContinueStack.push_back(BreakContinue(JumpDest(), Continue));
510 // Emit loop body.
511 EmitStmt(S.getBody());
512 // The end (updates/cleanups).
513 EmitBlock(Continue.getBlock());
514 BreakContinueStack.pop_back();
515 if (SeparateIter) {
516 // TODO: Update lastprivates if the SeparateIter flag is true.
517 // This will be implemented in a follow-up OMPLastprivateClause patch, but
518 // result should be still correct without it, as we do not make these
519 // variables private yet.
520 }
521}
522
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000523void CodeGenFunction::EmitOMPInnerLoop(
524 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
525 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000526 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
527 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +0000528 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000529
530 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +0000531 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000532 EmitBlock(CondBlock);
533 LoopStack.push(CondBlock);
534
535 // If there are any cleanups between here and the loop-exit scope,
536 // create a block to stage a loop exit along.
537 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +0000538 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +0000539 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000540
Alexander Musmand196ef22014-10-07 08:57:09 +0000541 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000542
Alexey Bataev2df54a02015-03-12 08:53:29 +0000543 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +0000544 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000545 if (ExitBlock != LoopExit.getBlock()) {
546 EmitBlock(ExitBlock);
547 EmitBranchThroughCleanup(LoopExit);
548 }
549
550 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +0000551 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000552
553 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +0000554 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000555 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
556
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000557 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000558
559 // Emit "IV = IV + 1" and a back-edge to the condition block.
560 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +0000561 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000562 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000563 BreakContinueStack.pop_back();
564 EmitBranch(CondBlock);
565 LoopStack.pop();
566 // Emit the fall-through block.
567 EmitBlock(LoopExit.getBlock());
568}
569
570void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &S) {
571 auto IC = S.counters().begin();
572 for (auto F : S.finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000573 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
574 if (LocalDeclMap.lookup(OrigVD)) {
575 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
576 CapturedStmtInfo->lookup(OrigVD) != nullptr,
577 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
578 auto *OrigAddr = EmitLValue(&DRE).getAddress();
579 OMPPrivateScope VarScope(*this);
580 VarScope.addPrivate(OrigVD,
581 [OrigAddr]() -> llvm::Value *{ return OrigAddr; });
582 (void)VarScope.Privatize();
Alexander Musmana5f070a2014-10-01 06:03:56 +0000583 EmitIgnoredExpr(F);
584 }
585 ++IC;
586 }
Alexander Musman3276a272015-03-21 10:12:56 +0000587 // Emit the final values of the linear variables.
Alexey Bataevc925aa32015-04-27 08:00:32 +0000588 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
589 auto *C = cast<OMPLinearClause>(*I);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000590 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +0000591 for (auto F : C->finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000592 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
593 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
594 CapturedStmtInfo->lookup(OrigVD) != nullptr,
595 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
596 auto *OrigAddr = EmitLValue(&DRE).getAddress();
597 OMPPrivateScope VarScope(*this);
598 VarScope.addPrivate(OrigVD,
599 [OrigAddr]() -> llvm::Value *{ return OrigAddr; });
600 (void)VarScope.Privatize();
Alexander Musman3276a272015-03-21 10:12:56 +0000601 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000602 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +0000603 }
604 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000605}
606
Alexander Musman09184fe2014-09-30 05:29:28 +0000607static void EmitOMPAlignedClause(CodeGenFunction &CGF, CodeGenModule &CGM,
608 const OMPAlignedClause &Clause) {
609 unsigned ClauseAlignment = 0;
610 if (auto AlignmentExpr = Clause.getAlignment()) {
611 auto AlignmentCI =
612 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
613 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
614 }
615 for (auto E : Clause.varlists()) {
616 unsigned Alignment = ClauseAlignment;
617 if (Alignment == 0) {
618 // OpenMP [2.8.1, Description]
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000619 // If no optional parameter is specified, implementation-defined default
Alexander Musman09184fe2014-09-30 05:29:28 +0000620 // alignments for SIMD instructions on the target platforms are assumed.
621 Alignment = CGM.getTargetCodeGenInfo().getOpenMPSimdDefaultAlignment(
622 E->getType());
623 }
624 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
625 "alignment is not power of 2");
626 if (Alignment != 0) {
627 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
628 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
629 }
630 }
631}
632
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000633static void EmitPrivateLoopCounters(CodeGenFunction &CGF,
634 CodeGenFunction::OMPPrivateScope &LoopScope,
635 ArrayRef<Expr *> Counters) {
636 for (auto *E : Counters) {
637 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev61114692015-04-28 13:20:05 +0000638 (void)LoopScope.addPrivate(VD, [&]() -> llvm::Value *{
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000639 // Emit var without initialization.
640 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
641 CGF.EmitAutoVarCleanups(VarEmission);
642 return VarEmission.getAllocatedAddress();
643 });
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000644 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000645}
646
Alexey Bataev62dbb972015-04-22 11:59:37 +0000647static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
648 const Expr *Cond, llvm::BasicBlock *TrueBlock,
649 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
650 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
651 EmitPrivateLoopCounters(CGF, PreCondScope, S.counters());
652 const VarDecl *IVDecl =
653 cast<VarDecl>(cast<DeclRefExpr>(S.getIterationVariable())->getDecl());
654 bool IsRegistered = PreCondScope.addPrivate(IVDecl, [&]() -> llvm::Value *{
655 // Emit var without initialization.
656 auto VarEmission = CGF.EmitAutoVarAlloca(*IVDecl);
657 CGF.EmitAutoVarCleanups(VarEmission);
658 return VarEmission.getAllocatedAddress();
659 });
660 assert(IsRegistered && "counter already registered as private");
661 // Silence the warning about unused variable.
662 (void)IsRegistered;
663 (void)PreCondScope.Privatize();
664 // Initialize internal counter to 0 to calculate initial values of real
665 // counters.
666 LValue IV = CGF.EmitLValue(S.getIterationVariable());
667 CGF.EmitStoreOfScalar(
668 llvm::ConstantInt::getNullValue(
669 IV.getAddress()->getType()->getPointerElementType()),
670 CGF.EmitLValue(S.getIterationVariable()), /*isInit=*/true);
671 // Get initial values of real counters.
672 for (auto I : S.updates()) {
673 CGF.EmitIgnoredExpr(I);
674 }
675 // Check that loop is executed at least one time.
676 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
677}
678
Alexander Musman3276a272015-03-21 10:12:56 +0000679static void
680EmitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
681 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataevc925aa32015-04-27 08:00:32 +0000682 for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) {
683 auto *C = cast<OMPLinearClause>(*I);
684 for (auto *E : C->varlists()) {
Alexander Musman3276a272015-03-21 10:12:56 +0000685 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
686 bool IsRegistered = PrivateScope.addPrivate(VD, [&]()->llvm::Value * {
687 // Emit var without initialization.
688 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
689 CGF.EmitAutoVarCleanups(VarEmission);
690 return VarEmission.getAllocatedAddress();
691 });
692 assert(IsRegistered && "linear var already registered as private");
693 // Silence the warning about unused variable.
694 (void)IsRegistered;
695 }
696 }
697}
698
Alexander Musman515ad8c2014-05-22 08:54:05 +0000699void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000700 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
701 // Pragma 'simd' code depends on presence of 'lastprivate'.
702 // If present, we have to separate last iteration of the loop:
703 //
Alexey Bataev62dbb972015-04-22 11:59:37 +0000704 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000705 // for (IV in 0..LastIteration-1) BODY;
706 // BODY with updates of lastprivate vars;
707 // <Final counter/linear vars updates>;
708 // }
709 //
710 // otherwise (when there's no lastprivate):
711 //
Alexey Bataev62dbb972015-04-22 11:59:37 +0000712 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000713 // for (IV in 0..LastIteration) BODY;
714 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000715 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000716 //
Alexander Musmana5f070a2014-10-01 06:03:56 +0000717
Alexey Bataev62dbb972015-04-22 11:59:37 +0000718 // Emit: if (PreCond) - begin.
719 // If the condition constant folds and can be elided, avoid emitting the
720 // whole loop.
721 bool CondConstant;
722 llvm::BasicBlock *ContBlock = nullptr;
723 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
724 if (!CondConstant)
725 return;
726 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000727 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
728 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +0000729 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
730 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +0000731 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +0000732 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000733 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000734 // Walk clauses and process safelen/lastprivate.
735 bool SeparateIter = false;
736 CGF.LoopStack.setParallel();
737 CGF.LoopStack.setVectorizerEnable(true);
738 for (auto C : S.clauses()) {
739 switch (C->getClauseKind()) {
740 case OMPC_safelen: {
741 RValue Len = CGF.EmitAnyExpr(cast<OMPSafelenClause>(C)->getSafelen(),
742 AggValueSlot::ignored(), true);
743 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
744 CGF.LoopStack.setVectorizerWidth(Val->getZExtValue());
745 // In presence of finite 'safelen', it may be unsafe to mark all
746 // the memory instructions parallel, because loop-carried
747 // dependences of 'safelen' iterations are possible.
748 CGF.LoopStack.setParallel(false);
749 break;
Alexander Musman3276a272015-03-21 10:12:56 +0000750 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000751 case OMPC_aligned:
752 EmitOMPAlignedClause(CGF, CGF.CGM, cast<OMPAlignedClause>(*C));
753 break;
754 case OMPC_lastprivate:
755 SeparateIter = true;
756 break;
757 default:
758 // Not handled yet
759 ;
760 }
761 }
Alexander Musman3276a272015-03-21 10:12:56 +0000762
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000763 // Emit inits for the linear variables.
Alexey Bataevc925aa32015-04-27 08:00:32 +0000764 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
765 auto *C = cast<OMPLinearClause>(*I);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000766 for (auto Init : C->inits()) {
767 auto *D = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
768 CGF.EmitVarDecl(*D);
769 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000770 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000771
772 // Emit the loop iteration variable.
773 const Expr *IVExpr = S.getIterationVariable();
774 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
775 CGF.EmitVarDecl(*IVDecl);
776 CGF.EmitIgnoredExpr(S.getInit());
777
778 // Emit the iterations count variable.
779 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000780 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000781 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
782 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
783 // Emit calculation of the iterations count.
784 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000785 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000786
787 // Emit the linear steps for the linear clauses.
788 // If a step is not constant, it is pre-calculated before the loop.
Alexey Bataevc925aa32015-04-27 08:00:32 +0000789 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
790 auto *C = cast<OMPLinearClause>(*I);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000791 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
792 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
793 CGF.EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
794 // Emit calculation of the linear step.
795 CGF.EmitIgnoredExpr(CS);
796 }
797 }
798
Alexey Bataev62dbb972015-04-22 11:59:37 +0000799 {
800 OMPPrivateScope LoopScope(CGF);
801 EmitPrivateLoopCounters(CGF, LoopScope, S.counters());
802 EmitPrivateLinearVars(CGF, S, LoopScope);
803 CGF.EmitOMPPrivateClause(S, LoopScope);
804 (void)LoopScope.Privatize();
805 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
806 S.getCond(SeparateIter), S.getInc(),
807 [&S](CodeGenFunction &CGF) {
808 CGF.EmitOMPLoopBody(S);
809 CGF.EmitStopPoint(&S);
810 },
811 [](CodeGenFunction &) {});
812 if (SeparateIter) {
813 CGF.EmitOMPLoopBody(S, /*SeparateIter=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000814 }
Alexey Bataev62dbb972015-04-22 11:59:37 +0000815 }
816 CGF.EmitOMPSimdFinal(S);
817 // Emit: if (PreCond) - end.
818 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000819 CGF.EmitBranch(ContBlock);
820 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000821 }
822 };
823 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +0000824}
825
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000826void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
827 const OMPLoopDirective &S,
828 OMPPrivateScope &LoopScope,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000829 bool Ordered, llvm::Value *LB,
830 llvm::Value *UB, llvm::Value *ST,
831 llvm::Value *IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000832 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000833
834 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000835 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
Alexander Musman92bdaab2015-03-12 13:37:50 +0000836
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000837 assert((Ordered ||
838 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000839 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000840
841 // Emit outer loop.
842 //
843 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +0000844 // When schedule(dynamic,chunk_size) is specified, the iterations are
845 // distributed to threads in the team in chunks as the threads request them.
846 // Each thread executes a chunk of iterations, then requests another chunk,
847 // until no chunks remain to be distributed. Each chunk contains chunk_size
848 // iterations, except for the last chunk to be distributed, which may have
849 // fewer iterations. When no chunk_size is specified, it defaults to 1.
850 //
851 // When schedule(guided,chunk_size) is specified, the iterations are assigned
852 // to threads in the team in chunks as the executing threads request them.
853 // Each thread executes a chunk of iterations, then requests another chunk,
854 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
855 // each chunk is proportional to the number of unassigned iterations divided
856 // by the number of threads in the team, decreasing to 1. For a chunk_size
857 // with value k (greater than 1), the size of each chunk is determined in the
858 // same way, with the restriction that the chunks do not contain fewer than k
859 // iterations (except for the last chunk to be assigned, which may have fewer
860 // than k iterations).
861 //
862 // When schedule(auto) is specified, the decision regarding scheduling is
863 // delegated to the compiler and/or runtime system. The programmer gives the
864 // implementation the freedom to choose any possible mapping of iterations to
865 // threads in the team.
866 //
867 // When schedule(runtime) is specified, the decision regarding scheduling is
868 // deferred until run time, and the schedule and chunk size are taken from the
869 // run-sched-var ICV. If the ICV is set to auto, the schedule is
870 // implementation defined
871 //
872 // while(__kmpc_dispatch_next(&LB, &UB)) {
873 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000874 // while (idx <= UB) { BODY; ++idx;
875 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
876 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +0000877 // }
878 //
879 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000880 // When schedule(static, chunk_size) is specified, iterations are divided into
881 // chunks of size chunk_size, and the chunks are assigned to the threads in
882 // the team in a round-robin fashion in the order of the thread number.
883 //
884 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
885 // while (idx <= UB) { BODY; ++idx; } // inner loop
886 // LB = LB + ST;
887 // UB = UB + ST;
888 // }
889 //
Alexander Musman92bdaab2015-03-12 13:37:50 +0000890
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000891 const Expr *IVExpr = S.getIterationVariable();
892 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
893 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
894
Alexander Musman92bdaab2015-03-12 13:37:50 +0000895 RT.emitForInit(
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000896 *this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, Ordered, IL, LB,
897 (DynamicOrOrdered ? EmitAnyExpr(S.getLastIteration()).getScalarVal()
898 : UB),
899 ST, Chunk);
Alexander Musman92bdaab2015-03-12 13:37:50 +0000900
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000901 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
902
903 // Start the loop with a block that tests the condition.
904 auto CondBlock = createBasicBlock("omp.dispatch.cond");
905 EmitBlock(CondBlock);
906 LoopStack.push(CondBlock);
907
908 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000909 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +0000910 // UB = min(UB, GlobalUB)
911 EmitIgnoredExpr(S.getEnsureUpperBound());
912 // IV = LB
913 EmitIgnoredExpr(S.getInit());
914 // IV < UB
915 BoolCondVal = EvaluateExprAsBool(S.getCond(false));
916 } else {
917 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
918 IL, LB, UB, ST);
919 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000920
921 // If there are any cleanups between here and the loop-exit scope,
922 // create a block to stage a loop exit along.
923 auto ExitBlock = LoopExit.getBlock();
924 if (LoopScope.requiresCleanups())
925 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
926
927 auto LoopBody = createBasicBlock("omp.dispatch.body");
928 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
929 if (ExitBlock != LoopExit.getBlock()) {
930 EmitBlock(ExitBlock);
931 EmitBranchThroughCleanup(LoopExit);
932 }
933 EmitBlock(LoopBody);
934
Alexander Musman92bdaab2015-03-12 13:37:50 +0000935 // Emit "IV = LB" (in case of static schedule, we have already calculated new
936 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000937 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +0000938 EmitIgnoredExpr(S.getInit());
939
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000940 // Create a block for the increment.
941 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
942 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
943
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000944 SourceLocation Loc = S.getLocStart();
Alexey Bataev53223c92015-05-07 04:25:17 +0000945 // Generate !llvm.loop.parallel metadata for loads and stores for loops with
946 // dynamic/guided scheduling and without ordered clause.
947 LoopStack.setParallel((ScheduleKind == OMPC_SCHEDULE_dynamic ||
948 ScheduleKind == OMPC_SCHEDULE_guided) &&
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000949 !Ordered);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000950 EmitOMPInnerLoop(
951 S, LoopScope.requiresCleanups(), S.getCond(/*SeparateIter=*/false),
952 S.getInc(),
953 [&S](CodeGenFunction &CGF) {
954 CGF.EmitOMPLoopBody(S);
955 CGF.EmitStopPoint(&S);
956 },
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000957 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
958 if (Ordered) {
959 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000960 CGF, Loc, IVSize, IVSigned);
961 }
962 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000963
964 EmitBlock(Continue.getBlock());
965 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000966 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +0000967 // Emit "LB = LB + Stride", "UB = UB + Stride".
968 EmitIgnoredExpr(S.getNextLowerBound());
969 EmitIgnoredExpr(S.getNextUpperBound());
970 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000971
972 EmitBranch(CondBlock);
973 LoopStack.pop();
974 // Emit the fall-through block.
975 EmitBlock(LoopExit.getBlock());
976
977 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000978 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000979 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000980}
981
Alexander Musmanc6388682014-12-15 07:07:06 +0000982/// \brief Emit a helper variable and return corresponding lvalue.
983static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
984 const DeclRefExpr *Helper) {
985 auto VDecl = cast<VarDecl>(Helper->getDecl());
986 CGF.EmitVarDecl(*VDecl);
987 return CGF.EmitLValue(Helper);
988}
989
Alexey Bataev040d5402015-05-12 08:35:28 +0000990static std::pair<llvm::Value * /*Chunk*/, OpenMPScheduleClauseKind>
991emitScheduleClause(CodeGenFunction &CGF, const OMPLoopDirective &S,
992 bool OuterRegion) {
993 // Detect the loop schedule kind and chunk.
994 auto ScheduleKind = OMPC_SCHEDULE_unknown;
995 llvm::Value *Chunk = nullptr;
996 if (auto *C =
997 cast_or_null<OMPScheduleClause>(S.getSingleClause(OMPC_schedule))) {
998 ScheduleKind = C->getScheduleKind();
999 if (const auto *Ch = C->getChunkSize()) {
1000 if (auto *ImpRef = cast_or_null<DeclRefExpr>(C->getHelperChunkSize())) {
1001 if (OuterRegion) {
1002 const VarDecl *ImpVar = cast<VarDecl>(ImpRef->getDecl());
1003 CGF.EmitVarDecl(*ImpVar);
1004 CGF.EmitStoreThroughLValue(
1005 CGF.EmitAnyExpr(Ch),
1006 CGF.MakeNaturalAlignAddrLValue(CGF.GetAddrOfLocalVar(ImpVar),
1007 ImpVar->getType()));
1008 } else {
1009 Ch = ImpRef;
1010 }
1011 }
1012 if (!C->getHelperChunkSize() || !OuterRegion) {
1013 Chunk = CGF.EmitScalarExpr(Ch);
1014 Chunk = CGF.EmitScalarConversion(Chunk, Ch->getType(),
1015 S.getIterationVariable()->getType());
1016 }
1017 }
1018 }
1019 return std::make_pair(Chunk, ScheduleKind);
1020}
1021
Alexey Bataev38e89532015-04-16 04:54:05 +00001022bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001023 // Emit the loop iteration variable.
1024 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1025 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1026 EmitVarDecl(*IVDecl);
1027
1028 // Emit the iterations count variable.
1029 // If it is not a variable, Sema decided to calculate iterations count on each
1030 // iteration (e.g., it is foldable into a constant).
1031 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1032 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1033 // Emit calculation of the iterations count.
1034 EmitIgnoredExpr(S.getCalcLastIteration());
1035 }
1036
1037 auto &RT = CGM.getOpenMPRuntime();
1038
Alexey Bataev38e89532015-04-16 04:54:05 +00001039 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001040 // Check pre-condition.
1041 {
1042 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001043 // If the condition constant folds and can be elided, avoid emitting the
1044 // whole loop.
1045 bool CondConstant;
1046 llvm::BasicBlock *ContBlock = nullptr;
1047 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1048 if (!CondConstant)
1049 return false;
1050 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001051 auto *ThenBlock = createBasicBlock("omp.precond.then");
1052 ContBlock = createBasicBlock("omp.precond.end");
1053 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001054 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001055 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001056 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001057 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001058 // Emit 'then' code.
1059 {
1060 // Emit helper vars inits.
1061 LValue LB =
1062 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1063 LValue UB =
1064 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1065 LValue ST =
1066 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1067 LValue IL =
1068 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1069
1070 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001071 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1072 // Emit implicit barrier to synchronize threads and avoid data races on
1073 // initialization of firstprivate variables.
1074 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1075 OMPD_unknown);
1076 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001077 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001078 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001079 EmitOMPReductionClauseInit(S, LoopScope);
Alexander Musmanc6388682014-12-15 07:07:06 +00001080 EmitPrivateLoopCounters(*this, LoopScope, S.counters());
Alexander Musman7931b982015-03-16 07:14:41 +00001081 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001082
1083 // Detect the loop schedule kind and chunk.
Alexey Bataev040d5402015-05-12 08:35:28 +00001084 llvm::Value *Chunk;
1085 OpenMPScheduleClauseKind ScheduleKind;
1086 auto ScheduleInfo =
1087 emitScheduleClause(*this, S, /*OuterRegion=*/false);
1088 Chunk = ScheduleInfo.first;
1089 ScheduleKind = ScheduleInfo.second;
Alexander Musmanc6388682014-12-15 07:07:06 +00001090 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1091 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001092 const bool Ordered = S.getSingleClause(OMPC_ordered) != nullptr;
Alexander Musmanc6388682014-12-15 07:07:06 +00001093 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001094 /* Chunked */ Chunk != nullptr) &&
1095 !Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001096 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1097 // When no chunk_size is specified, the iteration space is divided into
1098 // chunks that are approximately equal in size, and at most one chunk is
1099 // distributed to each thread. Note that the size of the chunks is
1100 // unspecified in this case.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001101 RT.emitForInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001102 Ordered, IL.getAddress(), LB.getAddress(),
1103 UB.getAddress(), ST.getAddress());
Alexander Musmanc6388682014-12-15 07:07:06 +00001104 // UB = min(UB, GlobalUB);
1105 EmitIgnoredExpr(S.getEnsureUpperBound());
1106 // IV = LB;
1107 EmitIgnoredExpr(S.getInit());
1108 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001109 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
1110 S.getCond(/*SeparateIter=*/false), S.getInc(),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001111 [&S](CodeGenFunction &CGF) {
1112 CGF.EmitOMPLoopBody(S);
1113 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001114 },
1115 [](CodeGenFunction &) {});
Alexander Musmanc6388682014-12-15 07:07:06 +00001116 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001117 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001118 } else {
1119 // Emit the outer loop, which requests its work chunk [LB..UB] from
1120 // runtime and runs the inner loop to process it.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001121 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, Ordered,
1122 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1123 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001124 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001125 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001126 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1127 if (HasLastprivateClause)
1128 EmitOMPLastprivateClauseFinal(
1129 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001130 }
1131 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001132 if (ContBlock) {
1133 EmitBranch(ContBlock);
1134 EmitBlock(ContBlock, true);
1135 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001136 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001137 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001138}
1139
1140void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001141 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev38e89532015-04-16 04:54:05 +00001142 bool HasLastprivates = false;
1143 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1144 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1145 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001146 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musmanc6388682014-12-15 07:07:06 +00001147
1148 // Emit an implicit barrier at the end.
Alexey Bataev38e89532015-04-16 04:54:05 +00001149 if (!S.getSingleClause(OMPC_nowait) || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001150 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1151 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001152}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001153
Alexander Musmanf82886e2014-09-18 05:12:34 +00001154void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &) {
1155 llvm_unreachable("CodeGen for 'omp for simd' is not supported yet.");
1156}
1157
Alexey Bataev2df54a02015-03-12 08:53:29 +00001158static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1159 const Twine &Name,
1160 llvm::Value *Init = nullptr) {
1161 auto LVal = CGF.MakeNaturalAlignAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
1162 if (Init)
1163 CGF.EmitScalarInit(Init, LVal);
1164 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001165}
1166
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001167static OpenMPDirectiveKind emitSections(CodeGenFunction &CGF,
1168 const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001169 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1170 auto *CS = dyn_cast<CompoundStmt>(Stmt);
1171 if (CS && CS->size() > 1) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001172 bool HasLastprivates = false;
1173 auto &&CodeGen = [&S, CS, &HasLastprivates](CodeGenFunction &CGF) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001174 auto &C = CGF.CGM.getContext();
1175 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1176 // Emit helper vars inits.
1177 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1178 CGF.Builder.getInt32(0));
1179 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
1180 LValue UB =
1181 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1182 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1183 CGF.Builder.getInt32(1));
1184 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1185 CGF.Builder.getInt32(0));
1186 // Loop counter.
1187 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1188 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001189 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001190 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001191 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001192 // Generate condition for loop.
1193 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1194 OK_Ordinary, S.getLocStart(),
1195 /*fpContractable=*/false);
1196 // Increment for loop counter.
1197 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
1198 OK_Ordinary, S.getLocStart());
1199 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
1200 // Iterate through all sections and emit a switch construct:
1201 // switch (IV) {
1202 // case 0:
1203 // <SectionStmt[0]>;
1204 // break;
1205 // ...
1206 // case <NumSection> - 1:
1207 // <SectionStmt[<NumSection> - 1]>;
1208 // break;
1209 // }
1210 // .omp.sections.exit:
1211 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1212 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1213 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1214 CS->size());
1215 unsigned CaseNumber = 0;
1216 for (auto C = CS->children(); C; ++C, ++CaseNumber) {
1217 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1218 CGF.EmitBlock(CaseBB);
1219 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
1220 CGF.EmitStmt(*C);
1221 CGF.EmitBranch(ExitBB);
1222 }
1223 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1224 };
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001225
1226 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1227 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
1228 // Emit implicit barrier to synchronize threads and avoid data races on
1229 // initialization of firstprivate variables.
1230 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1231 OMPD_unknown);
1232 }
Alexey Bataev73870832015-04-27 04:12:12 +00001233 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001234 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001235 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001236 (void)LoopScope.Privatize();
1237
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001238 // Emit static non-chunked loop.
1239 CGF.CGM.getOpenMPRuntime().emitForInit(
1240 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001241 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
1242 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001243 // UB = min(UB, GlobalUB);
1244 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1245 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1246 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1247 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1248 // IV = LB;
1249 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1250 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001251 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1252 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001253 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001254 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataeva89adf22015-04-27 05:04:13 +00001255 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001256
1257 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1258 if (HasLastprivates)
1259 CGF.EmitOMPLastprivateClauseFinal(
1260 S, CGF.Builder.CreateIsNotNull(
1261 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev2df54a02015-03-12 08:53:29 +00001262 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001263
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001264 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, CodeGen);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001265 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1266 // clause. Otherwise the barrier will be generated by the codegen for the
1267 // directive.
1268 if (HasLastprivates && S.getSingleClause(OMPC_nowait)) {
1269 // Emit implicit barrier to synchronize threads and avoid data races on
1270 // initialization of firstprivate variables.
1271 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1272 OMPD_unknown);
1273 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001274 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001275 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001276 // If only one section is found - no need to generate loop, emit as a single
1277 // region.
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001278 bool HasFirstprivates;
Alexey Bataeva89adf22015-04-27 05:04:13 +00001279 // No need to generate reductions for sections with single section region, we
1280 // can use original shared variables for all operations.
Alexey Bataevc925aa32015-04-27 08:00:32 +00001281 bool HasReductions = !S.getClausesOfKind(OMPC_reduction).empty();
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001282 // No need to generate lastprivates for sections with single section region,
1283 // we can use original shared variable for all calculations with barrier at
1284 // the end of the sections.
Alexey Bataevc925aa32015-04-27 08:00:32 +00001285 bool HasLastprivates = !S.getClausesOfKind(OMPC_lastprivate).empty();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001286 auto &&CodeGen = [Stmt, &S, &HasFirstprivates](CodeGenFunction &CGF) {
1287 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1288 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev73870832015-04-27 04:12:12 +00001289 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001290 (void)SingleScope.Privatize();
1291
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001292 CGF.EmitStmt(Stmt);
1293 CGF.EnsureInsertPoint();
1294 };
1295 CGF.CGM.getOpenMPRuntime().emitSingleRegion(CGF, CodeGen, S.getLocStart(),
1296 llvm::None, llvm::None,
1297 llvm::None, llvm::None);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001298 // Emit barrier for firstprivates, lastprivates or reductions only if
1299 // 'sections' directive has 'nowait' clause. Otherwise the barrier will be
1300 // generated by the codegen for the directive.
1301 if ((HasFirstprivates || HasLastprivates || HasReductions) &&
1302 S.getSingleClause(OMPC_nowait)) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001303 // Emit implicit barrier to synchronize threads and avoid data races on
1304 // initialization of firstprivate variables.
1305 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1306 OMPD_unknown);
1307 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001308 return OMPD_single;
1309}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001310
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001311void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1312 LexicalScope Scope(*this, S.getSourceRange());
1313 OpenMPDirectiveKind EmittedAs = emitSections(*this, S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001314 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001315 if (!S.getSingleClause(OMPC_nowait)) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001316 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001317 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001318}
1319
1320void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001321 LexicalScope Scope(*this, S.getSourceRange());
1322 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1323 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1324 CGF.EnsureInsertPoint();
1325 };
1326 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001327}
1328
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001329void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001330 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001331 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001332 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001333 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001334 // Check if there are any 'copyprivate' clauses associated with this
1335 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001336 // construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001337 // Build a list of copyprivate variables along with helper expressions
1338 // (<source>, <destination>, <destination>=<source> expressions)
Alexey Bataevc925aa32015-04-27 08:00:32 +00001339 for (auto &&I = S.getClausesOfKind(OMPC_copyprivate); I; ++I) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001340 auto *C = cast<OMPCopyprivateClause>(*I);
1341 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001342 DestExprs.append(C->destination_exprs().begin(),
1343 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001344 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001345 AssignmentOps.append(C->assignment_ops().begin(),
1346 C->assignment_ops().end());
1347 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001348 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001349 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev5521d782015-04-24 04:21:15 +00001350 bool HasFirstprivates;
1351 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) {
1352 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1353 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev59c654a2015-04-27 03:48:52 +00001354 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev5521d782015-04-24 04:21:15 +00001355 (void)SingleScope.Privatize();
1356
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001357 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1358 CGF.EnsureInsertPoint();
1359 };
1360 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001361 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001362 AssignmentOps);
Alexey Bataev5521d782015-04-24 04:21:15 +00001363 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1364 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
1365 if ((!S.getSingleClause(OMPC_nowait) || HasFirstprivates) &&
1366 CopyprivateVars.empty()) {
1367 CGM.getOpenMPRuntime().emitBarrierCall(
1368 *this, S.getLocStart(),
1369 S.getSingleClause(OMPC_nowait) ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001370 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001371}
1372
Alexey Bataev8d690652014-12-04 07:23:53 +00001373void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001374 LexicalScope Scope(*this, S.getSourceRange());
1375 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1376 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1377 CGF.EnsureInsertPoint();
1378 };
1379 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001380}
1381
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001382void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001383 LexicalScope Scope(*this, S.getSourceRange());
1384 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1385 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1386 CGF.EnsureInsertPoint();
1387 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001388 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001389 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001390}
1391
Alexey Bataev671605e2015-04-13 05:28:11 +00001392void CodeGenFunction::EmitOMPParallelForDirective(
1393 const OMPParallelForDirective &S) {
1394 // Emit directive as a combined directive that consists of two implicit
1395 // directives: 'parallel' with 'for' directive.
1396 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev040d5402015-05-12 08:35:28 +00001397 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
Alexey Bataev671605e2015-04-13 05:28:11 +00001398 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1399 CGF.EmitOMPWorksharingLoop(S);
1400 // Emit implicit barrier at the end of parallel region, but this barrier
1401 // is at the end of 'for' directive, so emit it as the implicit barrier for
1402 // this 'for' directive.
1403 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1404 OMPD_parallel);
1405 };
1406 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001407}
1408
Alexander Musmane4e893b2014-09-23 09:33:00 +00001409void CodeGenFunction::EmitOMPParallelForSimdDirective(
1410 const OMPParallelForSimdDirective &) {
1411 llvm_unreachable("CodeGen for 'omp parallel for simd' is not supported yet.");
1412}
1413
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001414void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001415 const OMPParallelSectionsDirective &S) {
1416 // Emit directive as a combined directive that consists of two implicit
1417 // directives: 'parallel' with 'sections' directive.
1418 LexicalScope Scope(*this, S.getSourceRange());
1419 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1420 (void)emitSections(CGF, S);
1421 // Emit implicit barrier at the end of parallel region.
1422 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1423 OMPD_parallel);
1424 };
1425 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001426}
1427
Alexey Bataev62b63b12015-03-10 07:28:44 +00001428void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1429 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001430 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001431 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1432 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1433 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001434 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001435 // The first function argument for tasks is a thread id, the second one is a
1436 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001437 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
1438 // Get list of private variables.
1439 llvm::SmallVector<const Expr *, 8> PrivateVars;
1440 llvm::SmallVector<const Expr *, 8> PrivateCopies;
1441 for (auto &&I = S.getClausesOfKind(OMPC_private); I; ++I) {
1442 auto *C = cast<OMPPrivateClause>(*I);
1443 auto IRef = C->varlist_begin();
1444 for (auto *IInit : C->private_copies()) {
1445 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1446 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1447 PrivateVars.push_back(*IRef);
1448 PrivateCopies.push_back(IInit);
1449 }
1450 ++IRef;
1451 }
1452 }
1453 EmittedAsPrivate.clear();
1454 // Get list of firstprivate variables.
1455 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
1456 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
1457 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
1458 for (auto &&I = S.getClausesOfKind(OMPC_firstprivate); I; ++I) {
1459 auto *C = cast<OMPFirstprivateClause>(*I);
1460 auto IRef = C->varlist_begin();
1461 auto IElemInitRef = C->inits().begin();
1462 for (auto *IInit : C->private_copies()) {
1463 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1464 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1465 FirstprivateVars.push_back(*IRef);
1466 FirstprivateCopies.push_back(IInit);
1467 FirstprivateInits.push_back(*IElemInitRef);
1468 }
1469 ++IRef, ++IElemInitRef;
1470 }
1471 }
1472 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
1473 CodeGenFunction &CGF) {
1474 // Set proper addresses for generated private copies.
1475 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
1476 OMPPrivateScope Scope(CGF);
1477 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
1478 auto *CopyFn = CGF.Builder.CreateAlignedLoad(
1479 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)),
1480 CGF.PointerAlignInBytes);
1481 auto *PrivatesPtr = CGF.Builder.CreateAlignedLoad(
1482 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)),
1483 CGF.PointerAlignInBytes);
1484 // Map privates.
1485 llvm::SmallVector<std::pair<const VarDecl *, llvm::Value *>, 16>
1486 PrivatePtrs;
1487 llvm::SmallVector<llvm::Value *, 16> CallArgs;
1488 CallArgs.push_back(PrivatesPtr);
1489 for (auto *E : PrivateVars) {
1490 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1491 auto *PrivatePtr =
1492 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
1493 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
1494 CallArgs.push_back(PrivatePtr);
1495 }
1496 for (auto *E : FirstprivateVars) {
1497 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1498 auto *PrivatePtr =
1499 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
1500 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
1501 CallArgs.push_back(PrivatePtr);
1502 }
1503 CGF.EmitRuntimeCall(CopyFn, CallArgs);
1504 for (auto &&Pair : PrivatePtrs) {
1505 auto *Replacement =
1506 CGF.Builder.CreateAlignedLoad(Pair.second, CGF.PointerAlignInBytes);
1507 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
1508 }
1509 }
1510 (void)Scope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001511 if (*PartId) {
1512 // TODO: emit code for untied tasks.
1513 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001514 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001515 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00001516 auto OutlinedFn =
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001517 CGM.getOpenMPRuntime().emitTaskOutlinedFunction(S, *I, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001518 // Check if we should emit tied or untied task.
1519 bool Tied = !S.getSingleClause(OMPC_untied);
1520 // Check if the task is final
1521 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
1522 if (auto *Clause = S.getSingleClause(OMPC_final)) {
1523 // If the condition constant folds and can be elided, try to avoid emitting
1524 // the condition and the dead arm of the if/else.
1525 auto *Cond = cast<OMPFinalClause>(Clause)->getCondition();
1526 bool CondConstant;
1527 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1528 Final.setInt(CondConstant);
1529 else
1530 Final.setPointer(EvaluateExprAsBool(Cond));
1531 } else {
1532 // By default the task is not final.
1533 Final.setInt(/*IntVal=*/false);
1534 }
1535 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00001536 const Expr *IfCond = nullptr;
1537 if (auto C = S.getSingleClause(OMPC_if)) {
1538 IfCond = cast<OMPIfClause>(C)->getCondition();
1539 }
Alexey Bataev9e034042015-05-05 04:05:12 +00001540 CGM.getOpenMPRuntime().emitTaskCall(
1541 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001542 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev9e034042015-05-05 04:05:12 +00001543 FirstprivateCopies, FirstprivateInits);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001544}
1545
Alexey Bataev9f797f32015-02-05 05:57:51 +00001546void CodeGenFunction::EmitOMPTaskyieldDirective(
1547 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001548 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001549}
1550
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001551void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001552 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001553}
1554
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001555void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
1556 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00001557}
1558
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001559void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001560 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
1561 if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) {
1562 auto FlushClause = cast<OMPFlushClause>(C);
1563 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1564 FlushClause->varlist_end());
1565 }
1566 return llvm::None;
1567 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00001568}
1569
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001570void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
1571 LexicalScope Scope(*this, S.getSourceRange());
1572 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1573 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1574 CGF.EnsureInsertPoint();
1575 };
1576 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001577}
1578
Alexey Bataevb57056f2015-01-22 06:17:56 +00001579static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
1580 QualType SrcType, QualType DestType) {
1581 assert(CGF.hasScalarEvaluationKind(DestType) &&
1582 "DestType must have scalar evaluation kind.");
1583 assert(!Val.isAggregate() && "Must be a scalar or complex.");
1584 return Val.isScalar()
1585 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType)
1586 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
1587 DestType);
1588}
1589
1590static CodeGenFunction::ComplexPairTy
1591convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
1592 QualType DestType) {
1593 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
1594 "DestType must have complex evaluation kind.");
1595 CodeGenFunction::ComplexPairTy ComplexVal;
1596 if (Val.isScalar()) {
1597 // Convert the input element to the element type of the complex.
1598 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1599 auto ScalarVal =
1600 CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestElementType);
1601 ComplexVal = CodeGenFunction::ComplexPairTy(
1602 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
1603 } else {
1604 assert(Val.isComplex() && "Must be a scalar or complex.");
1605 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
1606 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1607 ComplexVal.first = CGF.EmitScalarConversion(
1608 Val.getComplexVal().first, SrcElementType, DestElementType);
1609 ComplexVal.second = CGF.EmitScalarConversion(
1610 Val.getComplexVal().second, SrcElementType, DestElementType);
1611 }
1612 return ComplexVal;
1613}
1614
Alexey Bataev5e018f92015-04-23 06:35:10 +00001615static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
1616 LValue LVal, RValue RVal) {
1617 if (LVal.isGlobalReg()) {
1618 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
1619 } else {
1620 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
1621 : llvm::Monotonic,
1622 LVal.isVolatile(), /*IsInit=*/false);
1623 }
1624}
1625
1626static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal,
1627 QualType RValTy) {
1628 switch (CGF.getEvaluationKind(LVal.getType())) {
1629 case TEK_Scalar:
1630 CGF.EmitStoreThroughLValue(
1631 RValue::get(convertToScalarValue(CGF, RVal, RValTy, LVal.getType())),
1632 LVal);
1633 break;
1634 case TEK_Complex:
1635 CGF.EmitStoreOfComplex(
1636 convertToComplexValue(CGF, RVal, RValTy, LVal.getType()), LVal,
1637 /*isInit=*/false);
1638 break;
1639 case TEK_Aggregate:
1640 llvm_unreachable("Must be a scalar or complex.");
1641 }
1642}
1643
Alexey Bataevb57056f2015-01-22 06:17:56 +00001644static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
1645 const Expr *X, const Expr *V,
1646 SourceLocation Loc) {
1647 // v = x;
1648 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
1649 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
1650 LValue XLValue = CGF.EmitLValue(X);
1651 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00001652 RValue Res = XLValue.isGlobalReg()
1653 ? CGF.EmitLoadOfLValue(XLValue, Loc)
1654 : CGF.EmitAtomicLoad(XLValue, Loc,
1655 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00001656 : llvm::Monotonic,
1657 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001658 // OpenMP, 2.12.6, atomic Construct
1659 // Any atomic construct with a seq_cst clause forces the atomically
1660 // performed operation to include an implicit flush operation without a
1661 // list.
1662 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001663 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001664 emitSimpleStore(CGF,VLValue, Res, X->getType().getNonReferenceType());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001665}
1666
Alexey Bataevb8329262015-02-27 06:33:30 +00001667static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
1668 const Expr *X, const Expr *E,
1669 SourceLocation Loc) {
1670 // x = expr;
1671 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00001672 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00001673 // OpenMP, 2.12.6, atomic Construct
1674 // Any atomic construct with a seq_cst clause forces the atomically
1675 // performed operation to include an implicit flush operation without a
1676 // list.
1677 if (IsSeqCst)
1678 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1679}
1680
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00001681static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
1682 RValue Update,
1683 BinaryOperatorKind BO,
1684 llvm::AtomicOrdering AO,
1685 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001686 auto &Context = CGF.CGM.getContext();
1687 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00001688 // expression is simple and atomic is allowed for the given type for the
1689 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001690 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00001691 !Update.getScalarVal()->getType()->isIntegerTy() ||
1692 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
1693 (Update.getScalarVal()->getType() !=
1694 X.getAddress()->getType()->getPointerElementType())) ||
1695 !X.getAddress()->getType()->getPointerElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001696 !Context.getTargetInfo().hasBuiltinAtomic(
1697 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00001698 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001699
1700 llvm::AtomicRMWInst::BinOp RMWOp;
1701 switch (BO) {
1702 case BO_Add:
1703 RMWOp = llvm::AtomicRMWInst::Add;
1704 break;
1705 case BO_Sub:
1706 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00001707 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001708 RMWOp = llvm::AtomicRMWInst::Sub;
1709 break;
1710 case BO_And:
1711 RMWOp = llvm::AtomicRMWInst::And;
1712 break;
1713 case BO_Or:
1714 RMWOp = llvm::AtomicRMWInst::Or;
1715 break;
1716 case BO_Xor:
1717 RMWOp = llvm::AtomicRMWInst::Xor;
1718 break;
1719 case BO_LT:
1720 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1721 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
1722 : llvm::AtomicRMWInst::Max)
1723 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
1724 : llvm::AtomicRMWInst::UMax);
1725 break;
1726 case BO_GT:
1727 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1728 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
1729 : llvm::AtomicRMWInst::Min)
1730 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
1731 : llvm::AtomicRMWInst::UMin);
1732 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001733 case BO_Assign:
1734 RMWOp = llvm::AtomicRMWInst::Xchg;
1735 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001736 case BO_Mul:
1737 case BO_Div:
1738 case BO_Rem:
1739 case BO_Shl:
1740 case BO_Shr:
1741 case BO_LAnd:
1742 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001743 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001744 case BO_PtrMemD:
1745 case BO_PtrMemI:
1746 case BO_LE:
1747 case BO_GE:
1748 case BO_EQ:
1749 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001750 case BO_AddAssign:
1751 case BO_SubAssign:
1752 case BO_AndAssign:
1753 case BO_OrAssign:
1754 case BO_XorAssign:
1755 case BO_MulAssign:
1756 case BO_DivAssign:
1757 case BO_RemAssign:
1758 case BO_ShlAssign:
1759 case BO_ShrAssign:
1760 case BO_Comma:
1761 llvm_unreachable("Unsupported atomic update operation");
1762 }
1763 auto *UpdateVal = Update.getScalarVal();
1764 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
1765 UpdateVal = CGF.Builder.CreateIntCast(
1766 IC, X.getAddress()->getType()->getPointerElementType(),
1767 X.getType()->hasSignedIntegerRepresentation());
1768 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001769 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getAddress(), UpdateVal, AO);
1770 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001771}
1772
Alexey Bataev5e018f92015-04-23 06:35:10 +00001773std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001774 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
1775 llvm::AtomicOrdering AO, SourceLocation Loc,
1776 const llvm::function_ref<RValue(RValue)> &CommonGen) {
1777 // Update expressions are allowed to have the following forms:
1778 // x binop= expr; -> xrval + expr;
1779 // x++, ++x -> xrval + 1;
1780 // x--, --x -> xrval - 1;
1781 // x = x binop expr; -> xrval binop expr
1782 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001783 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
1784 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001785 if (X.isGlobalReg()) {
1786 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
1787 // 'xrval'.
1788 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
1789 } else {
1790 // Perform compare-and-swap procedure.
1791 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00001792 }
1793 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001794 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001795}
1796
1797static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
1798 const Expr *X, const Expr *E,
1799 const Expr *UE, bool IsXLHSInRHSPart,
1800 SourceLocation Loc) {
1801 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1802 "Update expr in 'atomic update' must be a binary operator.");
1803 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1804 // Update expressions are allowed to have the following forms:
1805 // x binop= expr; -> xrval + expr;
1806 // x++, ++x -> xrval + 1;
1807 // x--, --x -> xrval - 1;
1808 // x = x binop expr; -> xrval binop expr
1809 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001810 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00001811 LValue XLValue = CGF.EmitLValue(X);
1812 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001813 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001814 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1815 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1816 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1817 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1818 auto Gen =
1819 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
1820 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1821 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1822 return CGF.EmitAnyExpr(UE);
1823 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00001824 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
1825 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1826 // OpenMP, 2.12.6, atomic Construct
1827 // Any atomic construct with a seq_cst clause forces the atomically
1828 // performed operation to include an implicit flush operation without a
1829 // list.
1830 if (IsSeqCst)
1831 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1832}
1833
1834static RValue convertToType(CodeGenFunction &CGF, RValue Value,
1835 QualType SourceType, QualType ResType) {
1836 switch (CGF.getEvaluationKind(ResType)) {
1837 case TEK_Scalar:
1838 return RValue::get(convertToScalarValue(CGF, Value, SourceType, ResType));
1839 case TEK_Complex: {
1840 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType);
1841 return RValue::getComplex(Res.first, Res.second);
1842 }
1843 case TEK_Aggregate:
1844 break;
1845 }
1846 llvm_unreachable("Must be a scalar or complex.");
1847}
1848
1849static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
1850 bool IsPostfixUpdate, const Expr *V,
1851 const Expr *X, const Expr *E,
1852 const Expr *UE, bool IsXLHSInRHSPart,
1853 SourceLocation Loc) {
1854 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
1855 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
1856 RValue NewVVal;
1857 LValue VLValue = CGF.EmitLValue(V);
1858 LValue XLValue = CGF.EmitLValue(X);
1859 RValue ExprRValue = CGF.EmitAnyExpr(E);
1860 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
1861 QualType NewVValType;
1862 if (UE) {
1863 // 'x' is updated with some additional value.
1864 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1865 "Update expr in 'atomic capture' must be a binary operator.");
1866 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1867 // Update expressions are allowed to have the following forms:
1868 // x binop= expr; -> xrval + expr;
1869 // x++, ++x -> xrval + 1;
1870 // x--, --x -> xrval - 1;
1871 // x = x binop expr; -> xrval binop expr
1872 // x = expr Op x; - > expr binop xrval;
1873 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1874 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1875 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1876 NewVValType = XRValExpr->getType();
1877 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1878 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
1879 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
1880 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1881 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1882 RValue Res = CGF.EmitAnyExpr(UE);
1883 NewVVal = IsPostfixUpdate ? XRValue : Res;
1884 return Res;
1885 };
1886 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1887 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1888 if (Res.first) {
1889 // 'atomicrmw' instruction was generated.
1890 if (IsPostfixUpdate) {
1891 // Use old value from 'atomicrmw'.
1892 NewVVal = Res.second;
1893 } else {
1894 // 'atomicrmw' does not provide new value, so evaluate it using old
1895 // value of 'x'.
1896 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1897 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
1898 NewVVal = CGF.EmitAnyExpr(UE);
1899 }
1900 }
1901 } else {
1902 // 'x' is simply rewritten with some 'expr'.
1903 NewVValType = X->getType().getNonReferenceType();
1904 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
1905 X->getType().getNonReferenceType());
1906 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
1907 NewVVal = XRValue;
1908 return ExprRValue;
1909 };
1910 // Try to perform atomicrmw xchg, otherwise simple exchange.
1911 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1912 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
1913 Loc, Gen);
1914 if (Res.first) {
1915 // 'atomicrmw' instruction was generated.
1916 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
1917 }
1918 }
1919 // Emit post-update store to 'v' of old/new 'x' value.
1920 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001921 // OpenMP, 2.12.6, atomic Construct
1922 // Any atomic construct with a seq_cst clause forces the atomically
1923 // performed operation to include an implicit flush operation without a
1924 // list.
1925 if (IsSeqCst)
1926 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1927}
1928
Alexey Bataevb57056f2015-01-22 06:17:56 +00001929static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00001930 bool IsSeqCst, bool IsPostfixUpdate,
1931 const Expr *X, const Expr *V, const Expr *E,
1932 const Expr *UE, bool IsXLHSInRHSPart,
1933 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001934 switch (Kind) {
1935 case OMPC_read:
1936 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
1937 break;
1938 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00001939 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
1940 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001941 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001942 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00001943 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
1944 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001945 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001946 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
1947 IsXLHSInRHSPart, Loc);
1948 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001949 case OMPC_if:
1950 case OMPC_final:
1951 case OMPC_num_threads:
1952 case OMPC_private:
1953 case OMPC_firstprivate:
1954 case OMPC_lastprivate:
1955 case OMPC_reduction:
1956 case OMPC_safelen:
1957 case OMPC_collapse:
1958 case OMPC_default:
1959 case OMPC_seq_cst:
1960 case OMPC_shared:
1961 case OMPC_linear:
1962 case OMPC_aligned:
1963 case OMPC_copyin:
1964 case OMPC_copyprivate:
1965 case OMPC_flush:
1966 case OMPC_proc_bind:
1967 case OMPC_schedule:
1968 case OMPC_ordered:
1969 case OMPC_nowait:
1970 case OMPC_untied:
1971 case OMPC_threadprivate:
1972 case OMPC_mergeable:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001973 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
1974 }
1975}
1976
1977void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
1978 bool IsSeqCst = S.getSingleClause(/*K=*/OMPC_seq_cst);
1979 OpenMPClauseKind Kind = OMPC_unknown;
1980 for (auto *C : S.clauses()) {
1981 // Find first clause (skip seq_cst clause, if it is first).
1982 if (C->getClauseKind() != OMPC_seq_cst) {
1983 Kind = C->getClauseKind();
1984 break;
1985 }
1986 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001987
1988 const auto *CS =
1989 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001990 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00001991 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001992 }
1993 // Processing for statements under 'atomic capture'.
1994 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
1995 for (const auto *C : Compound->body()) {
1996 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
1997 enterFullExpression(EWC);
1998 }
1999 }
2000 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002001
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002002 LexicalScope Scope(*this, S.getSourceRange());
2003 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002004 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2005 S.getV(), S.getExpr(), S.getUpdateExpr(),
2006 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002007 };
2008 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00002009}
2010
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002011void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) {
2012 llvm_unreachable("CodeGen for 'omp target' is not supported yet.");
2013}
2014
Alexey Bataev13314bf2014-10-09 04:18:56 +00002015void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
2016 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
2017}