blob: b5e7db5350862df37d054128bd96062e687ee9d2 [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;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000118 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000119 auto IRef = C->varlist_begin();
120 auto InitsRef = C->inits().begin();
121 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000122 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000123 if (EmittedAsFirstprivate.count(OrigVD) == 0) {
124 EmittedAsFirstprivate.insert(OrigVD);
125 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
126 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
127 bool IsRegistered;
128 DeclRefExpr DRE(
129 const_cast<VarDecl *>(OrigVD),
130 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
131 OrigVD) != nullptr,
132 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
133 auto *OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000134 QualType Type = OrigVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000135 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000136 // Emit VarDecl with copy init for arrays.
137 // Get the address of the original variable captured in current
138 // captured region.
139 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
140 auto Emission = EmitAutoVarAlloca(*VD);
141 auto *Init = VD->getInit();
142 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
143 // Perform simple memcpy.
144 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000145 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000146 } else {
147 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000148 Emission.getAllocatedAddress(), OriginalAddr, Type,
Alexey Bataev69c62a92015-04-15 04:52:20 +0000149 [this, VDInit, Init](llvm::Value *DestElement,
150 llvm::Value *SrcElement) {
151 // Clean up any temporaries needed by the initialization.
152 RunCleanupsScope InitScope(*this);
153 // Emit initialization for single element.
154 LocalDeclMap[VDInit] = SrcElement;
155 EmitAnyExprToMem(Init, DestElement,
156 Init->getType().getQualifiers(),
157 /*IsInitializer*/ false);
158 LocalDeclMap.erase(VDInit);
159 });
160 }
161 EmitAutoVarCleanups(Emission);
162 return Emission.getAllocatedAddress();
163 });
164 } else {
165 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
166 // Emit private VarDecl with copy init.
167 // Remap temp VDInit variable to the address of the original
168 // variable
169 // (for proper handling of captured global variables).
170 LocalDeclMap[VDInit] = OriginalAddr;
171 EmitDecl(*VD);
172 LocalDeclMap.erase(VDInit);
173 return GetAddrOfLocalVar(VD);
174 });
175 }
176 assert(IsRegistered &&
177 "firstprivate var already registered as private");
178 // Silence the warning about unused variable.
179 (void)IsRegistered;
180 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000181 ++IRef, ++InitsRef;
182 }
183 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000184 return !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000185}
186
Alexey Bataev03b340a2014-10-21 03:16:40 +0000187void CodeGenFunction::EmitOMPPrivateClause(
188 const OMPExecutableDirective &D,
189 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev50a64582015-04-22 12:24:45 +0000190 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000191 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000192 auto IRef = C->varlist_begin();
193 for (auto IInit : C->private_copies()) {
194 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000195 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
196 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
197 bool IsRegistered =
198 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
199 // Emit private VarDecl with copy init.
200 EmitDecl(*VD);
201 return GetAddrOfLocalVar(VD);
202 });
203 assert(IsRegistered && "private var already registered as private");
204 // Silence the warning about unused variable.
205 (void)IsRegistered;
206 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000207 ++IRef;
208 }
209 }
210}
211
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000212bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
213 // threadprivate_var1 = master_threadprivate_var1;
214 // operator=(threadprivate_var2, master_threadprivate_var2);
215 // ...
216 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000217 llvm::DenseSet<const VarDecl *> CopiedVars;
218 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000219 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000220 auto IRef = C->varlist_begin();
221 auto ISrcRef = C->source_exprs().begin();
222 auto IDestRef = C->destination_exprs().begin();
223 for (auto *AssignOp : C->assignment_ops()) {
224 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000225 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000226 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000227
228 // Get the address of the master variable. If we are emitting code with
229 // TLS support, the address is passed from the master as field in the
230 // captured declaration.
231 llvm::Value *MasterAddr;
232 if (getLangOpts().OpenMPUseTLS &&
233 getContext().getTargetInfo().isTLSSupported()) {
234 assert(CapturedStmtInfo->lookup(VD) &&
235 "Copyin threadprivates should have been captured!");
236 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
237 VK_LValue, (*IRef)->getExprLoc());
238 MasterAddr = EmitLValue(&DRE).getAddress();
239 } else {
240 MasterAddr = VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
241 : CGM.GetAddrOfGlobal(VD);
242 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000243 // Get the address of the threadprivate variable.
244 auto *PrivateAddr = EmitLValue(*IRef).getAddress();
245 if (CopiedVars.size() == 1) {
246 // At first check if current thread is a master thread. If it is, no
247 // need to copy data.
248 CopyBegin = createBasicBlock("copyin.not.master");
249 CopyEnd = createBasicBlock("copyin.not.master.end");
250 Builder.CreateCondBr(
251 Builder.CreateICmpNE(
252 Builder.CreatePtrToInt(MasterAddr, CGM.IntPtrTy),
253 Builder.CreatePtrToInt(PrivateAddr, CGM.IntPtrTy)),
254 CopyBegin, CopyEnd);
255 EmitBlock(CopyBegin);
256 }
257 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
258 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000259 EmitOMPCopy(*this, Type, PrivateAddr, MasterAddr, DestVD, SrcVD,
260 AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000261 }
262 ++IRef;
263 ++ISrcRef;
264 ++IDestRef;
265 }
266 }
267 if (CopyEnd) {
268 // Exit out of copying procedure for non-master thread.
269 EmitBlock(CopyEnd, /*IsFinished=*/true);
270 return true;
271 }
272 return false;
273}
274
Alexey Bataev38e89532015-04-16 04:54:05 +0000275bool CodeGenFunction::EmitOMPLastprivateClauseInit(
276 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000277 bool HasAtLeastOneLastprivate = false;
278 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000279 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000280 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000281 auto IRef = C->varlist_begin();
282 auto IDestRef = C->destination_exprs().begin();
283 for (auto *IInit : C->private_copies()) {
284 // Keep the address of the original variable for future update at the end
285 // of the loop.
286 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
287 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
288 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
289 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> llvm::Value *{
290 DeclRefExpr DRE(
291 const_cast<VarDecl *>(OrigVD),
292 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
293 OrigVD) != nullptr,
294 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
295 return EmitLValue(&DRE).getAddress();
296 });
297 // Check if the variable is also a firstprivate: in this case IInit is
298 // not generated. Initialization of this variable will happen in codegen
299 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000300 if (IInit) {
301 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
302 bool IsRegistered =
303 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
304 // Emit private VarDecl with copy init.
305 EmitDecl(*VD);
306 return GetAddrOfLocalVar(VD);
307 });
308 assert(IsRegistered &&
309 "lastprivate var already registered as private");
310 (void)IsRegistered;
311 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000312 }
313 ++IRef, ++IDestRef;
314 }
315 }
316 return HasAtLeastOneLastprivate;
317}
318
319void CodeGenFunction::EmitOMPLastprivateClauseFinal(
320 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
321 // Emit following code:
322 // if (<IsLastIterCond>) {
323 // orig_var1 = private_orig_var1;
324 // ...
325 // orig_varn = private_orig_varn;
326 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000327 llvm::BasicBlock *ThenBB = nullptr;
328 llvm::BasicBlock *DoneBB = nullptr;
329 if (IsLastIterCond) {
330 ThenBB = createBasicBlock(".omp.lastprivate.then");
331 DoneBB = createBasicBlock(".omp.lastprivate.done");
332 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
333 EmitBlock(ThenBB);
334 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000335 llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
336 const Expr *LastIterVal = nullptr;
337 const Expr *IVExpr = nullptr;
338 const Expr *IncExpr = nullptr;
339 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000340 if (isOpenMPWorksharingDirective(D.getDirectiveKind())) {
341 LastIterVal = cast<VarDecl>(cast<DeclRefExpr>(
342 LoopDirective->getUpperBoundVariable())
343 ->getDecl())
344 ->getAnyInitializer();
345 IVExpr = LoopDirective->getIterationVariable();
346 IncExpr = LoopDirective->getInc();
347 auto IUpdate = LoopDirective->updates().begin();
348 for (auto *E : LoopDirective->counters()) {
349 auto *D = cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
350 LoopCountersAndUpdates[D] = *IUpdate;
351 ++IUpdate;
352 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000353 }
354 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000355 {
Alexey Bataev38e89532015-04-16 04:54:05 +0000356 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000357 bool FirstLCV = true;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000358 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000359 auto IRef = C->varlist_begin();
360 auto ISrcRef = C->source_exprs().begin();
361 auto IDestRef = C->destination_exprs().begin();
362 for (auto *AssignOp : C->assignment_ops()) {
363 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000364 QualType Type = PrivateVD->getType();
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000365 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
366 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
367 // If lastprivate variable is a loop control variable for loop-based
368 // directive, update its value before copyin back to original
369 // variable.
370 if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD)) {
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000371 if (FirstLCV && LastIterVal) {
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000372 EmitAnyExprToMem(LastIterVal, EmitLValue(IVExpr).getAddress(),
373 IVExpr->getType().getQualifiers(),
374 /*IsInitializer=*/false);
375 EmitIgnoredExpr(IncExpr);
376 FirstLCV = false;
377 }
378 EmitIgnoredExpr(UpExpr);
379 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000380 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
381 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
382 // Get the address of the original variable.
383 auto *OriginalAddr = GetAddrOfLocalVar(DestVD);
384 // Get the address of the private variable.
385 auto *PrivateAddr = GetAddrOfLocalVar(PrivateVD);
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000386 EmitOMPCopy(*this, Type, OriginalAddr, PrivateAddr, DestVD, SrcVD,
387 AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000388 }
389 ++IRef;
390 ++ISrcRef;
391 ++IDestRef;
392 }
393 }
394 }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000395 if (IsLastIterCond) {
396 EmitBlock(DoneBB, /*IsFinished=*/true);
397 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000398}
399
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000400void CodeGenFunction::EmitOMPReductionClauseInit(
401 const OMPExecutableDirective &D,
402 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000403 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000404 auto ILHS = C->lhs_exprs().begin();
405 auto IRHS = C->rhs_exprs().begin();
406 for (auto IRef : C->varlists()) {
407 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
408 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
409 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
410 // Store the address of the original variable associated with the LHS
411 // implicit variable.
412 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> llvm::Value *{
413 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
414 CapturedStmtInfo->lookup(OrigVD) != nullptr,
415 IRef->getType(), VK_LValue, IRef->getExprLoc());
416 return EmitLValue(&DRE).getAddress();
417 });
418 // Emit reduction copy.
419 bool IsRegistered =
420 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> llvm::Value *{
421 // Emit private VarDecl with reduction init.
422 EmitDecl(*PrivateVD);
423 return GetAddrOfLocalVar(PrivateVD);
424 });
425 assert(IsRegistered && "private var already registered as private");
426 // Silence the warning about unused variable.
427 (void)IsRegistered;
428 ++ILHS, ++IRHS;
429 }
430 }
431}
432
433void CodeGenFunction::EmitOMPReductionClauseFinal(
434 const OMPExecutableDirective &D) {
435 llvm::SmallVector<const Expr *, 8> LHSExprs;
436 llvm::SmallVector<const Expr *, 8> RHSExprs;
437 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000438 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000439 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000440 HasAtLeastOneReduction = true;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000441 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
442 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
443 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
444 }
445 if (HasAtLeastOneReduction) {
446 // Emit nowait reduction if nowait clause is present or directive is a
447 // parallel directive (it always has implicit barrier).
448 CGM.getOpenMPRuntime().emitReduction(
449 *this, D.getLocEnd(), LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000450 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000451 isOpenMPParallelDirective(D.getDirectiveKind()) ||
452 D.getDirectiveKind() == OMPD_simd,
453 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000454 }
455}
456
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000457static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
458 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000459 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000460 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000461 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000462 auto CapturedStruct = CGF.GenerateCapturedStmtArgument(*CS);
463 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000464 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000465 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +0000466 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +0000467 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
468 /*IgnoreResultAssign*/ true);
469 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
470 CGF, NumThreads, NumThreadsClause->getLocStart());
471 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000472 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev7f210c62015-06-18 13:40:03 +0000473 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +0000474 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
475 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
476 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000477 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +0000478 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
479 if (C->getNameModifier() == OMPD_unknown ||
480 C->getNameModifier() == OMPD_parallel) {
481 IfCond = C->getCondition();
482 break;
483 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000484 }
485 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
486 CapturedStruct, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000487}
488
489void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
490 LexicalScope Scope(*this, S.getSourceRange());
491 // Emit parallel region as a standalone region.
492 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
493 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000494 bool Copyins = CGF.EmitOMPCopyinClause(S);
495 bool Firstprivates = CGF.EmitOMPFirstprivateClause(S, PrivateScope);
496 if (Copyins || Firstprivates) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000497 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000498 // initialization of firstprivate variables or propagation master's thread
499 // values of threadprivate variables to local instances of that variables
500 // of all other implicit threads.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000501 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
502 OMPD_unknown);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000503 }
504 CGF.EmitOMPPrivateClause(S, PrivateScope);
505 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
506 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000507 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000508 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000509 // Emit implicit barrier at the end of the 'parallel' directive.
510 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
511 OMPD_unknown);
512 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000513 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +0000514}
Alexander Musman515ad8c2014-05-22 08:54:05 +0000515
Alexey Bataev0f34da12015-07-02 04:17:07 +0000516void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
517 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +0000518 RunCleanupsScope BodyScope(*this);
519 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000520 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +0000521 EmitIgnoredExpr(I);
522 }
Alexander Musman3276a272015-03-21 10:12:56 +0000523 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000524 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexander Musman3276a272015-03-21 10:12:56 +0000525 for (auto U : C->updates()) {
526 EmitIgnoredExpr(U);
527 }
528 }
529
Alexander Musmana5f070a2014-10-01 06:03:56 +0000530 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +0000531 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +0000532 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000533 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000534 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000535 // The end (updates/cleanups).
536 EmitBlock(Continue.getBlock());
537 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +0000538 // TODO: Update lastprivates if the SeparateIter flag is true.
539 // This will be implemented in a follow-up OMPLastprivateClause patch, but
540 // result should be still correct without it, as we do not make these
541 // variables private yet.
Alexander Musmana5f070a2014-10-01 06:03:56 +0000542}
543
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000544void CodeGenFunction::EmitOMPInnerLoop(
545 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
546 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000547 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
548 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +0000549 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000550
551 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +0000552 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000553 EmitBlock(CondBlock);
554 LoopStack.push(CondBlock);
555
556 // If there are any cleanups between here and the loop-exit scope,
557 // create a block to stage a loop exit along.
558 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +0000559 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +0000560 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000561
Alexander Musmand196ef22014-10-07 08:57:09 +0000562 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000563
Alexey Bataev2df54a02015-03-12 08:53:29 +0000564 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +0000565 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000566 if (ExitBlock != LoopExit.getBlock()) {
567 EmitBlock(ExitBlock);
568 EmitBranchThroughCleanup(LoopExit);
569 }
570
571 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +0000572 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000573
574 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +0000575 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000576 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
577
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000578 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000579
580 // Emit "IV = IV + 1" and a back-edge to the condition block.
581 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +0000582 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000583 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000584 BreakContinueStack.pop_back();
585 EmitBranch(CondBlock);
586 LoopStack.pop();
587 // Emit the fall-through block.
588 EmitBlock(LoopExit.getBlock());
589}
590
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000591void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000592 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000593 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000594 for (auto Init : C->inits()) {
595 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000596 auto *OrigVD = cast<VarDecl>(
597 cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())->getDecl());
598 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
599 CapturedStmtInfo->lookup(OrigVD) != nullptr,
600 VD->getInit()->getType(), VK_LValue,
601 VD->getInit()->getExprLoc());
602 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
603 EmitExprAsInit(&DRE, VD,
604 MakeAddrLValue(Emission.getAllocatedAddress(),
605 VD->getType(), Emission.Alignment),
606 /*capturedByInit=*/false);
607 EmitAutoVarCleanups(Emission);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000608 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000609 // Emit the linear steps for the linear clauses.
610 // If a step is not constant, it is pre-calculated before the loop.
611 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
612 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000613 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000614 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000615 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000616 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000617 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000618}
619
620static void emitLinearClauseFinal(CodeGenFunction &CGF,
621 const OMPLoopDirective &D) {
Alexander Musman3276a272015-03-21 10:12:56 +0000622 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000623 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000624 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +0000625 for (auto F : C->finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000626 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
627 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000628 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +0000629 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000630 auto *OrigAddr = CGF.EmitLValue(&DRE).getAddress();
631 CodeGenFunction::OMPPrivateScope VarScope(CGF);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000632 VarScope.addPrivate(OrigVD,
633 [OrigAddr]() -> llvm::Value *{ return OrigAddr; });
634 (void)VarScope.Privatize();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000635 CGF.EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000636 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +0000637 }
638 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000639}
640
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000641static void emitAlignedClause(CodeGenFunction &CGF,
642 const OMPExecutableDirective &D) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000643 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000644 unsigned ClauseAlignment = 0;
645 if (auto AlignmentExpr = Clause->getAlignment()) {
646 auto AlignmentCI =
647 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
648 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +0000649 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000650 for (auto E : Clause->varlists()) {
651 unsigned Alignment = ClauseAlignment;
652 if (Alignment == 0) {
653 // OpenMP [2.8.1, Description]
654 // If no optional parameter is specified, implementation-defined default
655 // alignments for SIMD instructions on the target platforms are assumed.
656 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +0000657 CGF.getContext()
658 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
659 E->getType()->getPointeeType()))
660 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000661 }
662 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
663 "alignment is not power of 2");
664 if (Alignment != 0) {
665 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
666 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
667 }
Alexander Musman09184fe2014-09-30 05:29:28 +0000668 }
669 }
670}
671
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000672static void emitPrivateLoopCounters(CodeGenFunction &CGF,
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000673 CodeGenFunction::OMPPrivateScope &LoopScope,
Alexey Bataeva8899172015-08-06 12:30:57 +0000674 ArrayRef<Expr *> Counters,
675 ArrayRef<Expr *> PrivateCounters) {
676 auto I = PrivateCounters.begin();
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000677 for (auto *E : Counters) {
Alexey Bataeva8899172015-08-06 12:30:57 +0000678 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
679 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
680 llvm::Value *Addr;
681 (void)LoopScope.addPrivate(PrivateVD, [&]() -> llvm::Value * {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000682 // Emit var without initialization.
Alexey Bataeva8899172015-08-06 12:30:57 +0000683 auto VarEmission = CGF.EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000684 CGF.EmitAutoVarCleanups(VarEmission);
Alexey Bataeva8899172015-08-06 12:30:57 +0000685 Addr = VarEmission.getAllocatedAddress();
686 return Addr;
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000687 });
Alexey Bataeva8899172015-08-06 12:30:57 +0000688 (void)LoopScope.addPrivate(VD, [&]() -> llvm::Value * { return Addr; });
689 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000690 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000691}
692
Alexey Bataev62dbb972015-04-22 11:59:37 +0000693static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
694 const Expr *Cond, llvm::BasicBlock *TrueBlock,
695 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +0000696 {
697 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +0000698 emitPrivateLoopCounters(CGF, PreCondScope, S.counters(),
699 S.private_counters());
Alexey Bataev6e8248f2015-06-11 10:53:56 +0000700 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +0000701 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +0000702 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +0000703 CGF.EmitIgnoredExpr(I);
704 }
Alexey Bataev62dbb972015-04-22 11:59:37 +0000705 }
706 // Check that loop is executed at least one time.
707 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
708}
709
Alexander Musman3276a272015-03-21 10:12:56 +0000710static void
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000711emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexander Musman3276a272015-03-21 10:12:56 +0000712 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000713 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +0000714 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +0000715 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +0000716 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
717 auto *PrivateVD =
718 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
719 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> llvm::Value * {
720 // Emit private VarDecl with copy init.
721 CGF.EmitVarDecl(*PrivateVD);
722 return CGF.GetAddrOfLocalVar(PrivateVD);
Alexander Musman3276a272015-03-21 10:12:56 +0000723 });
724 assert(IsRegistered && "linear var already registered as private");
725 // Silence the warning about unused variable.
726 (void)IsRegistered;
Alexey Bataevbd9fec12015-08-18 06:47:21 +0000727 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +0000728 }
729 }
730}
731
Alexey Bataev45bfad52015-08-21 12:19:04 +0000732static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
733 const OMPExecutableDirective &D) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000734 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +0000735 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
736 /*ignoreResult=*/true);
737 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
738 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
739 // In presence of finite 'safelen', it may be unsafe to mark all
740 // the memory instructions parallel, because loop-carried
741 // dependences of 'safelen' iterations are possible.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000742 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
743 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000744 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
745 /*ignoreResult=*/true);
746 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +0000747 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000748 // In presence of finite 'safelen', it may be unsafe to mark all
749 // the memory instructions parallel, because loop-carried
750 // dependences of 'safelen' iterations are possible.
751 CGF.LoopStack.setParallel(false);
752 }
753}
754
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000755void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D) {
756 // Walk clauses and process safelen/lastprivate.
757 LoopStack.setParallel();
Tyler Nowickida46d0e2015-07-14 23:03:09 +0000758 LoopStack.setVectorizeEnable(true);
Alexey Bataev45bfad52015-08-21 12:19:04 +0000759 emitSimdlenSafelenClause(*this, D);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000760}
761
762void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &D) {
763 auto IC = D.counters().begin();
764 for (auto F : D.finals()) {
765 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000766 if (LocalDeclMap.lookup(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000767 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
768 CapturedStmtInfo->lookup(OrigVD) != nullptr,
769 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
770 auto *OrigAddr = EmitLValue(&DRE).getAddress();
771 OMPPrivateScope VarScope(*this);
772 VarScope.addPrivate(OrigVD,
773 [OrigAddr]() -> llvm::Value *{ return OrigAddr; });
774 (void)VarScope.Privatize();
775 EmitIgnoredExpr(F);
776 }
777 ++IC;
778 }
779 emitLinearClauseFinal(*this, D);
780}
781
Alexander Musman515ad8c2014-05-22 08:54:05 +0000782void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000783 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000784 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000785 // for (IV in 0..LastIteration) BODY;
786 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000787 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000788 //
Alexander Musmana5f070a2014-10-01 06:03:56 +0000789
Alexey Bataev62dbb972015-04-22 11:59:37 +0000790 // Emit: if (PreCond) - begin.
791 // If the condition constant folds and can be elided, avoid emitting the
792 // whole loop.
793 bool CondConstant;
794 llvm::BasicBlock *ContBlock = nullptr;
795 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
796 if (!CondConstant)
797 return;
798 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000799 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
800 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +0000801 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
802 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +0000803 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +0000804 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000805 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000806
807 // Emit the loop iteration variable.
808 const Expr *IVExpr = S.getIterationVariable();
809 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
810 CGF.EmitVarDecl(*IVDecl);
811 CGF.EmitIgnoredExpr(S.getInit());
812
813 // Emit the iterations count variable.
814 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000815 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000816 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
817 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
818 // Emit calculation of the iterations count.
819 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000820 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000821
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000822 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000823
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000824 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000825 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000826 bool HasLastprivateClause;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000827 {
828 OMPPrivateScope LoopScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +0000829 emitPrivateLoopCounters(CGF, LoopScope, S.counters(),
830 S.private_counters());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000831 emitPrivateLinearVars(CGF, S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000832 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000833 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000834 HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000835 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +0000836 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
837 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +0000838 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +0000839 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +0000840 CGF.EmitStopPoint(&S);
841 },
842 [](CodeGenFunction &) {});
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000843 // Emit final copy of the lastprivate variables at the end of loops.
844 if (HasLastprivateClause) {
845 CGF.EmitOMPLastprivateClauseFinal(S);
846 }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000847 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000848 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000849 CGF.EmitOMPSimdFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000850 // Emit: if (PreCond) - end.
851 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000852 CGF.EmitBranch(ContBlock);
853 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000854 }
855 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000856 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +0000857}
858
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000859void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
860 const OMPLoopDirective &S,
861 OMPPrivateScope &LoopScope,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000862 bool Ordered, llvm::Value *LB,
863 llvm::Value *UB, llvm::Value *ST,
864 llvm::Value *IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000865 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000866
867 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000868 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
Alexander Musman92bdaab2015-03-12 13:37:50 +0000869
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000870 assert((Ordered ||
871 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000872 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000873
874 // Emit outer loop.
875 //
876 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +0000877 // When schedule(dynamic,chunk_size) is specified, the iterations are
878 // distributed to threads in the team in chunks as the threads request them.
879 // Each thread executes a chunk of iterations, then requests another chunk,
880 // until no chunks remain to be distributed. Each chunk contains chunk_size
881 // iterations, except for the last chunk to be distributed, which may have
882 // fewer iterations. When no chunk_size is specified, it defaults to 1.
883 //
884 // When schedule(guided,chunk_size) is specified, the iterations are assigned
885 // to threads in the team in chunks as the executing threads request them.
886 // Each thread executes a chunk of iterations, then requests another chunk,
887 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
888 // each chunk is proportional to the number of unassigned iterations divided
889 // by the number of threads in the team, decreasing to 1. For a chunk_size
890 // with value k (greater than 1), the size of each chunk is determined in the
891 // same way, with the restriction that the chunks do not contain fewer than k
892 // iterations (except for the last chunk to be assigned, which may have fewer
893 // than k iterations).
894 //
895 // When schedule(auto) is specified, the decision regarding scheduling is
896 // delegated to the compiler and/or runtime system. The programmer gives the
897 // implementation the freedom to choose any possible mapping of iterations to
898 // threads in the team.
899 //
900 // When schedule(runtime) is specified, the decision regarding scheduling is
901 // deferred until run time, and the schedule and chunk size are taken from the
902 // run-sched-var ICV. If the ICV is set to auto, the schedule is
903 // implementation defined
904 //
905 // while(__kmpc_dispatch_next(&LB, &UB)) {
906 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000907 // while (idx <= UB) { BODY; ++idx;
908 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
909 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +0000910 // }
911 //
912 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000913 // When schedule(static, chunk_size) is specified, iterations are divided into
914 // chunks of size chunk_size, and the chunks are assigned to the threads in
915 // the team in a round-robin fashion in the order of the thread number.
916 //
917 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
918 // while (idx <= UB) { BODY; ++idx; } // inner loop
919 // LB = LB + ST;
920 // UB = UB + ST;
921 // }
922 //
Alexander Musman92bdaab2015-03-12 13:37:50 +0000923
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000924 const Expr *IVExpr = S.getIterationVariable();
925 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
926 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
927
Alexander Musman92bdaab2015-03-12 13:37:50 +0000928 RT.emitForInit(
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000929 *this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, Ordered, IL, LB,
930 (DynamicOrOrdered ? EmitAnyExpr(S.getLastIteration()).getScalarVal()
931 : UB),
932 ST, Chunk);
Alexander Musman92bdaab2015-03-12 13:37:50 +0000933
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000934 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
935
936 // Start the loop with a block that tests the condition.
937 auto CondBlock = createBasicBlock("omp.dispatch.cond");
938 EmitBlock(CondBlock);
939 LoopStack.push(CondBlock);
940
941 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000942 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +0000943 // UB = min(UB, GlobalUB)
944 EmitIgnoredExpr(S.getEnsureUpperBound());
945 // IV = LB
946 EmitIgnoredExpr(S.getInit());
947 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +0000948 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +0000949 } else {
950 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
951 IL, LB, UB, ST);
952 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000953
954 // If there are any cleanups between here and the loop-exit scope,
955 // create a block to stage a loop exit along.
956 auto ExitBlock = LoopExit.getBlock();
957 if (LoopScope.requiresCleanups())
958 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
959
960 auto LoopBody = createBasicBlock("omp.dispatch.body");
961 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
962 if (ExitBlock != LoopExit.getBlock()) {
963 EmitBlock(ExitBlock);
964 EmitBranchThroughCleanup(LoopExit);
965 }
966 EmitBlock(LoopBody);
967
Alexander Musman92bdaab2015-03-12 13:37:50 +0000968 // Emit "IV = LB" (in case of static schedule, we have already calculated new
969 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000970 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +0000971 EmitIgnoredExpr(S.getInit());
972
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000973 // Create a block for the increment.
974 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
975 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
976
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000977 // Generate !llvm.loop.parallel metadata for loads and stores for loops
978 // with dynamic/guided scheduling and without ordered clause.
979 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
980 LoopStack.setParallel((ScheduleKind == OMPC_SCHEDULE_dynamic ||
981 ScheduleKind == OMPC_SCHEDULE_guided) &&
982 !Ordered);
983 } else {
984 EmitOMPSimdInit(S);
985 }
986
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000987 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +0000988 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
989 [&S, LoopExit](CodeGenFunction &CGF) {
990 CGF.EmitOMPLoopBody(S, LoopExit);
991 CGF.EmitStopPoint(&S);
992 },
993 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
994 if (Ordered) {
995 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
996 CGF, Loc, IVSize, IVSigned);
997 }
998 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000999
1000 EmitBlock(Continue.getBlock());
1001 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001002 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001003 // Emit "LB = LB + Stride", "UB = UB + Stride".
1004 EmitIgnoredExpr(S.getNextLowerBound());
1005 EmitIgnoredExpr(S.getNextUpperBound());
1006 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001007
1008 EmitBranch(CondBlock);
1009 LoopStack.pop();
1010 // Emit the fall-through block.
1011 EmitBlock(LoopExit.getBlock());
1012
1013 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001014 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001015 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001016}
1017
Alexander Musmanc6388682014-12-15 07:07:06 +00001018/// \brief Emit a helper variable and return corresponding lvalue.
1019static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1020 const DeclRefExpr *Helper) {
1021 auto VDecl = cast<VarDecl>(Helper->getDecl());
1022 CGF.EmitVarDecl(*VDecl);
1023 return CGF.EmitLValue(Helper);
1024}
1025
Alexey Bataev040d5402015-05-12 08:35:28 +00001026static std::pair<llvm::Value * /*Chunk*/, OpenMPScheduleClauseKind>
1027emitScheduleClause(CodeGenFunction &CGF, const OMPLoopDirective &S,
1028 bool OuterRegion) {
1029 // Detect the loop schedule kind and chunk.
1030 auto ScheduleKind = OMPC_SCHEDULE_unknown;
1031 llvm::Value *Chunk = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001032 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001033 ScheduleKind = C->getScheduleKind();
1034 if (const auto *Ch = C->getChunkSize()) {
1035 if (auto *ImpRef = cast_or_null<DeclRefExpr>(C->getHelperChunkSize())) {
1036 if (OuterRegion) {
1037 const VarDecl *ImpVar = cast<VarDecl>(ImpRef->getDecl());
1038 CGF.EmitVarDecl(*ImpVar);
1039 CGF.EmitStoreThroughLValue(
1040 CGF.EmitAnyExpr(Ch),
1041 CGF.MakeNaturalAlignAddrLValue(CGF.GetAddrOfLocalVar(ImpVar),
1042 ImpVar->getType()));
1043 } else {
1044 Ch = ImpRef;
1045 }
1046 }
1047 if (!C->getHelperChunkSize() || !OuterRegion) {
1048 Chunk = CGF.EmitScalarExpr(Ch);
1049 Chunk = CGF.EmitScalarConversion(Chunk, Ch->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001050 S.getIterationVariable()->getType(),
1051 S.getLocStart());
Alexey Bataev040d5402015-05-12 08:35:28 +00001052 }
1053 }
1054 }
1055 return std::make_pair(Chunk, ScheduleKind);
1056}
1057
Alexey Bataev38e89532015-04-16 04:54:05 +00001058bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001059 // Emit the loop iteration variable.
1060 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1061 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1062 EmitVarDecl(*IVDecl);
1063
1064 // Emit the iterations count variable.
1065 // If it is not a variable, Sema decided to calculate iterations count on each
1066 // iteration (e.g., it is foldable into a constant).
1067 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1068 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1069 // Emit calculation of the iterations count.
1070 EmitIgnoredExpr(S.getCalcLastIteration());
1071 }
1072
1073 auto &RT = CGM.getOpenMPRuntime();
1074
Alexey Bataev38e89532015-04-16 04:54:05 +00001075 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001076 // Check pre-condition.
1077 {
1078 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001079 // If the condition constant folds and can be elided, avoid emitting the
1080 // whole loop.
1081 bool CondConstant;
1082 llvm::BasicBlock *ContBlock = nullptr;
1083 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1084 if (!CondConstant)
1085 return false;
1086 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001087 auto *ThenBlock = createBasicBlock("omp.precond.then");
1088 ContBlock = createBasicBlock("omp.precond.end");
1089 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001090 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001091 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001092 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001093 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001094
1095 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001096 EmitOMPLinearClauseInit(S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001097 // Emit 'then' code.
1098 {
1099 // Emit helper vars inits.
1100 LValue LB =
1101 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1102 LValue UB =
1103 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1104 LValue ST =
1105 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1106 LValue IL =
1107 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1108
1109 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001110 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1111 // Emit implicit barrier to synchronize threads and avoid data races on
1112 // initialization of firstprivate variables.
1113 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1114 OMPD_unknown);
1115 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001116 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001117 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001118 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataeva8899172015-08-06 12:30:57 +00001119 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
1120 S.private_counters());
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001121 emitPrivateLinearVars(*this, S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001122 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001123
1124 // Detect the loop schedule kind and chunk.
Alexey Bataev040d5402015-05-12 08:35:28 +00001125 llvm::Value *Chunk;
1126 OpenMPScheduleClauseKind ScheduleKind;
1127 auto ScheduleInfo =
1128 emitScheduleClause(*this, S, /*OuterRegion=*/false);
1129 Chunk = ScheduleInfo.first;
1130 ScheduleKind = ScheduleInfo.second;
Alexander Musmanc6388682014-12-15 07:07:06 +00001131 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1132 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001133 const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
Alexander Musmanc6388682014-12-15 07:07:06 +00001134 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001135 /* Chunked */ Chunk != nullptr) &&
1136 !Ordered) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001137 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1138 EmitOMPSimdInit(S);
1139 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001140 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1141 // When no chunk_size is specified, the iteration space is divided into
1142 // chunks that are approximately equal in size, and at most one chunk is
1143 // distributed to each thread. Note that the size of the chunks is
1144 // unspecified in this case.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001145 RT.emitForInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001146 Ordered, IL.getAddress(), LB.getAddress(),
1147 UB.getAddress(), ST.getAddress());
Alexey Bataev0f34da12015-07-02 04:17:07 +00001148 auto LoopExit = getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00001149 // UB = min(UB, GlobalUB);
1150 EmitIgnoredExpr(S.getEnsureUpperBound());
1151 // IV = LB;
1152 EmitIgnoredExpr(S.getInit());
1153 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001154 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1155 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00001156 [&S, LoopExit](CodeGenFunction &CGF) {
1157 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001158 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001159 },
1160 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00001161 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00001162 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001163 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001164 } else {
1165 // Emit the outer loop, which requests its work chunk [LB..UB] from
1166 // runtime and runs the inner loop to process it.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001167 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, Ordered,
1168 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1169 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001170 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001171 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001172 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1173 if (HasLastprivateClause)
1174 EmitOMPLastprivateClauseFinal(
1175 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001176 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001177 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1178 EmitOMPSimdFinal(S);
1179 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001180 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001181 if (ContBlock) {
1182 EmitBranch(ContBlock);
1183 EmitBlock(ContBlock, true);
1184 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001185 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001186 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001187}
1188
1189void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001190 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev38e89532015-04-16 04:54:05 +00001191 bool HasLastprivates = false;
1192 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1193 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1194 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001195 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen);
Alexander Musmanc6388682014-12-15 07:07:06 +00001196
1197 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001198 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001199 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1200 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001201}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001202
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001203void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
1204 LexicalScope Scope(*this, S.getSourceRange());
1205 bool HasLastprivates = false;
1206 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1207 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1208 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001209 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001210
1211 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001212 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001213 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1214 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001215}
1216
Alexey Bataev2df54a02015-03-12 08:53:29 +00001217static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1218 const Twine &Name,
1219 llvm::Value *Init = nullptr) {
1220 auto LVal = CGF.MakeNaturalAlignAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
1221 if (Init)
1222 CGF.EmitScalarInit(Init, LVal);
1223 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001224}
1225
Alexey Bataev0f34da12015-07-02 04:17:07 +00001226OpenMPDirectiveKind
1227CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001228 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1229 auto *CS = dyn_cast<CompoundStmt>(Stmt);
1230 if (CS && CS->size() > 1) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001231 bool HasLastprivates = false;
1232 auto &&CodeGen = [&S, CS, &HasLastprivates](CodeGenFunction &CGF) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001233 auto &C = CGF.CGM.getContext();
1234 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1235 // Emit helper vars inits.
1236 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1237 CGF.Builder.getInt32(0));
1238 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
1239 LValue UB =
1240 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1241 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1242 CGF.Builder.getInt32(1));
1243 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1244 CGF.Builder.getInt32(0));
1245 // Loop counter.
1246 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1247 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001248 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001249 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001250 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001251 // Generate condition for loop.
1252 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1253 OK_Ordinary, S.getLocStart(),
1254 /*fpContractable=*/false);
1255 // Increment for loop counter.
1256 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
1257 OK_Ordinary, S.getLocStart());
1258 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
1259 // Iterate through all sections and emit a switch construct:
1260 // switch (IV) {
1261 // case 0:
1262 // <SectionStmt[0]>;
1263 // break;
1264 // ...
1265 // case <NumSection> - 1:
1266 // <SectionStmt[<NumSection> - 1]>;
1267 // break;
1268 // }
1269 // .omp.sections.exit:
1270 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1271 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1272 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1273 CS->size());
1274 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00001275 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001276 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1277 CGF.EmitBlock(CaseBB);
1278 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001279 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001280 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001281 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001282 }
1283 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1284 };
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001285
1286 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1287 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
1288 // Emit implicit barrier to synchronize threads and avoid data races on
1289 // initialization of firstprivate variables.
1290 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1291 OMPD_unknown);
1292 }
Alexey Bataev73870832015-04-27 04:12:12 +00001293 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001294 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001295 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001296 (void)LoopScope.Privatize();
1297
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001298 // Emit static non-chunked loop.
1299 CGF.CGM.getOpenMPRuntime().emitForInit(
1300 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001301 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
1302 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001303 // UB = min(UB, GlobalUB);
1304 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1305 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1306 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1307 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1308 // IV = LB;
1309 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1310 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001311 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1312 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001313 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001314 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataeva89adf22015-04-27 05:04:13 +00001315 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001316
1317 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1318 if (HasLastprivates)
1319 CGF.EmitOMPLastprivateClauseFinal(
1320 S, CGF.Builder.CreateIsNotNull(
1321 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev2df54a02015-03-12 08:53:29 +00001322 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001323
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001324 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001325 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1326 // clause. Otherwise the barrier will be generated by the codegen for the
1327 // directive.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001328 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001329 // Emit implicit barrier to synchronize threads and avoid data races on
1330 // initialization of firstprivate variables.
Alexey Bataev0f34da12015-07-02 04:17:07 +00001331 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1332 OMPD_unknown);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001333 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001334 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001335 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001336 // If only one section is found - no need to generate loop, emit as a single
1337 // region.
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001338 bool HasFirstprivates;
Alexey Bataeva89adf22015-04-27 05:04:13 +00001339 // No need to generate reductions for sections with single section region, we
1340 // can use original shared variables for all operations.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001341 bool HasReductions = S.hasClausesOfKind<OMPReductionClause>();
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001342 // No need to generate lastprivates for sections with single section region,
1343 // we can use original shared variable for all calculations with barrier at
1344 // the end of the sections.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001345 bool HasLastprivates = S.hasClausesOfKind<OMPLastprivateClause>();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001346 auto &&CodeGen = [Stmt, &S, &HasFirstprivates](CodeGenFunction &CGF) {
1347 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1348 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev73870832015-04-27 04:12:12 +00001349 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001350 (void)SingleScope.Privatize();
1351
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001352 CGF.EmitStmt(Stmt);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001353 };
Alexey Bataev0f34da12015-07-02 04:17:07 +00001354 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
1355 llvm::None, llvm::None, llvm::None,
1356 llvm::None);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001357 // Emit barrier for firstprivates, lastprivates or reductions only if
1358 // 'sections' directive has 'nowait' clause. Otherwise the barrier will be
1359 // generated by the codegen for the directive.
1360 if ((HasFirstprivates || HasLastprivates || HasReductions) &&
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001361 S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001362 // Emit implicit barrier to synchronize threads and avoid data races on
1363 // initialization of firstprivate variables.
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001364 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001365 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001366 return OMPD_single;
1367}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001368
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001369void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1370 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev0f34da12015-07-02 04:17:07 +00001371 OpenMPDirectiveKind EmittedAs = EmitSections(S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001372 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001373 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001374 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001375 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001376}
1377
1378void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001379 LexicalScope Scope(*this, S.getSourceRange());
1380 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1381 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1382 CGF.EnsureInsertPoint();
1383 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001384 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001385}
1386
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001387void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001388 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001389 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001390 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001391 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001392 // Check if there are any 'copyprivate' clauses associated with this
1393 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001394 // construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001395 // Build a list of copyprivate variables along with helper expressions
1396 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001397 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001398 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001399 DestExprs.append(C->destination_exprs().begin(),
1400 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001401 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001402 AssignmentOps.append(C->assignment_ops().begin(),
1403 C->assignment_ops().end());
1404 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001405 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001406 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev5521d782015-04-24 04:21:15 +00001407 bool HasFirstprivates;
1408 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) {
1409 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1410 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev59c654a2015-04-27 03:48:52 +00001411 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev5521d782015-04-24 04:21:15 +00001412 (void)SingleScope.Privatize();
1413
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001414 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1415 CGF.EnsureInsertPoint();
1416 };
1417 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001418 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001419 AssignmentOps);
Alexey Bataev5521d782015-04-24 04:21:15 +00001420 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1421 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001422 if ((!S.getSingleClause<OMPNowaitClause>() || HasFirstprivates) &&
Alexey Bataev5521d782015-04-24 04:21:15 +00001423 CopyprivateVars.empty()) {
1424 CGM.getOpenMPRuntime().emitBarrierCall(
1425 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001426 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001427 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001428}
1429
Alexey Bataev8d690652014-12-04 07:23:53 +00001430void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001431 LexicalScope Scope(*this, S.getSourceRange());
1432 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1433 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1434 CGF.EnsureInsertPoint();
1435 };
1436 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001437}
1438
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001439void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001440 LexicalScope Scope(*this, S.getSourceRange());
1441 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1442 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1443 CGF.EnsureInsertPoint();
1444 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001445 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001446 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001447}
1448
Alexey Bataev671605e2015-04-13 05:28:11 +00001449void CodeGenFunction::EmitOMPParallelForDirective(
1450 const OMPParallelForDirective &S) {
1451 // Emit directive as a combined directive that consists of two implicit
1452 // directives: 'parallel' with 'for' directive.
1453 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev040d5402015-05-12 08:35:28 +00001454 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
Alexey Bataev671605e2015-04-13 05:28:11 +00001455 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1456 CGF.EmitOMPWorksharingLoop(S);
1457 // Emit implicit barrier at the end of parallel region, but this barrier
1458 // is at the end of 'for' directive, so emit it as the implicit barrier for
1459 // this 'for' directive.
1460 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1461 OMPD_parallel);
1462 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001463 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001464}
1465
Alexander Musmane4e893b2014-09-23 09:33:00 +00001466void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001467 const OMPParallelForSimdDirective &S) {
1468 // Emit directive as a combined directive that consists of two implicit
1469 // directives: 'parallel' with 'for' directive.
1470 LexicalScope Scope(*this, S.getSourceRange());
1471 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
1472 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1473 CGF.EmitOMPWorksharingLoop(S);
1474 // Emit implicit barrier at the end of parallel region, but this barrier
1475 // is at the end of 'for' directive, so emit it as the implicit barrier for
1476 // this 'for' directive.
1477 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1478 OMPD_parallel);
1479 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001480 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001481}
1482
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001483void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001484 const OMPParallelSectionsDirective &S) {
1485 // Emit directive as a combined directive that consists of two implicit
1486 // directives: 'parallel' with 'sections' directive.
1487 LexicalScope Scope(*this, S.getSourceRange());
1488 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001489 (void)CGF.EmitSections(S);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001490 // Emit implicit barrier at the end of parallel region.
1491 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1492 OMPD_parallel);
1493 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001494 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001495}
1496
Alexey Bataev62b63b12015-03-10 07:28:44 +00001497void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1498 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001499 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001500 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1501 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1502 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001503 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001504 // The first function argument for tasks is a thread id, the second one is a
1505 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001506 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
1507 // Get list of private variables.
1508 llvm::SmallVector<const Expr *, 8> PrivateVars;
1509 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001510 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001511 auto IRef = C->varlist_begin();
1512 for (auto *IInit : C->private_copies()) {
1513 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1514 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1515 PrivateVars.push_back(*IRef);
1516 PrivateCopies.push_back(IInit);
1517 }
1518 ++IRef;
1519 }
1520 }
1521 EmittedAsPrivate.clear();
1522 // Get list of firstprivate variables.
1523 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
1524 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
1525 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001526 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001527 auto IRef = C->varlist_begin();
1528 auto IElemInitRef = C->inits().begin();
1529 for (auto *IInit : C->private_copies()) {
1530 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1531 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1532 FirstprivateVars.push_back(*IRef);
1533 FirstprivateCopies.push_back(IInit);
1534 FirstprivateInits.push_back(*IElemInitRef);
1535 }
1536 ++IRef, ++IElemInitRef;
1537 }
1538 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001539 // Build list of dependences.
1540 llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8>
1541 Dependences;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001542 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001543 for (auto *IRef : C->varlists()) {
1544 Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
1545 }
1546 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001547 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
1548 CodeGenFunction &CGF) {
1549 // Set proper addresses for generated private copies.
1550 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
1551 OMPPrivateScope Scope(CGF);
1552 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
1553 auto *CopyFn = CGF.Builder.CreateAlignedLoad(
1554 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)),
1555 CGF.PointerAlignInBytes);
1556 auto *PrivatesPtr = CGF.Builder.CreateAlignedLoad(
1557 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)),
1558 CGF.PointerAlignInBytes);
1559 // Map privates.
1560 llvm::SmallVector<std::pair<const VarDecl *, llvm::Value *>, 16>
1561 PrivatePtrs;
1562 llvm::SmallVector<llvm::Value *, 16> CallArgs;
1563 CallArgs.push_back(PrivatesPtr);
1564 for (auto *E : PrivateVars) {
1565 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1566 auto *PrivatePtr =
1567 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
1568 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
1569 CallArgs.push_back(PrivatePtr);
1570 }
1571 for (auto *E : FirstprivateVars) {
1572 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1573 auto *PrivatePtr =
1574 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
1575 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
1576 CallArgs.push_back(PrivatePtr);
1577 }
1578 CGF.EmitRuntimeCall(CopyFn, CallArgs);
1579 for (auto &&Pair : PrivatePtrs) {
1580 auto *Replacement =
1581 CGF.Builder.CreateAlignedLoad(Pair.second, CGF.PointerAlignInBytes);
1582 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
1583 }
1584 }
1585 (void)Scope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001586 if (*PartId) {
1587 // TODO: emit code for untied tasks.
1588 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001589 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001590 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001591 auto OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
1592 S, *I, OMPD_task, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001593 // Check if we should emit tied or untied task.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001594 bool Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev62b63b12015-03-10 07:28:44 +00001595 // Check if the task is final
1596 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001597 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001598 // If the condition constant folds and can be elided, try to avoid emitting
1599 // the condition and the dead arm of the if/else.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001600 auto *Cond = Clause->getCondition();
Alexey Bataev62b63b12015-03-10 07:28:44 +00001601 bool CondConstant;
1602 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1603 Final.setInt(CondConstant);
1604 else
1605 Final.setPointer(EvaluateExprAsBool(Cond));
1606 } else {
1607 // By default the task is not final.
1608 Final.setInt(/*IntVal=*/false);
1609 }
1610 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00001611 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001612 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1613 if (C->getNameModifier() == OMPD_unknown ||
1614 C->getNameModifier() == OMPD_task) {
1615 IfCond = C->getCondition();
1616 break;
1617 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001618 }
Alexey Bataev9e034042015-05-05 04:05:12 +00001619 CGM.getOpenMPRuntime().emitTaskCall(
1620 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001621 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001622 FirstprivateCopies, FirstprivateInits, Dependences);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001623}
1624
Alexey Bataev9f797f32015-02-05 05:57:51 +00001625void CodeGenFunction::EmitOMPTaskyieldDirective(
1626 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001627 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001628}
1629
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001630void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001631 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001632}
1633
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001634void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
1635 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00001636}
1637
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001638void CodeGenFunction::EmitOMPTaskgroupDirective(
1639 const OMPTaskgroupDirective &S) {
1640 LexicalScope Scope(*this, S.getSourceRange());
1641 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1642 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1643 CGF.EnsureInsertPoint();
1644 };
1645 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
1646}
1647
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001648void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001649 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001650 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001651 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1652 FlushClause->varlist_end());
1653 }
1654 return llvm::None;
1655 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00001656}
1657
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001658void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
1659 LexicalScope Scope(*this, S.getSourceRange());
1660 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1661 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1662 CGF.EnsureInsertPoint();
1663 };
1664 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001665}
1666
Alexey Bataevb57056f2015-01-22 06:17:56 +00001667static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001668 QualType SrcType, QualType DestType,
1669 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001670 assert(CGF.hasScalarEvaluationKind(DestType) &&
1671 "DestType must have scalar evaluation kind.");
1672 assert(!Val.isAggregate() && "Must be a scalar or complex.");
1673 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001674 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
1675 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00001676 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001677 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001678}
1679
1680static CodeGenFunction::ComplexPairTy
1681convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001682 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001683 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
1684 "DestType must have complex evaluation kind.");
1685 CodeGenFunction::ComplexPairTy ComplexVal;
1686 if (Val.isScalar()) {
1687 // Convert the input element to the element type of the complex.
1688 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001689 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
1690 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001691 ComplexVal = CodeGenFunction::ComplexPairTy(
1692 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
1693 } else {
1694 assert(Val.isComplex() && "Must be a scalar or complex.");
1695 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
1696 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1697 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001698 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001699 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001700 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001701 }
1702 return ComplexVal;
1703}
1704
Alexey Bataev5e018f92015-04-23 06:35:10 +00001705static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
1706 LValue LVal, RValue RVal) {
1707 if (LVal.isGlobalReg()) {
1708 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
1709 } else {
1710 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
1711 : llvm::Monotonic,
1712 LVal.isVolatile(), /*IsInit=*/false);
1713 }
1714}
1715
1716static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001717 QualType RValTy, SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00001718 switch (CGF.getEvaluationKind(LVal.getType())) {
1719 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001720 CGF.EmitStoreThroughLValue(RValue::get(convertToScalarValue(
1721 CGF, RVal, RValTy, LVal.getType(), Loc)),
1722 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001723 break;
1724 case TEK_Complex:
1725 CGF.EmitStoreOfComplex(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001726 convertToComplexValue(CGF, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00001727 /*isInit=*/false);
1728 break;
1729 case TEK_Aggregate:
1730 llvm_unreachable("Must be a scalar or complex.");
1731 }
1732}
1733
Alexey Bataevb57056f2015-01-22 06:17:56 +00001734static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
1735 const Expr *X, const Expr *V,
1736 SourceLocation Loc) {
1737 // v = x;
1738 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
1739 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
1740 LValue XLValue = CGF.EmitLValue(X);
1741 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00001742 RValue Res = XLValue.isGlobalReg()
1743 ? CGF.EmitLoadOfLValue(XLValue, Loc)
1744 : CGF.EmitAtomicLoad(XLValue, Loc,
1745 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00001746 : llvm::Monotonic,
1747 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001748 // OpenMP, 2.12.6, atomic Construct
1749 // Any atomic construct with a seq_cst clause forces the atomically
1750 // performed operation to include an implicit flush operation without a
1751 // list.
1752 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001753 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001754 emitSimpleStore(CGF, VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001755}
1756
Alexey Bataevb8329262015-02-27 06:33:30 +00001757static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
1758 const Expr *X, const Expr *E,
1759 SourceLocation Loc) {
1760 // x = expr;
1761 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00001762 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00001763 // OpenMP, 2.12.6, atomic Construct
1764 // Any atomic construct with a seq_cst clause forces the atomically
1765 // performed operation to include an implicit flush operation without a
1766 // list.
1767 if (IsSeqCst)
1768 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1769}
1770
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00001771static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
1772 RValue Update,
1773 BinaryOperatorKind BO,
1774 llvm::AtomicOrdering AO,
1775 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001776 auto &Context = CGF.CGM.getContext();
1777 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00001778 // expression is simple and atomic is allowed for the given type for the
1779 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001780 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00001781 !Update.getScalarVal()->getType()->isIntegerTy() ||
1782 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
1783 (Update.getScalarVal()->getType() !=
1784 X.getAddress()->getType()->getPointerElementType())) ||
1785 !X.getAddress()->getType()->getPointerElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001786 !Context.getTargetInfo().hasBuiltinAtomic(
1787 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00001788 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001789
1790 llvm::AtomicRMWInst::BinOp RMWOp;
1791 switch (BO) {
1792 case BO_Add:
1793 RMWOp = llvm::AtomicRMWInst::Add;
1794 break;
1795 case BO_Sub:
1796 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00001797 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001798 RMWOp = llvm::AtomicRMWInst::Sub;
1799 break;
1800 case BO_And:
1801 RMWOp = llvm::AtomicRMWInst::And;
1802 break;
1803 case BO_Or:
1804 RMWOp = llvm::AtomicRMWInst::Or;
1805 break;
1806 case BO_Xor:
1807 RMWOp = llvm::AtomicRMWInst::Xor;
1808 break;
1809 case BO_LT:
1810 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1811 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
1812 : llvm::AtomicRMWInst::Max)
1813 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
1814 : llvm::AtomicRMWInst::UMax);
1815 break;
1816 case BO_GT:
1817 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1818 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
1819 : llvm::AtomicRMWInst::Min)
1820 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
1821 : llvm::AtomicRMWInst::UMin);
1822 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001823 case BO_Assign:
1824 RMWOp = llvm::AtomicRMWInst::Xchg;
1825 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001826 case BO_Mul:
1827 case BO_Div:
1828 case BO_Rem:
1829 case BO_Shl:
1830 case BO_Shr:
1831 case BO_LAnd:
1832 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001833 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001834 case BO_PtrMemD:
1835 case BO_PtrMemI:
1836 case BO_LE:
1837 case BO_GE:
1838 case BO_EQ:
1839 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001840 case BO_AddAssign:
1841 case BO_SubAssign:
1842 case BO_AndAssign:
1843 case BO_OrAssign:
1844 case BO_XorAssign:
1845 case BO_MulAssign:
1846 case BO_DivAssign:
1847 case BO_RemAssign:
1848 case BO_ShlAssign:
1849 case BO_ShrAssign:
1850 case BO_Comma:
1851 llvm_unreachable("Unsupported atomic update operation");
1852 }
1853 auto *UpdateVal = Update.getScalarVal();
1854 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
1855 UpdateVal = CGF.Builder.CreateIntCast(
1856 IC, X.getAddress()->getType()->getPointerElementType(),
1857 X.getType()->hasSignedIntegerRepresentation());
1858 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001859 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getAddress(), UpdateVal, AO);
1860 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001861}
1862
Alexey Bataev5e018f92015-04-23 06:35:10 +00001863std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001864 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
1865 llvm::AtomicOrdering AO, SourceLocation Loc,
1866 const llvm::function_ref<RValue(RValue)> &CommonGen) {
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;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001873 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
1874 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001875 if (X.isGlobalReg()) {
1876 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
1877 // 'xrval'.
1878 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
1879 } else {
1880 // Perform compare-and-swap procedure.
1881 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00001882 }
1883 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001884 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001885}
1886
1887static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
1888 const Expr *X, const Expr *E,
1889 const Expr *UE, bool IsXLHSInRHSPart,
1890 SourceLocation Loc) {
1891 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1892 "Update expr in 'atomic update' must be a binary operator.");
1893 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1894 // Update expressions are allowed to have the following forms:
1895 // x binop= expr; -> xrval + expr;
1896 // x++, ++x -> xrval + 1;
1897 // x--, --x -> xrval - 1;
1898 // x = x binop expr; -> xrval binop expr
1899 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001900 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00001901 LValue XLValue = CGF.EmitLValue(X);
1902 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001903 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001904 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1905 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1906 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1907 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1908 auto Gen =
1909 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
1910 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1911 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1912 return CGF.EmitAnyExpr(UE);
1913 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00001914 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
1915 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1916 // OpenMP, 2.12.6, atomic Construct
1917 // Any atomic construct with a seq_cst clause forces the atomically
1918 // performed operation to include an implicit flush operation without a
1919 // list.
1920 if (IsSeqCst)
1921 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1922}
1923
1924static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001925 QualType SourceType, QualType ResType,
1926 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00001927 switch (CGF.getEvaluationKind(ResType)) {
1928 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001929 return RValue::get(
1930 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00001931 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001932 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001933 return RValue::getComplex(Res.first, Res.second);
1934 }
1935 case TEK_Aggregate:
1936 break;
1937 }
1938 llvm_unreachable("Must be a scalar or complex.");
1939}
1940
1941static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
1942 bool IsPostfixUpdate, const Expr *V,
1943 const Expr *X, const Expr *E,
1944 const Expr *UE, bool IsXLHSInRHSPart,
1945 SourceLocation Loc) {
1946 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
1947 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
1948 RValue NewVVal;
1949 LValue VLValue = CGF.EmitLValue(V);
1950 LValue XLValue = CGF.EmitLValue(X);
1951 RValue ExprRValue = CGF.EmitAnyExpr(E);
1952 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
1953 QualType NewVValType;
1954 if (UE) {
1955 // 'x' is updated with some additional value.
1956 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1957 "Update expr in 'atomic capture' must be a binary operator.");
1958 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1959 // Update expressions are allowed to have the following forms:
1960 // x binop= expr; -> xrval + expr;
1961 // x++, ++x -> xrval + 1;
1962 // x--, --x -> xrval - 1;
1963 // x = x binop expr; -> xrval binop expr
1964 // x = expr Op x; - > expr binop xrval;
1965 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1966 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1967 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1968 NewVValType = XRValExpr->getType();
1969 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1970 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
1971 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
1972 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1973 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1974 RValue Res = CGF.EmitAnyExpr(UE);
1975 NewVVal = IsPostfixUpdate ? XRValue : Res;
1976 return Res;
1977 };
1978 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1979 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1980 if (Res.first) {
1981 // 'atomicrmw' instruction was generated.
1982 if (IsPostfixUpdate) {
1983 // Use old value from 'atomicrmw'.
1984 NewVVal = Res.second;
1985 } else {
1986 // 'atomicrmw' does not provide new value, so evaluate it using old
1987 // value of 'x'.
1988 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1989 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
1990 NewVVal = CGF.EmitAnyExpr(UE);
1991 }
1992 }
1993 } else {
1994 // 'x' is simply rewritten with some 'expr'.
1995 NewVValType = X->getType().getNonReferenceType();
1996 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001997 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001998 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
1999 NewVVal = XRValue;
2000 return ExprRValue;
2001 };
2002 // Try to perform atomicrmw xchg, otherwise simple exchange.
2003 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2004 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
2005 Loc, Gen);
2006 if (Res.first) {
2007 // 'atomicrmw' instruction was generated.
2008 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2009 }
2010 }
2011 // Emit post-update store to 'v' of old/new 'x' value.
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002012 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002013 // OpenMP, 2.12.6, atomic Construct
2014 // Any atomic construct with a seq_cst clause forces the atomically
2015 // performed operation to include an implicit flush operation without a
2016 // list.
2017 if (IsSeqCst)
2018 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2019}
2020
Alexey Bataevb57056f2015-01-22 06:17:56 +00002021static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002022 bool IsSeqCst, bool IsPostfixUpdate,
2023 const Expr *X, const Expr *V, const Expr *E,
2024 const Expr *UE, bool IsXLHSInRHSPart,
2025 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002026 switch (Kind) {
2027 case OMPC_read:
2028 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
2029 break;
2030 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00002031 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
2032 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002033 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002034 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00002035 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2036 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002037 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002038 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2039 IsXLHSInRHSPart, Loc);
2040 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002041 case OMPC_if:
2042 case OMPC_final:
2043 case OMPC_num_threads:
2044 case OMPC_private:
2045 case OMPC_firstprivate:
2046 case OMPC_lastprivate:
2047 case OMPC_reduction:
2048 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00002049 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002050 case OMPC_collapse:
2051 case OMPC_default:
2052 case OMPC_seq_cst:
2053 case OMPC_shared:
2054 case OMPC_linear:
2055 case OMPC_aligned:
2056 case OMPC_copyin:
2057 case OMPC_copyprivate:
2058 case OMPC_flush:
2059 case OMPC_proc_bind:
2060 case OMPC_schedule:
2061 case OMPC_ordered:
2062 case OMPC_nowait:
2063 case OMPC_untied:
2064 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002065 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002066 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00002067 case OMPC_device:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002068 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2069 }
2070}
2071
2072void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002073 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00002074 OpenMPClauseKind Kind = OMPC_unknown;
2075 for (auto *C : S.clauses()) {
2076 // Find first clause (skip seq_cst clause, if it is first).
2077 if (C->getClauseKind() != OMPC_seq_cst) {
2078 Kind = C->getClauseKind();
2079 break;
2080 }
2081 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002082
2083 const auto *CS =
2084 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002085 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00002086 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002087 }
2088 // Processing for statements under 'atomic capture'.
2089 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2090 for (const auto *C : Compound->body()) {
2091 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2092 enterFullExpression(EWC);
2093 }
2094 }
2095 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002096
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002097 LexicalScope Scope(*this, S.getSourceRange());
2098 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002099 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2100 S.getV(), S.getExpr(), S.getUpdateExpr(),
2101 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002102 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002103 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00002104}
2105
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002106void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) {
2107 llvm_unreachable("CodeGen for 'omp target' is not supported yet.");
2108}
2109
Alexey Bataev13314bf2014-10-09 04:18:56 +00002110void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
2111 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
2112}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002113
2114void CodeGenFunction::EmitOMPCancellationPointDirective(
2115 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00002116 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
2117 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002118}
2119
Alexey Bataev80909872015-07-02 11:25:17 +00002120void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002121 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(),
2122 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00002123}
2124
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002125CodeGenFunction::JumpDest
2126CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
2127 if (Kind == OMPD_parallel || Kind == OMPD_task)
2128 return ReturnBlock;
2129 else if (Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections)
2130 return BreakContinueStack.empty() ? JumpDest()
2131 : BreakContinueStack.back().BreakBlock;
2132 return JumpDest();
2133}
Michael Wong65f367f2015-07-21 13:44:28 +00002134
2135// Generate the instructions for '#pragma omp target data' directive.
2136void CodeGenFunction::EmitOMPTargetDataDirective(
2137 const OMPTargetDataDirective &S) {
2138
2139 // emit the code inside the construct for now
2140 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Michael Wongb5c16982015-08-11 04:52:01 +00002141 CGM.getOpenMPRuntime().emitInlinedDirective(
2142 *this, OMPD_target_data,
2143 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
Michael Wong65f367f2015-07-21 13:44:28 +00002144}