blob: 3ac3dfaf4533f83e856143dc7aad69e7e9d0cbeb [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(
John McCall7f416cc2015-09-08 08:05:57 +000027 Address DestAddr, Address SrcAddr, QualType OriginalType,
28 const llvm::function_ref<void(Address, Address)> &CopyGen) {
Alexey Bataev420d45b2015-04-14 05:11:24 +000029 // Perform element-by-element initialization.
30 QualType ElementTy;
John McCall7f416cc2015-09-08 08:05:57 +000031
32 // Drill down to the base element type on both arrays.
Alexey Bataev420d45b2015-04-14 05:11:24 +000033 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
John McCall7f416cc2015-09-08 08:05:57 +000034 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
35 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
36
37 auto SrcBegin = SrcAddr.getPointer();
38 auto DestBegin = DestAddr.getPointer();
Alexey Bataev420d45b2015-04-14 05:11:24 +000039 // Cast from pointer to array type to pointer to single element.
Alexey Bataev420d45b2015-04-14 05:11:24 +000040 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
41 // The basic structure here is a while-do loop.
42 auto BodyBB = createBasicBlock("omp.arraycpy.body");
43 auto DoneBB = createBasicBlock("omp.arraycpy.done");
44 auto IsEmpty =
45 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
46 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000047
Alexey Bataev420d45b2015-04-14 05:11:24 +000048 // Enter the loop body, making that address the current address.
49 auto EntryBB = Builder.GetInsertBlock();
50 EmitBlock(BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +000051
52 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
53
54 llvm::PHINode *SrcElementPHI =
55 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
56 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
57 Address SrcElementCurrent =
58 Address(SrcElementPHI,
59 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
60
61 llvm::PHINode *DestElementPHI =
62 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
63 DestElementPHI->addIncoming(DestBegin, EntryBB);
64 Address DestElementCurrent =
65 Address(DestElementPHI,
66 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
Alexey Bataev4a5bb772014-10-08 14:01:46 +000067
Alexey Bataev420d45b2015-04-14 05:11:24 +000068 // Emit copy.
69 CopyGen(DestElementCurrent, SrcElementCurrent);
70
71 // Shift the address forward by one element.
72 auto DestElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +000073 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +000074 auto SrcElementNext = Builder.CreateConstGEP1_32(
John McCall7f416cc2015-09-08 08:05:57 +000075 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
Alexey Bataev420d45b2015-04-14 05:11:24 +000076 // Check whether we've reached the end.
77 auto Done =
78 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
79 Builder.CreateCondBr(Done, DoneBB, BodyBB);
John McCall7f416cc2015-09-08 08:05:57 +000080 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
81 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
Alexey Bataev420d45b2015-04-14 05:11:24 +000082
83 // Done.
84 EmitBlock(DoneBB, /*IsFinished=*/true);
85}
86
John McCall7f416cc2015-09-08 08:05:57 +000087void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
88 Address SrcAddr, const VarDecl *DestVD,
Alexey Bataev420d45b2015-04-14 05:11:24 +000089 const VarDecl *SrcVD, const Expr *Copy) {
90 if (OriginalType->isArrayType()) {
91 auto *BO = dyn_cast<BinaryOperator>(Copy);
92 if (BO && BO->getOpcode() == BO_Assign) {
93 // Perform simple memcpy for simple copying.
John McCall7f416cc2015-09-08 08:05:57 +000094 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
Alexey Bataev420d45b2015-04-14 05:11:24 +000095 } else {
96 // For arrays with complex element types perform element by element
97 // copying.
John McCall7f416cc2015-09-08 08:05:57 +000098 EmitOMPAggregateAssign(
Alexey Bataev420d45b2015-04-14 05:11:24 +000099 DestAddr, SrcAddr, OriginalType,
John McCall7f416cc2015-09-08 08:05:57 +0000100 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000101 // Working with the single array element, so have to remap
102 // destination and source variables to corresponding array
103 // elements.
John McCall7f416cc2015-09-08 08:05:57 +0000104 CodeGenFunction::OMPPrivateScope Remap(*this);
105 Remap.addPrivate(DestVD, [DestElement]() -> Address {
Alexey Bataev420d45b2015-04-14 05:11:24 +0000106 return DestElement;
107 });
108 Remap.addPrivate(
John McCall7f416cc2015-09-08 08:05:57 +0000109 SrcVD, [SrcElement]() -> Address { return SrcElement; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000110 (void)Remap.Privatize();
John McCall7f416cc2015-09-08 08:05:57 +0000111 EmitIgnoredExpr(Copy);
Alexey Bataev420d45b2015-04-14 05:11:24 +0000112 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000113 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000114 } else {
115 // Remap pseudo source variable to private copy.
John McCall7f416cc2015-09-08 08:05:57 +0000116 CodeGenFunction::OMPPrivateScope Remap(*this);
117 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
118 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
Alexey Bataev420d45b2015-04-14 05:11:24 +0000119 (void)Remap.Privatize();
120 // Emit copying of the whole variable.
John McCall7f416cc2015-09-08 08:05:57 +0000121 EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000122 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000123}
124
Alexey Bataev69c62a92015-04-15 04:52:20 +0000125bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
126 OMPPrivateScope &PrivateScope) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000127 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000128 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000129 auto IRef = C->varlist_begin();
130 auto InitsRef = C->inits().begin();
131 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000132 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000133 if (EmittedAsFirstprivate.count(OrigVD) == 0) {
134 EmittedAsFirstprivate.insert(OrigVD);
135 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
136 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
137 bool IsRegistered;
138 DeclRefExpr DRE(
139 const_cast<VarDecl *>(OrigVD),
140 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
141 OrigVD) != nullptr,
142 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000143 Address OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000144 QualType Type = OrigVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000145 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000146 // Emit VarDecl with copy init for arrays.
147 // Get the address of the original variable captured in current
148 // captured region.
John McCall7f416cc2015-09-08 08:05:57 +0000149 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000150 auto Emission = EmitAutoVarAlloca(*VD);
151 auto *Init = VD->getInit();
152 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
153 // Perform simple memcpy.
154 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000155 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000156 } else {
157 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000158 Emission.getAllocatedAddress(), OriginalAddr, Type,
John McCall7f416cc2015-09-08 08:05:57 +0000159 [this, VDInit, Init](Address DestElement,
160 Address SrcElement) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000161 // Clean up any temporaries needed by the initialization.
162 RunCleanupsScope InitScope(*this);
163 // Emit initialization for single element.
John McCall7f416cc2015-09-08 08:05:57 +0000164 setAddrOfLocalVar(VDInit, SrcElement);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000165 EmitAnyExprToMem(Init, DestElement,
166 Init->getType().getQualifiers(),
167 /*IsInitializer*/ false);
168 LocalDeclMap.erase(VDInit);
169 });
170 }
171 EmitAutoVarCleanups(Emission);
172 return Emission.getAllocatedAddress();
173 });
174 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000175 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000176 // Emit private VarDecl with copy init.
177 // Remap temp VDInit variable to the address of the original
178 // variable
179 // (for proper handling of captured global variables).
John McCall7f416cc2015-09-08 08:05:57 +0000180 setAddrOfLocalVar(VDInit, OriginalAddr);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000181 EmitDecl(*VD);
182 LocalDeclMap.erase(VDInit);
183 return GetAddrOfLocalVar(VD);
184 });
185 }
186 assert(IsRegistered &&
187 "firstprivate var already registered as private");
188 // Silence the warning about unused variable.
189 (void)IsRegistered;
190 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000191 ++IRef, ++InitsRef;
192 }
193 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000194 return !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000195}
196
Alexey Bataev03b340a2014-10-21 03:16:40 +0000197void CodeGenFunction::EmitOMPPrivateClause(
198 const OMPExecutableDirective &D,
199 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev50a64582015-04-22 12:24:45 +0000200 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000201 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000202 auto IRef = C->varlist_begin();
203 for (auto IInit : C->private_copies()) {
204 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000205 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
206 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
207 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000208 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataev50a64582015-04-22 12:24:45 +0000209 // Emit private VarDecl with copy init.
210 EmitDecl(*VD);
211 return GetAddrOfLocalVar(VD);
212 });
213 assert(IsRegistered && "private var already registered as private");
214 // Silence the warning about unused variable.
215 (void)IsRegistered;
216 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000217 ++IRef;
218 }
219 }
220}
221
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000222bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
223 // threadprivate_var1 = master_threadprivate_var1;
224 // operator=(threadprivate_var2, master_threadprivate_var2);
225 // ...
226 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000227 llvm::DenseSet<const VarDecl *> CopiedVars;
228 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000229 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000230 auto IRef = C->varlist_begin();
231 auto ISrcRef = C->source_exprs().begin();
232 auto IDestRef = C->destination_exprs().begin();
233 for (auto *AssignOp : C->assignment_ops()) {
234 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000235 QualType Type = VD->getType();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000236 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000237
238 // Get the address of the master variable. If we are emitting code with
239 // TLS support, the address is passed from the master as field in the
240 // captured declaration.
John McCall7f416cc2015-09-08 08:05:57 +0000241 Address MasterAddr = Address::invalid();
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000242 if (getLangOpts().OpenMPUseTLS &&
243 getContext().getTargetInfo().isTLSSupported()) {
244 assert(CapturedStmtInfo->lookup(VD) &&
245 "Copyin threadprivates should have been captured!");
246 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
247 VK_LValue, (*IRef)->getExprLoc());
248 MasterAddr = EmitLValue(&DRE).getAddress();
249 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000250 MasterAddr =
251 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
252 : CGM.GetAddrOfGlobal(VD),
253 getContext().getDeclAlign(VD));
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000254 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000255 // Get the address of the threadprivate variable.
John McCall7f416cc2015-09-08 08:05:57 +0000256 Address PrivateAddr = EmitLValue(*IRef).getAddress();
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000257 if (CopiedVars.size() == 1) {
258 // At first check if current thread is a master thread. If it is, no
259 // need to copy data.
260 CopyBegin = createBasicBlock("copyin.not.master");
261 CopyEnd = createBasicBlock("copyin.not.master.end");
262 Builder.CreateCondBr(
263 Builder.CreateICmpNE(
John McCall7f416cc2015-09-08 08:05:57 +0000264 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
265 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000266 CopyBegin, CopyEnd);
267 EmitBlock(CopyBegin);
268 }
269 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
270 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000271 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000272 }
273 ++IRef;
274 ++ISrcRef;
275 ++IDestRef;
276 }
277 }
278 if (CopyEnd) {
279 // Exit out of copying procedure for non-master thread.
280 EmitBlock(CopyEnd, /*IsFinished=*/true);
281 return true;
282 }
283 return false;
284}
285
Alexey Bataev38e89532015-04-16 04:54:05 +0000286bool CodeGenFunction::EmitOMPLastprivateClauseInit(
287 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000288 bool HasAtLeastOneLastprivate = false;
289 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000290 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000291 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000292 auto IRef = C->varlist_begin();
293 auto IDestRef = C->destination_exprs().begin();
294 for (auto *IInit : C->private_copies()) {
295 // Keep the address of the original variable for future update at the end
296 // of the loop.
297 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
298 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
299 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000300 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev38e89532015-04-16 04:54:05 +0000301 DeclRefExpr DRE(
302 const_cast<VarDecl *>(OrigVD),
303 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
304 OrigVD) != nullptr,
305 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
306 return EmitLValue(&DRE).getAddress();
307 });
308 // Check if the variable is also a firstprivate: in this case IInit is
309 // not generated. Initialization of this variable will happen in codegen
310 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000311 if (IInit) {
312 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
313 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000314 PrivateScope.addPrivate(OrigVD, [&]() -> Address {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000315 // Emit private VarDecl with copy init.
316 EmitDecl(*VD);
317 return GetAddrOfLocalVar(VD);
318 });
319 assert(IsRegistered &&
320 "lastprivate var already registered as private");
321 (void)IsRegistered;
322 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000323 }
324 ++IRef, ++IDestRef;
325 }
326 }
327 return HasAtLeastOneLastprivate;
328}
329
330void CodeGenFunction::EmitOMPLastprivateClauseFinal(
331 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
332 // Emit following code:
333 // if (<IsLastIterCond>) {
334 // orig_var1 = private_orig_var1;
335 // ...
336 // orig_varn = private_orig_varn;
337 // }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000338 llvm::BasicBlock *ThenBB = nullptr;
339 llvm::BasicBlock *DoneBB = nullptr;
340 if (IsLastIterCond) {
341 ThenBB = createBasicBlock(".omp.lastprivate.then");
342 DoneBB = createBasicBlock(".omp.lastprivate.done");
343 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
344 EmitBlock(ThenBB);
345 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000346 llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
347 const Expr *LastIterVal = nullptr;
348 const Expr *IVExpr = nullptr;
349 const Expr *IncExpr = nullptr;
350 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000351 if (isOpenMPWorksharingDirective(D.getDirectiveKind())) {
352 LastIterVal = cast<VarDecl>(cast<DeclRefExpr>(
353 LoopDirective->getUpperBoundVariable())
354 ->getDecl())
355 ->getAnyInitializer();
356 IVExpr = LoopDirective->getIterationVariable();
357 IncExpr = LoopDirective->getInc();
358 auto IUpdate = LoopDirective->updates().begin();
359 for (auto *E : LoopDirective->counters()) {
360 auto *D = cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
361 LoopCountersAndUpdates[D] = *IUpdate;
362 ++IUpdate;
363 }
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000364 }
365 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000366 {
Alexey Bataev38e89532015-04-16 04:54:05 +0000367 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000368 bool FirstLCV = true;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000369 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000370 auto IRef = C->varlist_begin();
371 auto ISrcRef = C->source_exprs().begin();
372 auto IDestRef = C->destination_exprs().begin();
373 for (auto *AssignOp : C->assignment_ops()) {
374 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000375 QualType Type = PrivateVD->getType();
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000376 auto *CanonicalVD = PrivateVD->getCanonicalDecl();
377 if (AlreadyEmittedVars.insert(CanonicalVD).second) {
378 // If lastprivate variable is a loop control variable for loop-based
379 // directive, update its value before copyin back to original
380 // variable.
381 if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD)) {
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000382 if (FirstLCV && LastIterVal) {
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000383 EmitAnyExprToMem(LastIterVal, EmitLValue(IVExpr).getAddress(),
384 IVExpr->getType().getQualifiers(),
385 /*IsInitializer=*/false);
386 EmitIgnoredExpr(IncExpr);
387 FirstLCV = false;
388 }
389 EmitIgnoredExpr(UpExpr);
390 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000391 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
392 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
393 // Get the address of the original variable.
John McCall7f416cc2015-09-08 08:05:57 +0000394 Address OriginalAddr = GetAddrOfLocalVar(DestVD);
Alexey Bataev38e89532015-04-16 04:54:05 +0000395 // Get the address of the private variable.
John McCall7f416cc2015-09-08 08:05:57 +0000396 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
397 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
Alexey Bataevcaacd532015-09-04 11:26:21 +0000398 PrivateAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000399 Address(Builder.CreateLoad(PrivateAddr),
400 getNaturalTypeAlignment(RefTy->getPointeeType()));
401 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000402 }
403 ++IRef;
404 ++ISrcRef;
405 ++IDestRef;
406 }
407 }
408 }
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000409 if (IsLastIterCond) {
410 EmitBlock(DoneBB, /*IsFinished=*/true);
411 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000412}
413
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000414void CodeGenFunction::EmitOMPReductionClauseInit(
415 const OMPExecutableDirective &D,
416 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000417 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000418 auto ILHS = C->lhs_exprs().begin();
419 auto IRHS = C->rhs_exprs().begin();
420 for (auto IRef : C->varlists()) {
421 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
422 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
423 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
424 // Store the address of the original variable associated with the LHS
425 // implicit variable.
John McCall7f416cc2015-09-08 08:05:57 +0000426 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> Address {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000427 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
428 CapturedStmtInfo->lookup(OrigVD) != nullptr,
429 IRef->getType(), VK_LValue, IRef->getExprLoc());
430 return EmitLValue(&DRE).getAddress();
431 });
432 // Emit reduction copy.
433 bool IsRegistered =
John McCall7f416cc2015-09-08 08:05:57 +0000434 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> Address {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000435 // Emit private VarDecl with reduction init.
436 EmitDecl(*PrivateVD);
437 return GetAddrOfLocalVar(PrivateVD);
438 });
439 assert(IsRegistered && "private var already registered as private");
440 // Silence the warning about unused variable.
441 (void)IsRegistered;
442 ++ILHS, ++IRHS;
443 }
444 }
445}
446
447void CodeGenFunction::EmitOMPReductionClauseFinal(
448 const OMPExecutableDirective &D) {
449 llvm::SmallVector<const Expr *, 8> LHSExprs;
450 llvm::SmallVector<const Expr *, 8> RHSExprs;
451 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000452 bool HasAtLeastOneReduction = false;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000453 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000454 HasAtLeastOneReduction = true;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000455 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
456 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
457 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
458 }
459 if (HasAtLeastOneReduction) {
460 // Emit nowait reduction if nowait clause is present or directive is a
461 // parallel directive (it always has implicit barrier).
462 CGM.getOpenMPRuntime().emitReduction(
463 *this, D.getLocEnd(), LHSExprs, RHSExprs, ReductionOps,
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000464 D.getSingleClause<OMPNowaitClause>() ||
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000465 isOpenMPParallelDirective(D.getDirectiveKind()) ||
466 D.getDirectiveKind() == OMPD_simd,
467 D.getDirectiveKind() == OMPD_simd);
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000468 }
469}
470
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000471static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
472 const OMPExecutableDirective &S,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000473 OpenMPDirectiveKind InnermostKind,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000474 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000475 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000476 auto CapturedStruct = CGF.GenerateCapturedStmtArgument(*CS);
477 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000478 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000479 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
Alexey Bataev1d677132015-04-22 13:57:31 +0000480 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +0000481 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
482 /*IgnoreResultAssign*/ true);
483 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
484 CGF, NumThreads, NumThreadsClause->getLocStart());
485 }
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000486 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
Alexey Bataev7f210c62015-06-18 13:40:03 +0000487 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
Alexey Bataev7f210c62015-06-18 13:40:03 +0000488 CGF.CGM.getOpenMPRuntime().emitProcBindClause(
489 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
490 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000491 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +0000492 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
493 if (C->getNameModifier() == OMPD_unknown ||
494 C->getNameModifier() == OMPD_parallel) {
495 IfCond = C->getCondition();
496 break;
497 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000498 }
499 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
500 CapturedStruct, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000501}
502
503void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
504 LexicalScope Scope(*this, S.getSourceRange());
505 // Emit parallel region as a standalone region.
506 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
507 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000508 bool Copyins = CGF.EmitOMPCopyinClause(S);
509 bool Firstprivates = CGF.EmitOMPFirstprivateClause(S, PrivateScope);
510 if (Copyins || Firstprivates) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000511 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000512 // initialization of firstprivate variables or propagation master's thread
513 // values of threadprivate variables to local instances of that variables
514 // of all other implicit threads.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000515 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
516 OMPD_unknown);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000517 }
518 CGF.EmitOMPPrivateClause(S, PrivateScope);
519 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
520 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000521 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000522 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000523 // Emit implicit barrier at the end of the 'parallel' directive.
524 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
525 OMPD_unknown);
526 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000527 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +0000528}
Alexander Musman515ad8c2014-05-22 08:54:05 +0000529
Alexey Bataev0f34da12015-07-02 04:17:07 +0000530void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
531 JumpDest LoopExit) {
Alexander Musmana5f070a2014-10-01 06:03:56 +0000532 RunCleanupsScope BodyScope(*this);
533 // Update counters values on current iteration.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000534 for (auto I : D.updates()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +0000535 EmitIgnoredExpr(I);
536 }
Alexander Musman3276a272015-03-21 10:12:56 +0000537 // Update the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000538 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexander Musman3276a272015-03-21 10:12:56 +0000539 for (auto U : C->updates()) {
540 EmitIgnoredExpr(U);
541 }
542 }
543
Alexander Musmana5f070a2014-10-01 06:03:56 +0000544 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +0000545 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexey Bataev0f34da12015-07-02 04:17:07 +0000546 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000547 // Emit loop body.
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000548 EmitStmt(D.getBody());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000549 // The end (updates/cleanups).
550 EmitBlock(Continue.getBlock());
551 BreakContinueStack.pop_back();
Alexander Musmana5f070a2014-10-01 06:03:56 +0000552 // TODO: Update lastprivates if the SeparateIter flag is true.
553 // This will be implemented in a follow-up OMPLastprivateClause patch, but
554 // result should be still correct without it, as we do not make these
555 // variables private yet.
Alexander Musmana5f070a2014-10-01 06:03:56 +0000556}
557
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000558void CodeGenFunction::EmitOMPInnerLoop(
559 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
560 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000561 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
562 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +0000563 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000564
565 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +0000566 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000567 EmitBlock(CondBlock);
568 LoopStack.push(CondBlock);
569
570 // If there are any cleanups between here and the loop-exit scope,
571 // create a block to stage a loop exit along.
572 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +0000573 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +0000574 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000575
Alexander Musmand196ef22014-10-07 08:57:09 +0000576 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000577
Alexey Bataev2df54a02015-03-12 08:53:29 +0000578 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +0000579 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000580 if (ExitBlock != LoopExit.getBlock()) {
581 EmitBlock(ExitBlock);
582 EmitBranchThroughCleanup(LoopExit);
583 }
584
585 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +0000586 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000587
588 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +0000589 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000590 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
591
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000592 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000593
594 // Emit "IV = IV + 1" and a back-edge to the condition block.
595 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +0000596 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000597 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000598 BreakContinueStack.pop_back();
599 EmitBranch(CondBlock);
600 LoopStack.pop();
601 // Emit the fall-through block.
602 EmitBlock(LoopExit.getBlock());
603}
604
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000605void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000606 // Emit inits for the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000607 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000608 for (auto Init : C->inits()) {
609 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000610 auto *OrigVD = cast<VarDecl>(
611 cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())->getDecl());
612 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
613 CapturedStmtInfo->lookup(OrigVD) != nullptr,
614 VD->getInit()->getType(), VK_LValue,
615 VD->getInit()->getExprLoc());
616 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
617 EmitExprAsInit(&DRE, VD,
John McCall7f416cc2015-09-08 08:05:57 +0000618 MakeAddrLValue(Emission.getAllocatedAddress(), VD->getType()),
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000619 /*capturedByInit=*/false);
620 EmitAutoVarCleanups(Emission);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000621 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000622 // Emit the linear steps for the linear clauses.
623 // If a step is not constant, it is pre-calculated before the loop.
624 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
625 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000626 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000627 // Emit calculation of the linear step.
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000628 EmitIgnoredExpr(CS);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000629 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000630 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000631}
632
633static void emitLinearClauseFinal(CodeGenFunction &CGF,
634 const OMPLoopDirective &D) {
Alexander Musman3276a272015-03-21 10:12:56 +0000635 // Emit the final values of the linear variables.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000636 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000637 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +0000638 for (auto F : C->finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000639 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
640 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000641 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
Alexey Bataev39f915b82015-05-08 10:41:21 +0000642 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000643 Address OrigAddr = CGF.EmitLValue(&DRE).getAddress();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000644 CodeGenFunction::OMPPrivateScope VarScope(CGF);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000645 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +0000646 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev39f915b82015-05-08 10:41:21 +0000647 (void)VarScope.Privatize();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000648 CGF.EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000649 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +0000650 }
651 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000652}
653
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000654static void emitAlignedClause(CodeGenFunction &CGF,
655 const OMPExecutableDirective &D) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000656 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000657 unsigned ClauseAlignment = 0;
658 if (auto AlignmentExpr = Clause->getAlignment()) {
659 auto AlignmentCI =
660 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
661 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
Alexander Musman09184fe2014-09-30 05:29:28 +0000662 }
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000663 for (auto E : Clause->varlists()) {
664 unsigned Alignment = ClauseAlignment;
665 if (Alignment == 0) {
666 // OpenMP [2.8.1, Description]
667 // If no optional parameter is specified, implementation-defined default
668 // alignments for SIMD instructions on the target platforms are assumed.
669 Alignment =
Alexey Bataev00396512015-07-02 03:40:19 +0000670 CGF.getContext()
671 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
672 E->getType()->getPointeeType()))
673 .getQuantity();
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000674 }
675 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
676 "alignment is not power of 2");
677 if (Alignment != 0) {
678 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
679 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
680 }
Alexander Musman09184fe2014-09-30 05:29:28 +0000681 }
682 }
683}
684
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000685static void emitPrivateLoopCounters(CodeGenFunction &CGF,
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000686 CodeGenFunction::OMPPrivateScope &LoopScope,
Alexey Bataeva8899172015-08-06 12:30:57 +0000687 ArrayRef<Expr *> Counters,
688 ArrayRef<Expr *> PrivateCounters) {
689 auto I = PrivateCounters.begin();
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000690 for (auto *E : Counters) {
Alexey Bataeva8899172015-08-06 12:30:57 +0000691 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
692 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000693 Address Addr = Address::invalid();
694 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000695 // Emit var without initialization.
Alexey Bataeva8899172015-08-06 12:30:57 +0000696 auto VarEmission = CGF.EmitAutoVarAlloca(*PrivateVD);
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000697 CGF.EmitAutoVarCleanups(VarEmission);
Alexey Bataeva8899172015-08-06 12:30:57 +0000698 Addr = VarEmission.getAllocatedAddress();
699 return Addr;
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000700 });
John McCall7f416cc2015-09-08 08:05:57 +0000701 (void)LoopScope.addPrivate(VD, [&]() -> Address { return Addr; });
Alexey Bataeva8899172015-08-06 12:30:57 +0000702 ++I;
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000703 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000704}
705
Alexey Bataev62dbb972015-04-22 11:59:37 +0000706static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
707 const Expr *Cond, llvm::BasicBlock *TrueBlock,
708 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +0000709 {
710 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +0000711 emitPrivateLoopCounters(CGF, PreCondScope, S.counters(),
712 S.private_counters());
Alexey Bataev6e8248f2015-06-11 10:53:56 +0000713 (void)PreCondScope.Privatize();
Alexey Bataev6e8248f2015-06-11 10:53:56 +0000714 // Get initial values of real counters.
Alexey Bataevb08f89f2015-08-14 12:25:37 +0000715 for (auto I : S.inits()) {
Alexey Bataev6e8248f2015-06-11 10:53:56 +0000716 CGF.EmitIgnoredExpr(I);
717 }
Alexey Bataev62dbb972015-04-22 11:59:37 +0000718 }
719 // Check that loop is executed at least one time.
720 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
721}
722
Alexander Musman3276a272015-03-21 10:12:56 +0000723static void
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000724emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
Alexander Musman3276a272015-03-21 10:12:56 +0000725 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000726 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +0000727 auto CurPrivate = C->privates().begin();
Alexey Bataevc925aa32015-04-27 08:00:32 +0000728 for (auto *E : C->varlists()) {
Alexey Bataevbd9fec12015-08-18 06:47:21 +0000729 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
730 auto *PrivateVD =
731 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000732 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
Alexey Bataevbd9fec12015-08-18 06:47:21 +0000733 // Emit private VarDecl with copy init.
734 CGF.EmitVarDecl(*PrivateVD);
735 return CGF.GetAddrOfLocalVar(PrivateVD);
Alexander Musman3276a272015-03-21 10:12:56 +0000736 });
737 assert(IsRegistered && "linear var already registered as private");
738 // Silence the warning about unused variable.
739 (void)IsRegistered;
Alexey Bataevbd9fec12015-08-18 06:47:21 +0000740 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +0000741 }
742 }
743}
744
Alexey Bataev45bfad52015-08-21 12:19:04 +0000745static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
746 const OMPExecutableDirective &D) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000747 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
Alexey Bataev45bfad52015-08-21 12:19:04 +0000748 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
749 /*ignoreResult=*/true);
750 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
751 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
752 // In presence of finite 'safelen', it may be unsafe to mark all
753 // the memory instructions parallel, because loop-carried
754 // dependences of 'safelen' iterations are possible.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +0000755 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
756 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000757 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
758 /*ignoreResult=*/true);
759 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
Tyler Nowickida46d0e2015-07-14 23:03:09 +0000760 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000761 // In presence of finite 'safelen', it may be unsafe to mark all
762 // the memory instructions parallel, because loop-carried
763 // dependences of 'safelen' iterations are possible.
764 CGF.LoopStack.setParallel(false);
765 }
766}
767
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000768void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D) {
769 // Walk clauses and process safelen/lastprivate.
770 LoopStack.setParallel();
Tyler Nowickida46d0e2015-07-14 23:03:09 +0000771 LoopStack.setVectorizeEnable(true);
Alexey Bataev45bfad52015-08-21 12:19:04 +0000772 emitSimdlenSafelenClause(*this, D);
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000773}
774
775void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &D) {
776 auto IC = D.counters().begin();
777 for (auto F : D.finals()) {
778 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +0000779 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000780 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
781 CapturedStmtInfo->lookup(OrigVD) != nullptr,
782 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +0000783 Address OrigAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000784 OMPPrivateScope VarScope(*this);
785 VarScope.addPrivate(OrigVD,
John McCall7f416cc2015-09-08 08:05:57 +0000786 [OrigAddr]() -> Address { return OrigAddr; });
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000787 (void)VarScope.Privatize();
788 EmitIgnoredExpr(F);
789 }
790 ++IC;
791 }
792 emitLinearClauseFinal(*this, D);
793}
794
Alexander Musman515ad8c2014-05-22 08:54:05 +0000795void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000796 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000797 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000798 // for (IV in 0..LastIteration) BODY;
799 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000800 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000801 //
Alexander Musmana5f070a2014-10-01 06:03:56 +0000802
Alexey Bataev62dbb972015-04-22 11:59:37 +0000803 // Emit: if (PreCond) - begin.
804 // If the condition constant folds and can be elided, avoid emitting the
805 // whole loop.
806 bool CondConstant;
807 llvm::BasicBlock *ContBlock = nullptr;
808 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
809 if (!CondConstant)
810 return;
811 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000812 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
813 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +0000814 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
815 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +0000816 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +0000817 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000818 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000819
820 // Emit the loop iteration variable.
821 const Expr *IVExpr = S.getIterationVariable();
822 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
823 CGF.EmitVarDecl(*IVDecl);
824 CGF.EmitIgnoredExpr(S.getInit());
825
826 // Emit the iterations count variable.
827 // If it is not a variable, Sema decided to calculate iterations count on
Alexey Bataev7a228ff2015-05-21 07:59:51 +0000828 // each iteration (e.g., it is foldable into a constant).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000829 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
830 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
831 // Emit calculation of the iterations count.
832 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000833 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000834
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000835 CGF.EmitOMPSimdInit(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000836
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000837 emitAlignedClause(CGF, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +0000838 CGF.EmitOMPLinearClauseInit(S);
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000839 bool HasLastprivateClause;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000840 {
841 OMPPrivateScope LoopScope(CGF);
Alexey Bataeva8899172015-08-06 12:30:57 +0000842 emitPrivateLoopCounters(CGF, LoopScope, S.counters(),
843 S.private_counters());
Alexey Bataevcbdcbb72015-06-17 07:45:51 +0000844 emitPrivateLinearVars(CGF, S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000845 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000846 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000847 HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000848 (void)LoopScope.Privatize();
Alexey Bataev0f34da12015-07-02 04:17:07 +0000849 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
850 S.getInc(),
Alexey Bataev62dbb972015-04-22 11:59:37 +0000851 [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +0000852 CGF.EmitOMPLoopBody(S, JumpDest());
Alexey Bataev62dbb972015-04-22 11:59:37 +0000853 CGF.EmitStopPoint(&S);
854 },
855 [](CodeGenFunction &) {});
Alexey Bataevfc087ec2015-06-16 13:14:42 +0000856 // Emit final copy of the lastprivate variables at the end of loops.
857 if (HasLastprivateClause) {
858 CGF.EmitOMPLastprivateClauseFinal(S);
859 }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +0000860 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000861 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000862 CGF.EmitOMPSimdFinal(S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000863 // Emit: if (PreCond) - end.
864 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000865 CGF.EmitBranch(ContBlock);
866 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000867 }
868 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000869 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +0000870}
871
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000872void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
873 const OMPLoopDirective &S,
874 OMPPrivateScope &LoopScope,
John McCall7f416cc2015-09-08 08:05:57 +0000875 bool Ordered, Address LB,
876 Address UB, Address ST,
877 Address IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000878 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000879
880 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000881 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
Alexander Musman92bdaab2015-03-12 13:37:50 +0000882
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000883 assert((Ordered ||
884 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000885 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000886
887 // Emit outer loop.
888 //
889 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +0000890 // When schedule(dynamic,chunk_size) is specified, the iterations are
891 // distributed to threads in the team in chunks as the threads request them.
892 // Each thread executes a chunk of iterations, then requests another chunk,
893 // until no chunks remain to be distributed. Each chunk contains chunk_size
894 // iterations, except for the last chunk to be distributed, which may have
895 // fewer iterations. When no chunk_size is specified, it defaults to 1.
896 //
897 // When schedule(guided,chunk_size) is specified, the iterations are assigned
898 // to threads in the team in chunks as the executing threads request them.
899 // Each thread executes a chunk of iterations, then requests another chunk,
900 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
901 // each chunk is proportional to the number of unassigned iterations divided
902 // by the number of threads in the team, decreasing to 1. For a chunk_size
903 // with value k (greater than 1), the size of each chunk is determined in the
904 // same way, with the restriction that the chunks do not contain fewer than k
905 // iterations (except for the last chunk to be assigned, which may have fewer
906 // than k iterations).
907 //
908 // When schedule(auto) is specified, the decision regarding scheduling is
909 // delegated to the compiler and/or runtime system. The programmer gives the
910 // implementation the freedom to choose any possible mapping of iterations to
911 // threads in the team.
912 //
913 // When schedule(runtime) is specified, the decision regarding scheduling is
914 // deferred until run time, and the schedule and chunk size are taken from the
915 // run-sched-var ICV. If the ICV is set to auto, the schedule is
916 // implementation defined
917 //
918 // while(__kmpc_dispatch_next(&LB, &UB)) {
919 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000920 // while (idx <= UB) { BODY; ++idx;
921 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
922 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +0000923 // }
924 //
925 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000926 // When schedule(static, chunk_size) is specified, iterations are divided into
927 // chunks of size chunk_size, and the chunks are assigned to the threads in
928 // the team in a round-robin fashion in the order of the thread number.
929 //
930 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
931 // while (idx <= UB) { BODY; ++idx; } // inner loop
932 // LB = LB + ST;
933 // UB = UB + ST;
934 // }
935 //
Alexander Musman92bdaab2015-03-12 13:37:50 +0000936
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000937 const Expr *IVExpr = S.getIterationVariable();
938 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
939 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
940
John McCall7f416cc2015-09-08 08:05:57 +0000941 if (DynamicOrOrdered) {
942 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
943 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind,
944 IVSize, IVSigned, Ordered, UBVal, Chunk);
945 } else {
946 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
947 IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
948 }
Alexander Musman92bdaab2015-03-12 13:37:50 +0000949
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000950 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
951
952 // Start the loop with a block that tests the condition.
953 auto CondBlock = createBasicBlock("omp.dispatch.cond");
954 EmitBlock(CondBlock);
955 LoopStack.push(CondBlock);
956
957 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000958 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +0000959 // UB = min(UB, GlobalUB)
960 EmitIgnoredExpr(S.getEnsureUpperBound());
961 // IV = LB
962 EmitIgnoredExpr(S.getInit());
963 // IV < UB
Alexey Bataevae05c292015-06-16 11:59:36 +0000964 BoolCondVal = EvaluateExprAsBool(S.getCond());
Alexander Musman92bdaab2015-03-12 13:37:50 +0000965 } else {
966 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
967 IL, LB, UB, ST);
968 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000969
970 // If there are any cleanups between here and the loop-exit scope,
971 // create a block to stage a loop exit along.
972 auto ExitBlock = LoopExit.getBlock();
973 if (LoopScope.requiresCleanups())
974 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
975
976 auto LoopBody = createBasicBlock("omp.dispatch.body");
977 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
978 if (ExitBlock != LoopExit.getBlock()) {
979 EmitBlock(ExitBlock);
980 EmitBranchThroughCleanup(LoopExit);
981 }
982 EmitBlock(LoopBody);
983
Alexander Musman92bdaab2015-03-12 13:37:50 +0000984 // Emit "IV = LB" (in case of static schedule, we have already calculated new
985 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000986 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +0000987 EmitIgnoredExpr(S.getInit());
988
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000989 // Create a block for the increment.
990 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
991 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
992
Alexey Bataev58e5bdb2015-06-18 04:45:29 +0000993 // Generate !llvm.loop.parallel metadata for loads and stores for loops
994 // with dynamic/guided scheduling and without ordered clause.
995 if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
996 LoopStack.setParallel((ScheduleKind == OMPC_SCHEDULE_dynamic ||
997 ScheduleKind == OMPC_SCHEDULE_guided) &&
998 !Ordered);
999 } else {
1000 EmitOMPSimdInit(S);
1001 }
1002
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001003 SourceLocation Loc = S.getLocStart();
Alexey Bataev0f34da12015-07-02 04:17:07 +00001004 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1005 [&S, LoopExit](CodeGenFunction &CGF) {
1006 CGF.EmitOMPLoopBody(S, LoopExit);
1007 CGF.EmitStopPoint(&S);
1008 },
1009 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1010 if (Ordered) {
1011 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1012 CGF, Loc, IVSize, IVSigned);
1013 }
1014 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001015
1016 EmitBlock(Continue.getBlock());
1017 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001018 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001019 // Emit "LB = LB + Stride", "UB = UB + Stride".
1020 EmitIgnoredExpr(S.getNextLowerBound());
1021 EmitIgnoredExpr(S.getNextUpperBound());
1022 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001023
1024 EmitBranch(CondBlock);
1025 LoopStack.pop();
1026 // Emit the fall-through block.
1027 EmitBlock(LoopExit.getBlock());
1028
1029 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001030 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001031 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001032}
1033
Alexander Musmanc6388682014-12-15 07:07:06 +00001034/// \brief Emit a helper variable and return corresponding lvalue.
1035static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1036 const DeclRefExpr *Helper) {
1037 auto VDecl = cast<VarDecl>(Helper->getDecl());
1038 CGF.EmitVarDecl(*VDecl);
1039 return CGF.EmitLValue(Helper);
1040}
1041
Alexey Bataev040d5402015-05-12 08:35:28 +00001042static std::pair<llvm::Value * /*Chunk*/, OpenMPScheduleClauseKind>
1043emitScheduleClause(CodeGenFunction &CGF, const OMPLoopDirective &S,
1044 bool OuterRegion) {
1045 // Detect the loop schedule kind and chunk.
1046 auto ScheduleKind = OMPC_SCHEDULE_unknown;
1047 llvm::Value *Chunk = nullptr;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001048 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001049 ScheduleKind = C->getScheduleKind();
1050 if (const auto *Ch = C->getChunkSize()) {
1051 if (auto *ImpRef = cast_or_null<DeclRefExpr>(C->getHelperChunkSize())) {
1052 if (OuterRegion) {
1053 const VarDecl *ImpVar = cast<VarDecl>(ImpRef->getDecl());
1054 CGF.EmitVarDecl(*ImpVar);
1055 CGF.EmitStoreThroughLValue(
1056 CGF.EmitAnyExpr(Ch),
John McCall7f416cc2015-09-08 08:05:57 +00001057 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(ImpVar),
1058 ImpVar->getType()));
Alexey Bataev040d5402015-05-12 08:35:28 +00001059 } else {
1060 Ch = ImpRef;
1061 }
1062 }
1063 if (!C->getHelperChunkSize() || !OuterRegion) {
1064 Chunk = CGF.EmitScalarExpr(Ch);
1065 Chunk = CGF.EmitScalarConversion(Chunk, Ch->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001066 S.getIterationVariable()->getType(),
1067 S.getLocStart());
Alexey Bataev040d5402015-05-12 08:35:28 +00001068 }
1069 }
1070 }
1071 return std::make_pair(Chunk, ScheduleKind);
1072}
1073
Alexey Bataev38e89532015-04-16 04:54:05 +00001074bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001075 // Emit the loop iteration variable.
1076 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1077 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1078 EmitVarDecl(*IVDecl);
1079
1080 // Emit the iterations count variable.
1081 // If it is not a variable, Sema decided to calculate iterations count on each
1082 // iteration (e.g., it is foldable into a constant).
1083 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1084 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1085 // Emit calculation of the iterations count.
1086 EmitIgnoredExpr(S.getCalcLastIteration());
1087 }
1088
1089 auto &RT = CGM.getOpenMPRuntime();
1090
Alexey Bataev38e89532015-04-16 04:54:05 +00001091 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001092 // Check pre-condition.
1093 {
1094 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001095 // If the condition constant folds and can be elided, avoid emitting the
1096 // whole loop.
1097 bool CondConstant;
1098 llvm::BasicBlock *ContBlock = nullptr;
1099 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1100 if (!CondConstant)
1101 return false;
1102 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001103 auto *ThenBlock = createBasicBlock("omp.precond.then");
1104 ContBlock = createBasicBlock("omp.precond.end");
1105 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001106 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001107 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001108 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001109 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001110
1111 emitAlignedClause(*this, S);
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001112 EmitOMPLinearClauseInit(S);
Alexander Musmanc6388682014-12-15 07:07:06 +00001113 // Emit 'then' code.
1114 {
1115 // Emit helper vars inits.
1116 LValue LB =
1117 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1118 LValue UB =
1119 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1120 LValue ST =
1121 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1122 LValue IL =
1123 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1124
1125 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001126 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1127 // Emit implicit barrier to synchronize threads and avoid data races on
1128 // initialization of firstprivate variables.
1129 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1130 OMPD_unknown);
1131 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001132 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001133 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001134 EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataeva8899172015-08-06 12:30:57 +00001135 emitPrivateLoopCounters(*this, LoopScope, S.counters(),
1136 S.private_counters());
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001137 emitPrivateLinearVars(*this, S, LoopScope);
Alexander Musman7931b982015-03-16 07:14:41 +00001138 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001139
1140 // Detect the loop schedule kind and chunk.
Alexey Bataev040d5402015-05-12 08:35:28 +00001141 llvm::Value *Chunk;
1142 OpenMPScheduleClauseKind ScheduleKind;
1143 auto ScheduleInfo =
1144 emitScheduleClause(*this, S, /*OuterRegion=*/false);
1145 Chunk = ScheduleInfo.first;
1146 ScheduleKind = ScheduleInfo.second;
Alexander Musmanc6388682014-12-15 07:07:06 +00001147 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1148 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001149 const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
Alexander Musmanc6388682014-12-15 07:07:06 +00001150 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001151 /* Chunked */ Chunk != nullptr) &&
1152 !Ordered) {
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001153 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1154 EmitOMPSimdInit(S);
1155 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001156 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1157 // When no chunk_size is specified, the iteration space is divided into
1158 // chunks that are approximately equal in size, and at most one chunk is
1159 // distributed to each thread. Note that the size of the chunks is
1160 // unspecified in this case.
John McCall7f416cc2015-09-08 08:05:57 +00001161 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1162 IVSize, IVSigned, Ordered,
1163 IL.getAddress(), LB.getAddress(),
1164 UB.getAddress(), ST.getAddress());
Alexey Bataev0f34da12015-07-02 04:17:07 +00001165 auto LoopExit = getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
Alexander Musmanc6388682014-12-15 07:07:06 +00001166 // UB = min(UB, GlobalUB);
1167 EmitIgnoredExpr(S.getEnsureUpperBound());
1168 // IV = LB;
1169 EmitIgnoredExpr(S.getInit());
1170 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataevae05c292015-06-16 11:59:36 +00001171 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1172 S.getInc(),
Alexey Bataev0f34da12015-07-02 04:17:07 +00001173 [&S, LoopExit](CodeGenFunction &CGF) {
1174 CGF.EmitOMPLoopBody(S, LoopExit);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001175 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001176 },
1177 [](CodeGenFunction &) {});
Alexey Bataev0f34da12015-07-02 04:17:07 +00001178 EmitBlock(LoopExit.getBlock());
Alexander Musmanc6388682014-12-15 07:07:06 +00001179 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001180 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001181 } else {
1182 // Emit the outer loop, which requests its work chunk [LB..UB] from
1183 // runtime and runs the inner loop to process it.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001184 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, Ordered,
1185 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1186 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001187 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001188 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001189 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1190 if (HasLastprivateClause)
1191 EmitOMPLastprivateClauseFinal(
1192 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001193 }
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00001194 if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1195 EmitOMPSimdFinal(S);
1196 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001197 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001198 if (ContBlock) {
1199 EmitBranch(ContBlock);
1200 EmitBlock(ContBlock, true);
1201 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001202 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001203 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001204}
1205
1206void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001207 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev38e89532015-04-16 04:54:05 +00001208 bool HasLastprivates = false;
1209 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1210 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1211 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001212 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen);
Alexander Musmanc6388682014-12-15 07:07:06 +00001213
1214 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001215 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001216 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1217 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001218}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001219
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001220void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
1221 LexicalScope Scope(*this, S.getSourceRange());
1222 bool HasLastprivates = false;
1223 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1224 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1225 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001226 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001227
1228 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001229 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
Alexey Bataevcbdcbb72015-06-17 07:45:51 +00001230 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1231 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001232}
1233
Alexey Bataev2df54a02015-03-12 08:53:29 +00001234static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1235 const Twine &Name,
1236 llvm::Value *Init = nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +00001237 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001238 if (Init)
1239 CGF.EmitScalarInit(Init, LVal);
1240 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001241}
1242
Alexey Bataev0f34da12015-07-02 04:17:07 +00001243OpenMPDirectiveKind
1244CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001245 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1246 auto *CS = dyn_cast<CompoundStmt>(Stmt);
1247 if (CS && CS->size() > 1) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001248 bool HasLastprivates = false;
1249 auto &&CodeGen = [&S, CS, &HasLastprivates](CodeGenFunction &CGF) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001250 auto &C = CGF.CGM.getContext();
1251 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1252 // Emit helper vars inits.
1253 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1254 CGF.Builder.getInt32(0));
1255 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
1256 LValue UB =
1257 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1258 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1259 CGF.Builder.getInt32(1));
1260 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1261 CGF.Builder.getInt32(0));
1262 // Loop counter.
1263 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1264 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001265 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001266 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001267 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001268 // Generate condition for loop.
1269 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1270 OK_Ordinary, S.getLocStart(),
1271 /*fpContractable=*/false);
1272 // Increment for loop counter.
1273 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
1274 OK_Ordinary, S.getLocStart());
1275 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
1276 // Iterate through all sections and emit a switch construct:
1277 // switch (IV) {
1278 // case 0:
1279 // <SectionStmt[0]>;
1280 // break;
1281 // ...
1282 // case <NumSection> - 1:
1283 // <SectionStmt[<NumSection> - 1]>;
1284 // break;
1285 // }
1286 // .omp.sections.exit:
1287 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1288 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1289 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1290 CS->size());
1291 unsigned CaseNumber = 0;
Benjamin Kramer642f1732015-07-02 21:03:14 +00001292 for (auto *SubStmt : CS->children()) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001293 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1294 CGF.EmitBlock(CaseBB);
1295 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001296 CGF.EmitStmt(SubStmt);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001297 CGF.EmitBranch(ExitBB);
Benjamin Kramer642f1732015-07-02 21:03:14 +00001298 ++CaseNumber;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001299 }
1300 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1301 };
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001302
1303 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1304 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
1305 // Emit implicit barrier to synchronize threads and avoid data races on
1306 // initialization of firstprivate variables.
1307 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1308 OMPD_unknown);
1309 }
Alexey Bataev73870832015-04-27 04:12:12 +00001310 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001311 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001312 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001313 (void)LoopScope.Privatize();
1314
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001315 // Emit static non-chunked loop.
John McCall7f416cc2015-09-08 08:05:57 +00001316 CGF.CGM.getOpenMPRuntime().emitForStaticInit(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001317 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001318 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
1319 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001320 // UB = min(UB, GlobalUB);
1321 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1322 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1323 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1324 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1325 // IV = LB;
1326 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1327 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001328 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1329 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001330 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001331 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataeva89adf22015-04-27 05:04:13 +00001332 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001333
1334 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1335 if (HasLastprivates)
1336 CGF.EmitOMPLastprivateClauseFinal(
1337 S, CGF.Builder.CreateIsNotNull(
1338 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev2df54a02015-03-12 08:53:29 +00001339 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001340
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001341 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001342 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1343 // clause. Otherwise the barrier will be generated by the codegen for the
1344 // directive.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001345 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001346 // Emit implicit barrier to synchronize threads and avoid data races on
1347 // initialization of firstprivate variables.
Alexey Bataev0f34da12015-07-02 04:17:07 +00001348 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1349 OMPD_unknown);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001350 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001351 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001352 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001353 // If only one section is found - no need to generate loop, emit as a single
1354 // region.
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001355 bool HasFirstprivates;
Alexey Bataeva89adf22015-04-27 05:04:13 +00001356 // No need to generate reductions for sections with single section region, we
1357 // can use original shared variables for all operations.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001358 bool HasReductions = S.hasClausesOfKind<OMPReductionClause>();
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001359 // No need to generate lastprivates for sections with single section region,
1360 // we can use original shared variable for all calculations with barrier at
1361 // the end of the sections.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001362 bool HasLastprivates = S.hasClausesOfKind<OMPLastprivateClause>();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001363 auto &&CodeGen = [Stmt, &S, &HasFirstprivates](CodeGenFunction &CGF) {
1364 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1365 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev73870832015-04-27 04:12:12 +00001366 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001367 (void)SingleScope.Privatize();
1368
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001369 CGF.EmitStmt(Stmt);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001370 };
Alexey Bataev0f34da12015-07-02 04:17:07 +00001371 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
1372 llvm::None, llvm::None, llvm::None,
1373 llvm::None);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001374 // Emit barrier for firstprivates, lastprivates or reductions only if
1375 // 'sections' directive has 'nowait' clause. Otherwise the barrier will be
1376 // generated by the codegen for the directive.
1377 if ((HasFirstprivates || HasLastprivates || HasReductions) &&
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001378 S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001379 // Emit implicit barrier to synchronize threads and avoid data races on
1380 // initialization of firstprivate variables.
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001381 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_unknown);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001382 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001383 return OMPD_single;
1384}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001385
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001386void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1387 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev0f34da12015-07-02 04:17:07 +00001388 OpenMPDirectiveKind EmittedAs = EmitSections(S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001389 // Emit an implicit barrier at the end.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001390 if (!S.getSingleClause<OMPNowaitClause>()) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001391 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001392 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001393}
1394
1395void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001396 LexicalScope Scope(*this, S.getSourceRange());
1397 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1398 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1399 CGF.EnsureInsertPoint();
1400 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001401 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001402}
1403
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001404void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001405 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001406 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001407 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001408 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001409 // Check if there are any 'copyprivate' clauses associated with this
1410 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001411 // construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001412 // Build a list of copyprivate variables along with helper expressions
1413 // (<source>, <destination>, <destination>=<source> expressions)
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001414 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001415 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001416 DestExprs.append(C->destination_exprs().begin(),
1417 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001418 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001419 AssignmentOps.append(C->assignment_ops().begin(),
1420 C->assignment_ops().end());
1421 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001422 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001423 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev5521d782015-04-24 04:21:15 +00001424 bool HasFirstprivates;
1425 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) {
1426 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1427 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev59c654a2015-04-27 03:48:52 +00001428 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev5521d782015-04-24 04:21:15 +00001429 (void)SingleScope.Privatize();
1430
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001431 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1432 CGF.EnsureInsertPoint();
1433 };
1434 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001435 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001436 AssignmentOps);
Alexey Bataev5521d782015-04-24 04:21:15 +00001437 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1438 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001439 if ((!S.getSingleClause<OMPNowaitClause>() || HasFirstprivates) &&
Alexey Bataev5521d782015-04-24 04:21:15 +00001440 CopyprivateVars.empty()) {
1441 CGM.getOpenMPRuntime().emitBarrierCall(
1442 *this, S.getLocStart(),
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001443 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001444 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001445}
1446
Alexey Bataev8d690652014-12-04 07:23:53 +00001447void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001448 LexicalScope Scope(*this, S.getSourceRange());
1449 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1450 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1451 CGF.EnsureInsertPoint();
1452 };
1453 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001454}
1455
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001456void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001457 LexicalScope Scope(*this, S.getSourceRange());
1458 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1459 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1460 CGF.EnsureInsertPoint();
1461 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001462 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001463 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001464}
1465
Alexey Bataev671605e2015-04-13 05:28:11 +00001466void CodeGenFunction::EmitOMPParallelForDirective(
1467 const OMPParallelForDirective &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());
Alexey Bataev040d5402015-05-12 08:35:28 +00001471 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
Alexey Bataev671605e2015-04-13 05:28:11 +00001472 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_for, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001481}
1482
Alexander Musmane4e893b2014-09-23 09:33:00 +00001483void CodeGenFunction::EmitOMPParallelForSimdDirective(
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00001484 const OMPParallelForSimdDirective &S) {
1485 // Emit directive as a combined directive that consists of two implicit
1486 // directives: 'parallel' with 'for' directive.
1487 LexicalScope Scope(*this, S.getSourceRange());
1488 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
1489 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1490 CGF.EmitOMPWorksharingLoop(S);
1491 // Emit implicit barrier at the end of parallel region, but this barrier
1492 // is at the end of 'for' directive, so emit it as the implicit barrier for
1493 // this 'for' directive.
1494 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1495 OMPD_parallel);
1496 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001497 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001498}
1499
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001500void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001501 const OMPParallelSectionsDirective &S) {
1502 // Emit directive as a combined directive that consists of two implicit
1503 // directives: 'parallel' with 'sections' directive.
1504 LexicalScope Scope(*this, S.getSourceRange());
1505 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00001506 (void)CGF.EmitSections(S);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001507 // Emit implicit barrier at the end of parallel region.
1508 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1509 OMPD_parallel);
1510 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001511 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001512}
1513
Alexey Bataev62b63b12015-03-10 07:28:44 +00001514void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1515 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001516 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001517 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1518 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1519 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001520 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001521 // The first function argument for tasks is a thread id, the second one is a
1522 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001523 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
1524 // Get list of private variables.
1525 llvm::SmallVector<const Expr *, 8> PrivateVars;
1526 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001527 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001528 auto IRef = C->varlist_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 PrivateVars.push_back(*IRef);
1533 PrivateCopies.push_back(IInit);
1534 }
1535 ++IRef;
1536 }
1537 }
1538 EmittedAsPrivate.clear();
1539 // Get list of firstprivate variables.
1540 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
1541 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
1542 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001543 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001544 auto IRef = C->varlist_begin();
1545 auto IElemInitRef = C->inits().begin();
1546 for (auto *IInit : C->private_copies()) {
1547 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1548 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1549 FirstprivateVars.push_back(*IRef);
1550 FirstprivateCopies.push_back(IInit);
1551 FirstprivateInits.push_back(*IElemInitRef);
1552 }
1553 ++IRef, ++IElemInitRef;
1554 }
1555 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001556 // Build list of dependences.
1557 llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8>
1558 Dependences;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001559 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001560 for (auto *IRef : C->varlists()) {
1561 Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
1562 }
1563 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001564 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
1565 CodeGenFunction &CGF) {
1566 // Set proper addresses for generated private copies.
1567 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
1568 OMPPrivateScope Scope(CGF);
1569 if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00001570 auto *CopyFn = CGF.Builder.CreateLoad(
1571 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
1572 auto *PrivatesPtr = CGF.Builder.CreateLoad(
1573 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001574 // Map privates.
John McCall7f416cc2015-09-08 08:05:57 +00001575 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16>
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001576 PrivatePtrs;
1577 llvm::SmallVector<llvm::Value *, 16> CallArgs;
1578 CallArgs.push_back(PrivatesPtr);
1579 for (auto *E : PrivateVars) {
1580 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001581 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001582 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
1583 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00001584 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001585 }
1586 for (auto *E : FirstprivateVars) {
1587 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00001588 Address PrivatePtr =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001589 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
1590 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
John McCall7f416cc2015-09-08 08:05:57 +00001591 CallArgs.push_back(PrivatePtr.getPointer());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001592 }
1593 CGF.EmitRuntimeCall(CopyFn, CallArgs);
1594 for (auto &&Pair : PrivatePtrs) {
John McCall7f416cc2015-09-08 08:05:57 +00001595 Address Replacement(CGF.Builder.CreateLoad(Pair.second),
1596 CGF.getContext().getDeclAlign(Pair.first));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001597 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
1598 }
1599 }
1600 (void)Scope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001601 if (*PartId) {
1602 // TODO: emit code for untied tasks.
1603 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001604 CGF.EmitStmt(CS->getCapturedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001605 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001606 auto OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
1607 S, *I, OMPD_task, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001608 // Check if we should emit tied or untied task.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001609 bool Tied = !S.getSingleClause<OMPUntiedClause>();
Alexey Bataev62b63b12015-03-10 07:28:44 +00001610 // Check if the task is final
1611 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001612 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001613 // If the condition constant folds and can be elided, try to avoid emitting
1614 // the condition and the dead arm of the if/else.
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001615 auto *Cond = Clause->getCondition();
Alexey Bataev62b63b12015-03-10 07:28:44 +00001616 bool CondConstant;
1617 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1618 Final.setInt(CondConstant);
1619 else
1620 Final.setPointer(EvaluateExprAsBool(Cond));
1621 } else {
1622 // By default the task is not final.
1623 Final.setInt(/*IntVal=*/false);
1624 }
1625 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00001626 const Expr *IfCond = nullptr;
Alexey Bataev7371aa32015-09-03 08:45:56 +00001627 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1628 if (C->getNameModifier() == OMPD_unknown ||
1629 C->getNameModifier() == OMPD_task) {
1630 IfCond = C->getCondition();
1631 break;
1632 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001633 }
Alexey Bataev9e034042015-05-05 04:05:12 +00001634 CGM.getOpenMPRuntime().emitTaskCall(
1635 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001636 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001637 FirstprivateCopies, FirstprivateInits, Dependences);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001638}
1639
Alexey Bataev9f797f32015-02-05 05:57:51 +00001640void CodeGenFunction::EmitOMPTaskyieldDirective(
1641 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001642 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001643}
1644
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001645void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001646 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001647}
1648
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001649void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
1650 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00001651}
1652
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001653void CodeGenFunction::EmitOMPTaskgroupDirective(
1654 const OMPTaskgroupDirective &S) {
1655 LexicalScope Scope(*this, S.getSourceRange());
1656 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1657 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1658 CGF.EnsureInsertPoint();
1659 };
1660 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
1661}
1662
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001663void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001664 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00001665 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001666 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1667 FlushClause->varlist_end());
1668 }
1669 return llvm::None;
1670 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00001671}
1672
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001673void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
1674 LexicalScope Scope(*this, S.getSourceRange());
1675 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1676 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1677 CGF.EnsureInsertPoint();
1678 };
1679 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001680}
1681
Alexey Bataevb57056f2015-01-22 06:17:56 +00001682static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001683 QualType SrcType, QualType DestType,
1684 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001685 assert(CGF.hasScalarEvaluationKind(DestType) &&
1686 "DestType must have scalar evaluation kind.");
1687 assert(!Val.isAggregate() && "Must be a scalar or complex.");
1688 return Val.isScalar()
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001689 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
1690 Loc)
Alexey Bataevb57056f2015-01-22 06:17:56 +00001691 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001692 DestType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001693}
1694
1695static CodeGenFunction::ComplexPairTy
1696convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001697 QualType DestType, SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001698 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
1699 "DestType must have complex evaluation kind.");
1700 CodeGenFunction::ComplexPairTy ComplexVal;
1701 if (Val.isScalar()) {
1702 // Convert the input element to the element type of the complex.
1703 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001704 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
1705 DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001706 ComplexVal = CodeGenFunction::ComplexPairTy(
1707 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
1708 } else {
1709 assert(Val.isComplex() && "Must be a scalar or complex.");
1710 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
1711 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1712 ComplexVal.first = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001713 Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001714 ComplexVal.second = CGF.EmitScalarConversion(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001715 Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001716 }
1717 return ComplexVal;
1718}
1719
Alexey Bataev5e018f92015-04-23 06:35:10 +00001720static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
1721 LValue LVal, RValue RVal) {
1722 if (LVal.isGlobalReg()) {
1723 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
1724 } else {
1725 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
1726 : llvm::Monotonic,
1727 LVal.isVolatile(), /*IsInit=*/false);
1728 }
1729}
1730
1731static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001732 QualType RValTy, SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00001733 switch (CGF.getEvaluationKind(LVal.getType())) {
1734 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001735 CGF.EmitStoreThroughLValue(RValue::get(convertToScalarValue(
1736 CGF, RVal, RValTy, LVal.getType(), Loc)),
1737 LVal);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001738 break;
1739 case TEK_Complex:
1740 CGF.EmitStoreOfComplex(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001741 convertToComplexValue(CGF, RVal, RValTy, LVal.getType(), Loc), LVal,
Alexey Bataev5e018f92015-04-23 06:35:10 +00001742 /*isInit=*/false);
1743 break;
1744 case TEK_Aggregate:
1745 llvm_unreachable("Must be a scalar or complex.");
1746 }
1747}
1748
Alexey Bataevb57056f2015-01-22 06:17:56 +00001749static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
1750 const Expr *X, const Expr *V,
1751 SourceLocation Loc) {
1752 // v = x;
1753 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
1754 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
1755 LValue XLValue = CGF.EmitLValue(X);
1756 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00001757 RValue Res = XLValue.isGlobalReg()
1758 ? CGF.EmitLoadOfLValue(XLValue, Loc)
1759 : CGF.EmitAtomicLoad(XLValue, Loc,
1760 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00001761 : llvm::Monotonic,
1762 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +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)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001768 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001769 emitSimpleStore(CGF, VLValue, Res, X->getType().getNonReferenceType(), Loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001770}
1771
Alexey Bataevb8329262015-02-27 06:33:30 +00001772static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
1773 const Expr *X, const Expr *E,
1774 SourceLocation Loc) {
1775 // x = expr;
1776 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00001777 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00001778 // OpenMP, 2.12.6, atomic Construct
1779 // Any atomic construct with a seq_cst clause forces the atomically
1780 // performed operation to include an implicit flush operation without a
1781 // list.
1782 if (IsSeqCst)
1783 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1784}
1785
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00001786static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
1787 RValue Update,
1788 BinaryOperatorKind BO,
1789 llvm::AtomicOrdering AO,
1790 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001791 auto &Context = CGF.CGM.getContext();
1792 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00001793 // expression is simple and atomic is allowed for the given type for the
1794 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001795 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00001796 !Update.getScalarVal()->getType()->isIntegerTy() ||
1797 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
1798 (Update.getScalarVal()->getType() !=
John McCall7f416cc2015-09-08 08:05:57 +00001799 X.getAddress().getElementType())) ||
1800 !X.getAddress().getElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001801 !Context.getTargetInfo().hasBuiltinAtomic(
1802 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00001803 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001804
1805 llvm::AtomicRMWInst::BinOp RMWOp;
1806 switch (BO) {
1807 case BO_Add:
1808 RMWOp = llvm::AtomicRMWInst::Add;
1809 break;
1810 case BO_Sub:
1811 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00001812 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001813 RMWOp = llvm::AtomicRMWInst::Sub;
1814 break;
1815 case BO_And:
1816 RMWOp = llvm::AtomicRMWInst::And;
1817 break;
1818 case BO_Or:
1819 RMWOp = llvm::AtomicRMWInst::Or;
1820 break;
1821 case BO_Xor:
1822 RMWOp = llvm::AtomicRMWInst::Xor;
1823 break;
1824 case BO_LT:
1825 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1826 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
1827 : llvm::AtomicRMWInst::Max)
1828 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
1829 : llvm::AtomicRMWInst::UMax);
1830 break;
1831 case BO_GT:
1832 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1833 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
1834 : llvm::AtomicRMWInst::Min)
1835 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
1836 : llvm::AtomicRMWInst::UMin);
1837 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001838 case BO_Assign:
1839 RMWOp = llvm::AtomicRMWInst::Xchg;
1840 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001841 case BO_Mul:
1842 case BO_Div:
1843 case BO_Rem:
1844 case BO_Shl:
1845 case BO_Shr:
1846 case BO_LAnd:
1847 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001848 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001849 case BO_PtrMemD:
1850 case BO_PtrMemI:
1851 case BO_LE:
1852 case BO_GE:
1853 case BO_EQ:
1854 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001855 case BO_AddAssign:
1856 case BO_SubAssign:
1857 case BO_AndAssign:
1858 case BO_OrAssign:
1859 case BO_XorAssign:
1860 case BO_MulAssign:
1861 case BO_DivAssign:
1862 case BO_RemAssign:
1863 case BO_ShlAssign:
1864 case BO_ShrAssign:
1865 case BO_Comma:
1866 llvm_unreachable("Unsupported atomic update operation");
1867 }
1868 auto *UpdateVal = Update.getScalarVal();
1869 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
1870 UpdateVal = CGF.Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00001871 IC, X.getAddress().getElementType(),
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001872 X.getType()->hasSignedIntegerRepresentation());
1873 }
John McCall7f416cc2015-09-08 08:05:57 +00001874 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001875 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001876}
1877
Alexey Bataev5e018f92015-04-23 06:35:10 +00001878std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001879 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
1880 llvm::AtomicOrdering AO, SourceLocation Loc,
1881 const llvm::function_ref<RValue(RValue)> &CommonGen) {
1882 // Update expressions are allowed to have the following forms:
1883 // x binop= expr; -> xrval + expr;
1884 // x++, ++x -> xrval + 1;
1885 // x--, --x -> xrval - 1;
1886 // x = x binop expr; -> xrval binop expr
1887 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001888 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
1889 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001890 if (X.isGlobalReg()) {
1891 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
1892 // 'xrval'.
1893 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
1894 } else {
1895 // Perform compare-and-swap procedure.
1896 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00001897 }
1898 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001899 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001900}
1901
1902static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
1903 const Expr *X, const Expr *E,
1904 const Expr *UE, bool IsXLHSInRHSPart,
1905 SourceLocation Loc) {
1906 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1907 "Update expr in 'atomic update' must be a binary operator.");
1908 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1909 // Update expressions are allowed to have the following forms:
1910 // x binop= expr; -> xrval + expr;
1911 // x++, ++x -> xrval + 1;
1912 // x--, --x -> xrval - 1;
1913 // x = x binop expr; -> xrval binop expr
1914 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001915 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00001916 LValue XLValue = CGF.EmitLValue(X);
1917 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001918 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001919 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1920 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1921 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1922 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1923 auto Gen =
1924 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
1925 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1926 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1927 return CGF.EmitAnyExpr(UE);
1928 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00001929 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
1930 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1931 // OpenMP, 2.12.6, atomic Construct
1932 // Any atomic construct with a seq_cst clause forces the atomically
1933 // performed operation to include an implicit flush operation without a
1934 // list.
1935 if (IsSeqCst)
1936 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1937}
1938
1939static RValue convertToType(CodeGenFunction &CGF, RValue Value,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001940 QualType SourceType, QualType ResType,
1941 SourceLocation Loc) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00001942 switch (CGF.getEvaluationKind(ResType)) {
1943 case TEK_Scalar:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001944 return RValue::get(
1945 convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
Alexey Bataev5e018f92015-04-23 06:35:10 +00001946 case TEK_Complex: {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001947 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001948 return RValue::getComplex(Res.first, Res.second);
1949 }
1950 case TEK_Aggregate:
1951 break;
1952 }
1953 llvm_unreachable("Must be a scalar or complex.");
1954}
1955
1956static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
1957 bool IsPostfixUpdate, const Expr *V,
1958 const Expr *X, const Expr *E,
1959 const Expr *UE, bool IsXLHSInRHSPart,
1960 SourceLocation Loc) {
1961 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
1962 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
1963 RValue NewVVal;
1964 LValue VLValue = CGF.EmitLValue(V);
1965 LValue XLValue = CGF.EmitLValue(X);
1966 RValue ExprRValue = CGF.EmitAnyExpr(E);
1967 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
1968 QualType NewVValType;
1969 if (UE) {
1970 // 'x' is updated with some additional value.
1971 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1972 "Update expr in 'atomic capture' must be a binary operator.");
1973 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1974 // Update expressions are allowed to have the following forms:
1975 // x binop= expr; -> xrval + expr;
1976 // x++, ++x -> xrval + 1;
1977 // x--, --x -> xrval - 1;
1978 // x = x binop expr; -> xrval binop expr
1979 // x = expr Op x; - > expr binop xrval;
1980 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1981 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1982 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1983 NewVValType = XRValExpr->getType();
1984 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1985 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
1986 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
1987 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1988 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1989 RValue Res = CGF.EmitAnyExpr(UE);
1990 NewVVal = IsPostfixUpdate ? XRValue : Res;
1991 return Res;
1992 };
1993 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1994 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1995 if (Res.first) {
1996 // 'atomicrmw' instruction was generated.
1997 if (IsPostfixUpdate) {
1998 // Use old value from 'atomicrmw'.
1999 NewVVal = Res.second;
2000 } else {
2001 // 'atomicrmw' does not provide new value, so evaluate it using old
2002 // value of 'x'.
2003 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2004 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
2005 NewVVal = CGF.EmitAnyExpr(UE);
2006 }
2007 }
2008 } else {
2009 // 'x' is simply rewritten with some 'expr'.
2010 NewVValType = X->getType().getNonReferenceType();
2011 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002012 X->getType().getNonReferenceType(), Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002013 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
2014 NewVVal = XRValue;
2015 return ExprRValue;
2016 };
2017 // Try to perform atomicrmw xchg, otherwise simple exchange.
2018 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2019 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
2020 Loc, Gen);
2021 if (Res.first) {
2022 // 'atomicrmw' instruction was generated.
2023 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2024 }
2025 }
2026 // Emit post-update store to 'v' of old/new 'x' value.
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002027 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType, Loc);
Alexey Bataevb4505a72015-03-30 05:20:59 +00002028 // OpenMP, 2.12.6, atomic Construct
2029 // Any atomic construct with a seq_cst clause forces the atomically
2030 // performed operation to include an implicit flush operation without a
2031 // list.
2032 if (IsSeqCst)
2033 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2034}
2035
Alexey Bataevb57056f2015-01-22 06:17:56 +00002036static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00002037 bool IsSeqCst, bool IsPostfixUpdate,
2038 const Expr *X, const Expr *V, const Expr *E,
2039 const Expr *UE, bool IsXLHSInRHSPart,
2040 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002041 switch (Kind) {
2042 case OMPC_read:
2043 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
2044 break;
2045 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00002046 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
2047 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00002048 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002049 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00002050 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2051 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002052 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00002053 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2054 IsXLHSInRHSPart, Loc);
2055 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00002056 case OMPC_if:
2057 case OMPC_final:
2058 case OMPC_num_threads:
2059 case OMPC_private:
2060 case OMPC_firstprivate:
2061 case OMPC_lastprivate:
2062 case OMPC_reduction:
2063 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00002064 case OMPC_simdlen:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002065 case OMPC_collapse:
2066 case OMPC_default:
2067 case OMPC_seq_cst:
2068 case OMPC_shared:
2069 case OMPC_linear:
2070 case OMPC_aligned:
2071 case OMPC_copyin:
2072 case OMPC_copyprivate:
2073 case OMPC_flush:
2074 case OMPC_proc_bind:
2075 case OMPC_schedule:
2076 case OMPC_ordered:
2077 case OMPC_nowait:
2078 case OMPC_untied:
2079 case OMPC_threadprivate:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002080 case OMPC_depend:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002081 case OMPC_mergeable:
Michael Wonge710d542015-08-07 16:16:36 +00002082 case OMPC_device:
Alexey Bataevb57056f2015-01-22 06:17:56 +00002083 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2084 }
2085}
2086
2087void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00002088 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
Alexey Bataevb57056f2015-01-22 06:17:56 +00002089 OpenMPClauseKind Kind = OMPC_unknown;
2090 for (auto *C : S.clauses()) {
2091 // Find first clause (skip seq_cst clause, if it is first).
2092 if (C->getClauseKind() != OMPC_seq_cst) {
2093 Kind = C->getClauseKind();
2094 break;
2095 }
2096 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002097
2098 const auto *CS =
2099 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002100 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00002101 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00002102 }
2103 // Processing for statements under 'atomic capture'.
2104 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2105 for (const auto *C : Compound->body()) {
2106 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2107 enterFullExpression(EWC);
2108 }
2109 }
2110 }
Alexey Bataev10fec572015-03-11 04:48:56 +00002111
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002112 LexicalScope Scope(*this, S.getSourceRange());
2113 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00002114 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2115 S.getV(), S.getExpr(), S.getUpdateExpr(),
2116 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002117 };
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002118 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00002119}
2120
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002121void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) {
2122 llvm_unreachable("CodeGen for 'omp target' is not supported yet.");
2123}
2124
Alexey Bataev13314bf2014-10-09 04:18:56 +00002125void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
2126 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
2127}
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002128
2129void CodeGenFunction::EmitOMPCancellationPointDirective(
2130 const OMPCancellationPointDirective &S) {
Alexey Bataev0f34da12015-07-02 04:17:07 +00002131 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
2132 S.getCancelRegion());
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002133}
2134
Alexey Bataev80909872015-07-02 11:25:17 +00002135void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002136 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(),
2137 S.getCancelRegion());
Alexey Bataev80909872015-07-02 11:25:17 +00002138}
2139
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002140CodeGenFunction::JumpDest
2141CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
2142 if (Kind == OMPD_parallel || Kind == OMPD_task)
2143 return ReturnBlock;
2144 else if (Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections)
2145 return BreakContinueStack.empty() ? JumpDest()
2146 : BreakContinueStack.back().BreakBlock;
2147 return JumpDest();
2148}
Michael Wong65f367f2015-07-21 13:44:28 +00002149
2150// Generate the instructions for '#pragma omp target data' directive.
2151void CodeGenFunction::EmitOMPTargetDataDirective(
2152 const OMPTargetDataDirective &S) {
2153
2154 // emit the code inside the construct for now
2155 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Michael Wongb5c16982015-08-11 04:52:01 +00002156 CGM.getOpenMPRuntime().emitInlinedDirective(
2157 *this, OMPD_target_data,
2158 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
Michael Wong65f367f2015-07-21 13:44:28 +00002159}